rails 3.2.9 jquery_ujs not working with link_to

Question: I've have at least the following links that don't work
= link_to 'Delete', admin_picture_comment_path(comment.picture_id,comment.id), :class => 'delete', :remote => true ,:method => :delete

= link_to 'Disable', set_shown_admin_picture_path(picture), :class => 'delete', :method => :put, :remote => true

= link_to 'show', set_show_admin_picture_path(picture), :class => 'delete', :method => :put, :remote => true

= link_to 'delete', admin_picture_path(picture), :confirm => 'Are you sure?', :class => 'delete', :method => :delete, :remote => true

The HTML that is being created looks correct
Delete

Disable

In all cases I get back something that like
No route matches [GET] "/admin/pictures/27/comments/23"
I assume this is because the jquery_ujs is not loading correctly, however I have no idea why it's not loading as it shows up in the html header

Routes.rb
namespace :admin do
  #...
  resources :pictures do # admin/pictures
    member do
      put 'set_show'
      put 'set_shown'
    end
    resources :comments, :only => [:destroy]
  end
end

application.html.haml
%html
  %head
    %title title
    = stylesheet_link_tag :application
    = javascript_include_tag :application
    = csrf_meta_tag

application.js
//= require jquery
//= require jquery_ujs
//= require jquery.fileupload
//= require jquery.fileupload-ui
//= require jquery.lightbox

$(function(){

  $('.admin_picture a.delete').live('ajax:success',function(){
    $(this).closest('.admin_picture').fadeOut();
  });

  $('tr .ajax_delete').live('ajax:success', function() {
    $(this).closest('tr').fadeOut();
  });

  $('.comment a.delete').live('ajax:success',function(){
    $(this).closest('.comment').slideUp();
  });

  //...

});

gemfile
gem 'rails', '3.2.9'
gem 'thin'
gem 'jquery-rails'
gem 'haml-rails'
#...

I ran into this error while upgrading from a rails 3.0 application that was using unobtrusive jquery, what could I possibly be missing that would cause this.
Comment: Do you see an error in your javascript console (in the browser developer tools)? Because if you have some javascript error on your page, your javascript could just stop working.
Comment: No javascript errors that I can see.
Comment: Turns out it was a javascript error. It wasn't showing up as a javascript error because under settings >> console , "Perserve log upon navigation" was unchecked.
Answer: specifically, my jquery_ujs file was old and still "living" in my assets/javascript directory.  It still had .live methods which are deprecated.  Delete the file!!
Keep the gem 'jquery-rails', '~> 2.1'  # REF: https://github.com/rails/jquery-ujs
Keep the     //= require jquery and //= require jquery_ujs and //= require_tree .
In your application.js file
Make sure you update the gem and bundle install to get the latest gem.
If a javascript error is thrown as was the "sneaky" case for me, the rest of link_to js will not work.
Comment: I would not recommend the "Delete the Gemfile.lock", you can just call `bundle update jquery-rails` to update the lock file


Writing recursive template haskell functions

Question: Is it possible to transform a recursive TH function into an equivalent form which will compile? The following definition doesn't work, because in order to compile fact you must first compile fact.
fact :: ExpQ -> ExpQ
fact n = [|
    case $n of
      1 -> 1
      _ -> $n * $(fact [| $n - 1 |]) |]

This simple example is easily solved (fact n = [| product [ 1.. $n] |]) but in the general case, if it is not possible to rewrite a given function as a loop, can a recursive TH function be defined? Is there even a single example for which this doable?
To clarify for future readers: this question is specifically about writing recursive TH functions - not about 'how do I splice the factorial function'.
The answer to my question turned out to be remarkably simple:
{-# LANGUAGE TemplateHaskell #-}

import Control.Monad.Fix (fix)
import Language.Haskell.TH

fact = [| \f x -> $([|
     case x of
       1 -> 1
       _ -> f $([| x - 1 |]) * x  |]) |]

factorial = [| fix $fact |]

fact can be compiled because it is no longer recursive, and [| fix $fact |] is compiled at a later time, so no more infinite recursive definitions.
This version of fact looks slightly different than the original, but you can write the new fact exactly as the old one and transform it later:
fact' recurse n = [|
        case $n of
          1 -> 1
          _ -> $n * $(recurse [| $n - 1 |]) |]

fact = [| \x -> $((\f -> [| \x -> $(fact (\x -> [| $f $x |]) [| x |]) |]) [| x |]) |]

Answer: The fundamental problem with your code is not that it is recursive, but that it doesn't terminate. The n argument to fact just keeps getting bigger and bigger because [| $n - 1 ]| is an expression tree representing the operation (-) applied to n and 1.
Any non-terminating splice will hang the compiler in just the same way, for example the following behaves just like your fact when spliced:
broken :: ExpQ -> ExpQ
broken n = return $ LitE (IntegerL (fromIntegral (length [1..])))

A recursive function where the recursion is guaranteed to bottom out is guaranteed to terminate and works fine for appropriate inputs:
fact1 :: ExpQ -> ExpQ
fact1 n = do
    nBody <- n
    case nBody of
      LitE (IntegerL 1) -> [|1|]
      LitE (IntegerL nInt) | nInt > 1 ->
          let nMinusOne = return $ LitE (IntegerL (nInt-1))
          in [| $n * $(fact1 nMinusOne) |]

but of course it fails if the input isn't an appropriate integer literal.
You can also shift the recursion to runtime, so that instead of the recursive call being with an ever-bigger expression tree, it's with the runtime evaluated and shrinking Int:
fact2 :: ExpQ -> ExpQ
fact2 n =
   [|
    let factImpl n =
         case n of
          1 -> 1
          _ -> n * factImpl (n-1)
    in factImpl $n
   |]

Of course in this code we're not doing any analysis of the structure of n. But we can put it together with fact1 to get a version that is compile-time executed in some cases and defers others to runtime:
fact3 :: ExpQ -> ExpQ
fact3 n = do
    nBody <- n
    case nBody of
      LitE (IntegerL 1) -> [|1|]
      LitE (IntegerL nInt) ->
          let nMinusOne = return $ LitE (IntegerL (nInt-1))
          in [| $n * $(fact3 nMinusOne) |]
      _ -> [|
            let factImpl n =
                  case n of
                    1 -> 1
                    _ -> n * factImpl (n-1)
            in factImpl $n
           |]

Ultimately in your real code, you will need to apply some combination of these techniques - make sure that your compile-time recursion terminates and defer any remaining cases to runtime evaluation somehow.
Comment: You are just splicing the entire `fact` function. If this were the goal, I could write my code without any use of TH at all. With this approach, I can't perform any manipulations using TH within the function, because the inner `n` cannot escape its scope.
Comment: The point applies in general though - you need to transform your code so that the recursion is at runtime, using tricks like this. If your recursion won't bottom out at compile-time, your code can't work.
Comment: I added an example of doing recursion that does terminate on the TH expression, to illustrate that your problem is non-termination, not recursion itself.
Comment: The second function you added only works on literals - sort of redundant, if my function can't even be applied to variables, providing an even weaker form of the first function.
Comment: It's just to illustrate that terminating recursion is ok. As I said, your problem is that your recursion doesn't terminate, nothing else.
Comment: I reorganised my post to present the options more clearly and added a 'hybrid' version.
Comment: I'll accept your answer, even though it doesn't answer my question, because my question was quite poorly worded.
Answer: Yes, you can by using the following:
fact :: Int -> ExpQ
fact 0 = [| 1 |]
fact n = [| $(lift n) * $(fact $ n - 1) |]

lift is a function inside Language.Haskell.TH.Lift which converts a basic haskell values into template haskell values (eg Int to ExpQ).
Note that you don't need the case code to be generated, as you know the number at compile time. The above macro will expand to a series of multiplications. Eg $(fact 4) will expand to 4*3*2*1.
Note that in this case, you can do much better though. A template haskell expression is run at compile time, so a template haskell fact function can just return the literal value it represents. Eg $(fact 4) can return 24 (instead of 4*3*2*1). This can be done with the following code:
fact2 :: Int -> ExpQ
fact2 n = lift (product [1..n])

Comment: @user2407038 : Template Haskell is a compile-time pass.  If the input isn't known at compile time, you'll need to use the GHC Api or similar to dynamically compile code at run-time.  This sort of thing is possible now (http://johnlato.blogspot.com/2012/10/runtime-meta-programming-in-haskell.html), but will be better soon (http://gmainland.blogspot.com/2013/05/type-safe-runtime-code-generation-with.html)
Comment: What gave the impression that the input would be known at compile time? This is not the case at all, which is why my example function takes a `Q Exp` arguement and not `Int`.
Comment: Well if the input isn't known at compile time, what value are you giving for the `n` parameter when you are using the macro? If you want to just write a template haskell function that expands to the definition of a factorial function, you want the macro to have the type `Q Exp`, not `Q Exp -> Q Exp`.
Comment: My function of type `Q Exp -> Q Exp` can be converted very easily to just `Q Exp` (`\f -> [| \x -> $(f [| x |]) |]`); they are isomorphic. I am indeed trying to splice a function and not a value. @JohnL Typed TH would certainly be extremely useful! But I don't believe it is really relevant to the problem at hand.
Comment: @user2407038: I'm a bit confused about your last comment, as `Q Exp` and `Q Exp -> Q Exp` do not appear isomorphic to me (and neither does your example code). Can you give a code example as to how you would use the `fact` macro? Maybe that will clear up some confusion.
Comment: @user2407038: I agree typed TH isn't helpful for the problem at hand.  My point is, if you want to have a TH splice depend on a runtime value, you'll need to jump through some hoops.
Comment: The function I included in my last comment (namely `\f -> [| \x -> $(f [| x |]) |]`) converts `Q Exp -> Q Exp` to `Q Exp` by bringing the parameter into the splice. @JohnL Yes, it looks like I will, but it feels as if there should be a simple solution.


mocking the request module with sinon

Question: I want to mock the following piece of code using sinon,
<code>  request(options, function(error, response) {
    if (error) {
      reject(error);
    } else {
      resolve(response);
    }
  });
</code>
can you help me with this ?
Answer: Assuming it as a get request,
<code>let request = require('request') // request module.
let options = "some url" // mock data for url
requestStub = sinon.stub(request, 'get').callsArgsWith(0, options);// first argument of request call is options.
requestStub.yields(error, response)//It returns error and response. These will be mock data
sinon.assert.calledOnce(requestStub)//Test to check whether stub is called or not.
requestStub.restore(); // need to restore stub every time after use.
</code>
So depending upon what error and response you pass, it will return output accordingly.

mocking the request module with sinon


Proof that a statistic is complete

Question: I need some help with this exercise:
The density function of the random variable $X_i$ is:
\begin{equation*}
f_\theta(x)=\exp(\theta-x)1_{[\theta,\infty)}(x)
\end{equation*}
The maximum likelihood function is:
\begin{equation*}
L(x,\theta)=\prod_{i=1}^n\exp(\theta-x_i)1_{[\theta,\infty)}(x_i)=exp\bigg(n\theta-\sum_{i=1}^n x_i\bigg)1_{[0,\min\{X_1,...,X_n\}]}(\theta)
\end{equation*}
And its (unique) maximum is attended for $\hat\theta_{ML}=\min\{X_1,...,X_n\}$.
I find that the statistic $Y=\min\{X_1,...,X_n\}$ is sufficient using the factorization theorem and I now have to prove that it is also complete.
First of all I've calculated the density of $Y$ which is:
\begin{equation*}
g_\theta(x)= n\exp(n\theta-nx)
\end{equation*}
Then for the definition of complete statistic I have to prove that :
\begin{equation*}
E_\theta(h(Y))=0 \Rightarrow h=0
\end{equation*}
and this implies that:
\begin{equation*}
E_\theta(h(Y))=\int_\theta^\infty h(y)n\exp(n\theta-ny)dy=0
\end{equation*}
How can I conclude from the last expression that $h(y)$ has to be zero $\forall y$
Comment: https://math.stackexchange.com/q/3315327/321264
Answer: $f(\theta)=\int_\theta^\infty h(y)e^{-ny}dy$ is identically zero $\forall\theta>0$.
$\implies f'(\theta)=-h(\theta)e^{-n\theta}=0$ which gives $h(\theta)=0$ over $\Bbb R^+$ so $P_\theta[h(x)=0]=1$.

Proof that a statistic is complete


divergence between nls (simple power equation) on non-transformed data and lm on log transformed data in R

Question: I'm testing different ways to fit a simple power model to a dataset of 5 points.
I don't get same results if I use nls on non-transformed data or lm on log10 transformed data in R whereas Excel gives exactly the same results (it's power fitting might be a hidden linear fitting on log transformed data).
Here is an example of the code I'm using:
# data
r <- c(0.0778,0.0429,0.0320,0.0216,0.0148)
t <- c(4,10,40,100,400)
df <- data.frame(r,t)
df$log.r <- log10(df$r)
df$log.t <- log10(df$t)

# models
m1 <- nls(r ~ m * t^(-n), data=df, start=list(m=1, n=0.5))
m2 <- lm(log.r ~ log.t, data=df)

# simulate data
t.range <- seq(1, 1000, length.out=30000)
r.pred1 <- predict(m1, newdata=data.frame(t=t.range))
p1 <- data.frame(t=t.range, r=r.pred1)

log.t.range <- log10(t.range)
r.pred2 <- predict(m2, newdata=data.frame(log.t=log.t.range))
p2 <- data.frame(log.t=log.t.range, log.r=r.pred2)

# plot results
p1$log.r <- log10(p1$r)
p1$log.t <- log10(p1$t)
library(ggplot2)
ggplot(df, aes(x=log.t, y=log.r))+
  geom_line(data=p1, color="red")+
  geom_line(data=p2, color="blue", linetype="dashed")+
  geom_point()+
  ggtitle("red: nls on non-transformed data\ndashed blue: lm on log10 transformed data")+
  theme_bw()

Thus, some questions:

Which method (nls vs lm) would be the "best" in this case using R?
Am I missing something in the use of nls?
Could this be due to the small number of points (only 5) I'm trying to fit?
Comment: See [here](http://stats.stackexchange.com/questions/71096/linear-regression-and-prediction-on-transformed-data/71097#71097) and [here](http://stats.stackexchange.com/questions/61600/strange-outcome-when-performing-nonlinear-least-squares-fit-to-a-power-law).
Answer: Your model:
$y=ax^{-n}+\epsilon$
Note how I include the error term $\epsilon$. Usually you make some assumptions about the error term (for statistical inference).
Now the log-transformed model:
$\log(y)=\log(ax^{-n}+\epsilon)$
There is no way to simplify this.
With lm you use this model:
$\log(y)=\log(ax^{-n})+\epsilon=\log(a)-n\log(x)+\epsilon$
This is not a transformation of the original model and will give different parameter estimates.
So, what should you use? It depends on your data, i.e., the expected error structure.


How do I assign names to devices on a LAN?

Question: I have a relatively small LAN containing a mixture of Mac, Windows and Linux devices. They currently all receive their IP address (fixed against MAC addresses) through DHCP and the DHCP server is also the router and default gateway. The subnet is 192.168.3.0 with a subnet mask of 255.255.255.0. For example:

default gateway: 192.168.3.254
Mac1: 192.168.3.1
Windows1: 192.168.3.2
Windows2: 192.168.3.3
Linux1: 192.168.3.4
Linux2: 192.168.3.5

I would like to be able to refer to different machines using a name rather than an IP address. For example, when ssh'ing from one Linux machine to another. If it's relevant, I don't have a company domain, etc.
What approaches can I take to achieve this?
Answer: For a network this small I'd just use

/etc/hosts (on Linux and OSX), or
c:\windows\system32\drivers\etc\hosts (on Windows).

If the network were to get much bigger I'd deploy dhcpd and named on one of the Linux boxes and stop using the router as the DHCP and DNS server.
Comment: I think that dnsmasq would serve fine for a small network and it is easier to configure than dhcpd and named.
Comment: quite possibly, but it's not a standard package on all Linux distros.  Nor would it support DNSSEC.
Comment: /etc/hosts doesn't work on OS X(at least on 10.3. Maybe it's updated since?): # Note that this file is consulted when the system is running in single-user # mode. At other times this information is handled by lookupd. By default, # lookupd gets information from NetInfo, so this file will not be consulted # unless you have changed lookupd's configuration
Comment: it works fine on my 10.5 systems
Answer: Hmm, you should be able to have your dhcp clients to send a 'hostname' along with their dhcp request. If your dhcp server is configured correctly, or if it is the same as your dns server (ala dnsmasq), you will be able to refer to your machine using the 'hostname' that they sent along with their request.
Alternately, you could always assign some static IP addresses to be dished out by the DHCP server and configure these things in your DNS server as well. If you are using dnsmasq this is trivial.
Answer: I'm assuming this is a consumer router? You could think about installing OpenWRT or DD-WRT on your router if it is supported and running dnsmasq or a more complicated named/dhcpd setup.
You can do other cools things like run an OpenVPN server/Bit torrent/etc/ on your router as well.


Is there a formula for finding the nth number in a sequence with a changing pattern

Question: If a sequence has a pattern where +2 is the pattern at the start, but 1 is added each time, like the sequence below, is there a formula to find the 125th number in this sequence? It would also need to work with patterns similar to this. For example if the pattern started as +4, and 5 was added each time.

2, 4, 7, 11, 16, 22 ...
Comment: you can read arithmetic progression (AP) or arithmetic sequence you get your answer .
Comment: $\sum_{n=1}^N n = N(N+1)/2$ you already saw that, no ?
Comment: The term "changing pattern" you use is confusing. If a pattern changes all the time, it is no longer a pattern. However what you have here is a perfectly constant patterns, it is just a bit more complicated than the pattern of always adding the same number.
Comment: Isn't arithmetic progression only when the difference in the numbers in a sequence is constant? Other math site seem to explain it that way, [like this one.](https://www.math10.com/en/algebra/arithmetic-progression.html) Thank you so much though!
Comment: @MarcvanLeeuwen Thank you, you're right! Sorry I couldn't think of how to describe it, and without making the title humongous lol
Comment: @user1952009 Yes I couldn't think of a way to use that when the difference between the numbers in a sequence changes each time.
Answer: When you have a polynomial expressed as a sequence, you can find it by taking differences
$$ \begin {array} {l l l l l l} 2&4&7&11&16&22\\2&3&4&5&6\\1&1&1&1 \end {array}$$
where the first line is your sequence and subsequent entries are the difference between the one up and to the right and the one above.  The fact that the second differences are constant says you have a second power polynomial.  To get the leading term, you take the constant in the second line and divide it by $2!$, so your polynomial starts with $\frac 12n^2$.  You can subtract that off and get a linear polynomial, which will be constant in the first line down.  Another approach is (once you have concluded that it is quadratic) $A(n)=an^2+bn+c$, take the first three terms as data, and solve the equations for $a,b,c$.  You can combine these by noting that $a=\frac 12$ and proceeding.
Answer: Let $a_1 = 2$. From the way you defined the sequence you can see that $a_n - a_{n-1} = n$. We can use this to find
\begin{align}
a_n &= a_{n-1} + n\\
&= a_{n-2} + (n-1) + n\\
&= a_{n-3} + (n-2) + (n-1) + n\\
&\vdots \\
&= a_1 + 2 + \cdots + (n - 2) + (n-1) + n
\end{align}
which is just the sum of the natural numbers except 1($1 + 2 + \cdots + n = \frac{n(n+1)}{2}$). So
\begin{equation}
a_n = a_1 + \frac{n(n+1)}{2} - 1 = 2 - 1 + \frac{n(n+1)}{2} = \frac{n^2 + n + 2}{2}
\end{equation}
where $a_1$ is the starting number (in this case 2). This sequence is a quadratic sequence as it exhibits second differences(the difference of the differences is constant).
Comment: Great explanation! Thank you!
Answer: Let a be the first term.  c be the added term.  Then you add m more each term.
The kth term is a + c +(c+m)+... +(c + (k-2)m).
That is the kth term is $a + (k-1)c + m\sum_{i=0}^{k-2}i= a + (k-1)c +m\frac {(k-1)(k-2)}{2}$


Validar Campo Único Laravel

Question: Fala galera, estou tentando aprender Laravel e atualmente estou meio travado em uma coisa aparentemente simples, é o seguinte.
Criei um sisteminha bem simples com login e outras coisas, e estou tentando implementar a edição dos dados do usuario logado, fiz as validações e la defini que o email é unique.
<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class UsersRequest extends FormRequest
{
public function authorize()
{
    return true;
}

public function rules()
{
    return [
        'name' => 'required|max:255',
        'email' => 'required|email|max:255|unique:users',
        'type' => 'required|max:1'
    ];
}

public function messages(){
    return [
        'required' => 'O campo ":attribute" é obrigatório!',
        'numeric' => 'O campo ":attribute" deve ser um número!',
        'min' => 'O campo ":attribute" deve ter no mínimo :min caracteres!',
        'max' => 'O campo ":attribute" deve ter no maximo :max caracteres!',
        'type.required' => 'O campo "tipo" é obrigatório!',
        'unique' => 'Este ":attribute" não se encontra disponivel no momento!'
    ];
}
}

Até ai tudo bem, a validação funciona corretamente, porém, quando eu tento atualizar o registro de algum usuário, por não ter alterado o email do mesmo é me retornado o erro, como posso fazer para que a validação unique do email abra uma exceção para o usuario daquele ID?
Aproveitando, queria saber de vocês se essa forma de fazer validação é indicada, correta, segura, eficiente e coisas do tipo, teriam outra forma para me recomendar fazer?
Answer: Achei a solução Galera, vou disponibilizar caso mais alguém tenha esse problema.
No meu caso, eu utilizo o Laravel 5.4 e valido minhas requisições com Form Request, por isso não dava certo como nos exemplos da documentação, mas foi só adaptar que funcionou direitinho. O codigo ficou da seguinte forma.
<?php

namespace App\Http\Requests;

use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Auth;
use Illuminate\Foundation\Http\FormRequest;

class UsersRequest extends FormRequest
{
public function authorize()
{
    return true;
}

public function rules()
{
    //$user = User::find($this->user);
    return [
        'name' => 'required|max:255',
        'email' => ['required', Rule::unique('users')->ignore(Auth::user()->id)],
        'type' => 'required|max:1'
    ];
}

public function messages(){
    return [
        'required' => 'O campo ":attribute" é obrigatório!',
        'numeric' => 'O campo ":attribute" deve ser um número!',
        'min' => 'O campo ":attribute" deve ter no mínimo :min caracteres!',
        'max' => 'O campo ":attribute" deve ter no maximo :max caracteres!',
        'type.required' => 'O campo "tipo" é obrigatório!',
        'unique' => 'Este ":attribute" não se encontra disponivel no momento!'
    ];
}
}

Answer: Adiciona no seu HTML os valores que são retornados pelo banco.
Ex: se estou editando o campo e-mail que no banco esta com valor email@example.com, no meu HTML o campo deve vir com email@example.com.
Assim, quando enviar um POST com os dados do form, mesmo que nao tenha editado nenhum campo o objeto vai para o servidor com os dados.
Comment: Mas eu faço isso, value="{{Auth::user()->email}}"> o problema é que o email que esta no usuario teoricamente não pode ser salvo no banco porque já existe, o que eu quero é fazer uma exceção para um determinado ID
Comment: Entendi, bom que conseguiu arrumar :)

Validar Campo Único Laravel


What are the benefits of a self signed certificate on a live site?

Question: Are there any benefits of a self signed certificate on a live site?
I know in IIS 7 you have the ability to self sign a certificate and I was wondering if using that as a precurser to buying one from a CA would be a good idea.
Do you get the same encryption benefits that you get from a CA signed cert or am I confusing terms? (running off the https protocol)
Comment: On a side note, you can get a free CA signed ssl cert for a single domain without wildcards from http://cert.startcom.org/.
Answer: The encryption is not a property of the certificate or where it is signed from.  The benefit you get from a CA signed cert is that it is automatically trusted by web browsers (and other SSL-aware applications).  A self-signed certificate will pop up a warning that the certificate is not trusted.  In more recent browsers, such as FireFox 3, the default action is to refuse to show the page and the user has to take deliberate actions to enable use of a self-signed (or expired, for that matter) certificate.
If you can talk to everyone who will use the web page (if this is for your family only, for example), this isn't a problem.  Tell them to expect that warning and how to handle it in their browser and it's a one-time issue.
However, if this is for any use that requires anything approaching real security, you probably want a true, signed, not self-signed certificate.
Comment: Thanks Eddie.  I knew the trust issue was the big one, I was wondering if there was anything else I should be thinking about.
Answer: You get the same encryption benefits, but everyone viewing your site will get a warning that your certificate is untrusted (or from an untrusted source). The advantage of getting one of the main stream certs is that they are already in the browser as trusted.
In IE 7, go to Tools, Internet Options, Content, Certificates, Trusted Root Certification Authorities. Those are all the authorities IE trusts by default.
Answer: Trust.  A self-signed certificate gives the same encryption.
But I trust a CA.  I do not trust you.
So why shouldn't I trust you? Because there's no guarantee that the name on the certificate ("Discount Bob's Hanggliding and BBQ Emporium") was the person who actually created the certificate.  I could create a certificate that said "Discount Bob's Hanggliding and BBQ Emporium" and when you go to ritter.vg it'd say "Discount Bob's Hanggliding and BBQ Emporium".
But when I ask a CA to sign my certificate that says "Discount Bob's Hanggliding and BBQ Emporium", they'll ask "Sure, show me some credentials" and I don't have any, so they'll tell me to piss off.  But the actual Discount Bob will have those credentials, the CA will sign it.  So when you see the certificate, signed by the CA, you'll know that it actually is Discount Bob, because if it weren't the CA wouldn't have signed it.
The purpose of a signed certificate is to verify that the person is actually who he says he.  Because the CA said he is, and I trust the CA.
The encryption isn't directly relevant to a certificate - it just gets added in because it's good to have and it goes hand in hand.
Answer: Pros of self-signed cert:

Free
Same encryption technology as CA signed

Cons:

Browser will display some form of security warning requiring user interaction to view the site.  This can be suppressed by the user choosing to trust the cert.
The trust you are implying is against the signer of the cert.  Anybody's cert can enable SSL encrypted connections.  The trust policy protects the user form man-in-the-middle attacks.  No one can issue a signed cert but the CA it came from and only to be used on the server it was created for.  Therefore, it's contents cannot come from another source or be modified in transit.

Quick scenario:  If someone setup a rogue wifi access point in an internet cafe, it's then possible to transparently proxy victim users' activity and watch it in a network sniffer.  Normally, SSL is encrypted and the data is unusable.  However, tools exist to proxy the user's HTTPS requests and inspect the victim's content in transit.  This has a side effect of giving the affected user an unauthentic cert that is typically not trusted.
If you go to log into your bank's site and get an SSL security warning, DO NOT proceed.  You may be a target.
Some might recognize this as the Hak5 Pineapple.
Comment: Thanks for the scenario.  I'm planning on using the self signed cert to test my app on the live system while I prepare it for deployement, so I'm not really worried about any "clients" because it's just me.  When I'm ready to deploy I'll have already purchased a signed cert.  It's still very useful to know this information, though.
Comment: I believe this is only possible with the TLS variation of a SSL request.  A pure SSL handshake whouldn't reveal any packet content right?
Comment: Packet contents are always visible, but encrypted by a key that is randomly selected and exchanged during handshake.  This is true for all SSL/TLS versions.
Answer: Since you asked specifically for the benefits of a self-signed cert, I suppose the "benefits" would be that it's cheap (ie free) and quicker to set up initially. These are obviously far outweighed by the negatives of all of your site visitors having to add an exception to their browsers' security policies to allow them to view your site.
If you haven't listened to them already, you may find some of the past Security Now Podcasts of interest - SSL is discussed at length in a number of episodes.
Answer: You're confusing encryption with authentication.
Any cert will provide encryption.
A CA cert also proves that CA is vouching that you are who you say you are.
A self-signed cert provides encryption but not authentication.
Comment: I was under the assumption that a CA provides authentication, but that using the https protocol encrypts your pay load.  However, in order to use the https protocol, don't you have to have a cert?
Comment: Yes, the way TLS (aka SSL) is implemented you need a cert.  But that's a requirement of the protocol, NOT a requirement in theory.  I could communicate with anyone and at the beginning we'd negotiate how we're going to encrypt, and what keys.  But I wouldn't know that I'm talking to Bob and not someone pretending to be Bob.
Comment: I understand, you wouldn't be confident in knowing it was really Bob, but at least you could be confident knowing that no one is sniffing your conversation with said "Bob". Hence the need for both, encryption AND authentication.  I just didn't understand why I needed to have a cert if all I wanted to do was encrypt my pay load.
Comment: You need *a* cert to do encryption, but it doesn't have to be a *signed* cert.
Answer: Main benefit is you do not need to visit a 3rd party to handle your site's security. You can do this yourself. The problem is it's complicated to get right.
Their browser would need to "trust" the self-signed certificate. If you change the cert in the future, the same dialog should appear. Some answers explain how to do this. This is still bad, since users would be more susceptible to attacks, such as man-in-the-middle when they are trained to accept self signed certificates. I've seen companies where this is standard procedure! Too bad for those users!
Ideally, you would have a process to install a custom root cert on their box prior to attempting to hit your site. This root cert would then issue your site's cert. This way, their browser would trust your self signed cert prior to connecting to your site the 1st time, without displaying a trust error.


How do I set up a default value for a text field?

Question: I am trying to setup a default value according to drupal API (http://take.ms/sSbow) in case if the form is empty (before use filled any data) and not successful.
In hook_form_alter() I already added the code via
$form['#info']['filter-field_geoaddress_proximity']['label'] = t('Distance'); and it works well. Hovewer if I try like these
$form['#info']['filter-field_geoaddress_proximity']['value']['#default_value'] = 21;
$form['field_geoaddress_proximity']['widget'][0]['value']['#default_value'] = 21;

nothing happens.
This my debug info:
Array
(
    [operator] => field_geoaddress_proximity_op
    [value] => 2ield_geoaddress_proximity
    [label] => Drupal\Core\StringTranslation\TranslatableMarkup Object
        (
            [string:protected] => Distance
            [translatedMarkup:protected] =>
            [options:protected] => Array
                (
                )

            [stringTranslation:protected] =>
            [arguments:protected] => Array
                (
                )

        )

    [description] =>
)

Could somebody help me? Doesn't matter it is in hook_form_alter() or any other hook.
Thank you.
Answer: Usually you setup the default value when configuring the filter -- if you've got an exposed content:type filter, then you set the default values by selecting one or more content types in the Configure filter criterion dialog.
I wouldn't do this via hook_form_alter (or similar) as you'll be fighting Views the whole way.


How to show dependencies in Azure application insights?

Question: We have a custom integration with Azure Application Insights in PHP.
Currently we are able to visualize all of our services, but we can't show the dependencies between services.
Check a screenshot Here

Non working answers:

Application Insights' Application Map doesn't show dependency calls
Answer: Dependency Map is currently not available for PHP apps. However, it seems that you can do it calling:
<code>$this->_telemetryClient->trackDependency
</code>
more info:
https://github.com/microsoft/ApplicationInsights-PHP/blob/75858b71971edffd19d33dacf26c295adc62b03c/Tests/Telemetry_Client_Test.php
https://learn.microsoft.com/en-us/azure/azure-monitor/app/asp-net-dependencies
Comment: Application Insights provides officially supported SDKs for three languages - Java, Node.JS, .NET. Your answer said it is available for .NET apps which might be read as available only for .NET apps. AI PHP SDK is indeed not supported by Microsoft. But Open Tracing SDKs are supported. There is an Open Tracing PHP SDK.
Comment: changed my reply
Comment: All three officially supported Application Insights SDK (Java, Node.JS, .NET) and OpenTracing SDKs will produce Application Map.
Comment: @ZakiMa not what the official doc says: "This SDK is NOT maintained or supported by Microsoft even though we've contributed to it in the past." https://github.com/microsoft/ApplicationInsights-PHP
Comment: also: https://learn.microsoft.com/en-us/azure/azure-monitor/app/auto-collect-dependencies
Comment: Thank you! I haven't tried it myself. But if Open Tracing PHP SDK emits the right spans then it should work for Application Insights as well: https://github.com/opentracing/opentracing-php. Including Application Map.


I want to store images for my website

Question: I am developing one website.I want to store images.Users are supposed to insert images with their post.What are methods to store images?Is storing images in database really reliable?I thought about the amazon AWS but it's not reliable.
Comment: Possible duplicate question [Storing Images in DB - Yea or Nay?](https://stackoverflow.com/questions/3748/storing-images-in-db-yea-or-nay)
Answer: In today's web world, storing images in the DB or locally on your disks are not becoming good options as they were one day.
I usually prefer the separation of concerns concept, which means each part of the application should do one thing and do it very well, and this is becoming so important now when talking about scalability, maintainability, and fault tolerance.
Now, regarding your question: Im interested to know, how Amazon is not reliable for storing images? I'm asking this because Amazon S3 (and similar) is becoming the defecto-standard method for storage nowadays.
In my opinion, you can go with Amazon storage, or better off pick one of the image storage services like Cloudinary or File Picker, which offer more than image storage solutions, with the possibility to backup your images on Amazon S3 and similar services, you can have them checked.
Comment: I don't doubt the AWS.At this point i don't want to invest anything.Amazon s3 offering 20,000 get request and 2000 put request.But one of my friend said after crossing the limit they start deducting money from your credit card automatically.Is it true?
Comment: Yes, If you exceed the free limit quota, they will cost you money. But same thing will happened when you start growing your database in the hosting company, in addition to not being a good practice
Comment: so what should i do? I checked the Cloudinary they are offering 75000 images.
Comment: Go for it, they have a nice free starter plan and a nice admin page
Comment: If you think your question has been answered, please check my answer as the correct one

I want to store images for my website


Moving forum out of the main database

Question: I have a Drupal 6 site with an increasingly bloated forum. I am wondering whether it is possible I can move the forum out of the main site's database to a new database, possibly hosted in a new server.
So  I guess my question is a special case of distributing a single Drupal database over several servers.
Comment: How big are you considering bloated?  Have you profiled things and pinpointed that the forums are causing performance problems?
Comment: Well, by bloated, I mean over 100K posts. It is the main part of the site that involves a lot of queries/writes, so I guess it is responsible for a lot of mysql load.
Answer: One option is to have a multidomain setup where forum.yourdomain is your forum installation and www.yourdomain is your main portal. Then you could have a single sign on for both domains.
Comment: Yes, I thought about this but the difficult part is that how the database can be distributed/synchronized?

Moving forum out of the main database


Do i have to unsubscribe from anonymous event handlers of local variables?

Question: If I have a code that looks something like this:
public void Foo()
{
    Bar bar = new Bar();

    bar.SomeEvent += (sender, e) =>
    {
        //Do something here
    };

    bar.DoSomeOtherThingAndRaiseSomeEvent();
}

Will bar be collected when the method runs out of the scope, or will I have to manually unsubscribe from the event to prevent a memory leak because of a reference to SomeEvent?
Answer: Your situation is fine; the event subscriber will not prevent the publisher from being collected, but the opposite can happen.
For example,
class Foo
{
    public event EventHandler FooEvent;

    void LeakMemory()
    {
        Bar bar = new Bar();

        bar.AttachEvent(this);
    }
}

class Bar
{
    void AttachEvent(Foo foo)
    {
        foo.FooEvent += (sender, e) => { };
    }
}

In this case, the instance of Bar created within LeakMemory can't be collected until either

The anonymous method represented by the lambda is removed from FooEvent's invocation list
The instance of Foo to which it's attached can be collected

This is because the event (which is just some syntactic sugar over an ordinary delegate instance) holds onto a list of delegates to invoke when it's invoked, and each of these delegates has, in turn, a reference to the object that it's attached to (in this case, the instance of Bar).
Note that we're only talking about collection eligibility here. Just because it's eligible doesn't say anything about when (or even, really, if) it will be collected, just that it can be.
Comment: Is there any standard form/idiom of "weak-reference events"?
Comment: @pst: Unfortunately, no. This is something that's been discussed before (more generally, simply not considering references that are *only* part of delegates as being reachable), but the complexities and potential pitfalls have thus far prevented it from being implemented. There may have been changes to those plans since I last looked, but as far as I know this is where things stand and will continue to. Even solutions that use the `WeakReference` class just move the issue to another type.
Answer: Well, the object bar refers won't be automatically garbage collected immediately... it's just that the bar variable won't prevent it from being garbage collected.
The event handler won't prevent the instance of Bar from being garbage collected either though - the "normal" problem is that an event handler keeps the subscriber of an event from being garbage collected (if it uses an instance method or captures "this" in an anonymous function). It doesn't usually affect the publisher being garbage collected. Just remember that the publisher needs to keep a reference to all the subscribers - the subscriber doesn't need to remember what it's subscribed to, unless it explicitly wants to unsubscribe or use some other member later.
Assuming nothing else is keeping your instance of Bar alive, your code should be fine.
Answer: The above answers are correct; I just wanted to make a note. Anonymous delegates used as handlers can only be unsubscribed if you retain some other reference to the delegate/lambda. This is because lambdas are "function literals", kind of like string literals, however unlike strings they are NOT compared semantically when determining equality:
public event EventHandler MyEvent;

...

//adds a reference to this named method in the context of the current instance
MyEvent += Foo;

//Adds a reference to this anonymous function literal to MyEvent
MyEvent += (s,e) => Bar();

...

//The named method of the current instance will be the same reference
//as the named method.
MyEvent -= Foo;

//HOWEVER, even though this lambda is semantically equal to the anonymous handler,
//it is a different function literal and therefore a different reference,
//which will not match the anonymous handler.
MyEvent -= (s,e) => Bar();

var hasNoHandlers = MyEvent == null; //false

//To successfully unsubscribe a lambda, you have to keep a reference handy:

EventHandler myHandler = (s,e) => Bar();

MyEvent += myHandler;

...

//the variable holds the same reference we added to the event earlier,
//so THIS call will remove the handler.
MyEvent -= myHandler;


How to optimize Mysql Query that has 2 Inner Joins with Distinct? ( InnoDB )

Question: I have a query which I use InnoDB storage engine.
I want to optimize it. It takes too much time to execute. I have 5 million data in my database. Now it takes 250 seconds to execute.
INSERT INTO dynamicgroups (adressid)

    SELECT SQL_NO_CACHE DISTINCT(addressid) FROM (
        SELECT cluster_0.addressid FROM (
            SELECT DISTINCT addressid FROM (
                SELECT group_all.addressid FROM (
                    SELECT g.addressid FROM table2.635_emadresmgroups g
                        INNER JOIN table2.emaildata f_0
                               ON f_0.addressid = g.addressid
                        WHERE  (f_0.birthday > date(DATE_SUB(NOW(),INTERVAL 18 MONTH))
                            AND f_0.birthday < CURDATE() )
                ) group_all
            ) AS groups

        ) AS cluster_0

        INNER JOIN(
            SELECT DISTINCT addressid FROM (
                SELECT group_all.addressid FROM (
                    SELECT g.addressid FROM table2.635_emadresmgroups g
                        INNER JOIN table2.emaildata f_0
                               ON f_0.addressid = g.addressid
                        WHERE  (marriage_date = ''
                             OR marriage_date = '1900-01-01'
                             OR marriage_date = '0000-00-00' )
                ) group_all
            ) AS groups
        ) AS cluster_1 ON cluster_1.addressid = cluster_0.addressid

        INNER JOIN(
            SELECT DISTINCT addressid FROM (
                SELECT group_all.addressid FROM (
                    SELECT g.addressid FROM table2.635_emadresmgroups g
                        INNER JOIN table2.emaildata f_0
                                ON f_0.addressid = g.addressid
                        WHERE  (f_0.city = '34' )
                ) group_all
            ) AS groups
        ) AS cluster_2 ON cluster_2.addressid = cluster_1.addressid
    ) AS t

Answer: Even though the EXPLAIN operator isn't implemented as well as others.. I'd suggest you use it for your query.
After that you can analyse what the result that EXPLAIN give and decide which columns should be indexed.
For more information I'd suggest viewing these sources:
MySQL syntax: EXPLAIN
MySQL using: EXPLAIN
Furthermore, the last 2 selects appear to be very similar, maybe you can make a temporary table or a view out of these, so that you don't have to run the entire select twice?
Answer: Your queries all seem to be variations of this query:
SELECT g.addressid
FROM table2.635_emadresmgroups g INNER JOIN
     table2.emaildata f_0
     ON f_0.addressid = g.addressid
WHERE  (f_0.birthday > date(DATE_SUB(NOW(),INTERVAL 18 MONTH)) AND f_0.birthday < CURDATE() )

I would suggest approaching this using group by and having:
SELECT g.addressid
FROM table2.635_emadresmgroups g INNER JOIN
     table2.emaildata f_0
     ON f_0.addressid = g.addressid
GROUP BY g.addressid
HAVING SUM(f_0.birthday > date(DATE_SUB(NOW(), INTERVAL 18 MONTH)) AND f_0.birthday < CURDATE() ) > 0 AND
       SUM(marriage_date = '' OR marriage_date = '1900-01-01'  OR marriage_date = '0000-00-00' ) > 0 AND
       SUM(f_0.city = '34' ) > 0;

Depending on the volume of data, filtering before the group by can also help:
SELECT g.addressid
FROM table2.635_emadresmgroups g INNER JOIN
     table2.emaildata f_0
     ON f_0.addressid = g.addressid
WHERE (f_0.birthday > date(DATE_SUB(NOW(), INTERVAL 18 MONTH)) AND f_0.birthday < CURDATE() ) OR
      (marriage_date = ''  OR marriage_date = '1900-01-01' OR marriage_date = '0000-00-00' ) OR
      (f_0.city = '34' )
GROUP BY g.addressid
HAVING SUM(f_0.birthday > date(DATE_SUB(NOW(), INTERVAL 18 MONTH)) AND f_0.birthday < CURDATE() ) > 0 AND
       SUM(marriage_date = '' OR marriage_date = '1900-01-01'  OR marriage_date = '0000-00-00' ) > 0 AND
       SUM(f_0.city = '34' ) > 0;

Answer: marriage_date -- Make it NULLable and use NULL instead of '', etc.  That will avoid an inefficient OR and might lead to usability of an INDEX.
Please provide SHOW CREATE TABLE so we can assess the current indexes.
What version are you running?  Until very recently this construct was very inefficient:
FROM ( SELECT ... )
JOIN ( SELECT ... )

The workaround was to put the subqueries into tmp tables and add an INDEX.
This may help in your case, since you seem to be using the JOINs for filtering:  Turn JOIN ( SELECT ... ) into WHERE EXISTS ( SELECT * ... ).
Please describe, in English, what the query is trying to do.
Another approach, building on Gordon's suggestion of having a common SELECT:  Put that common SELECT into a TEMPORARY table; add index(es), then query from it.


Move clustered MSMQ storage location

Question: We have a two-node active/passive Windows 2003 cluster running MSMQ among other things. Windows picked the Quorum drive to store the queue messages, but this drive has VERY limited disk space. How can we change the location?
Answer: There is one and only one way to move the storage directory for MSMQ. It cannot be done in a scripted manner; it can only be done manually.

Go to the computer management MMC
Expand the "Services and Applications" node
Right click "Message Queuing" and select "properties"
Go to the storage tab and modify the location.

The MMC utility does the following:

Makes sure the new target is valid (meaning, not a network share but a local disk).
Makes the directory tree
Sets proper permissions
Moves the data

Official reference material.
Comment: Your article also says "Note - It is not supported to change the locations for a clustered MSMQ resource and no UI is available to allow you to do this."
Comment: Ah, yes. The cluster part of the equation is important.
Comment: updated link: https://docs.microsoft.com/en-us/archive/blogs/johnbreakwell/changing-the-msmq-storage-location
Answer: The MSMQ location is based on the disk resource you choose when you set up MSMQ as a cluster service. In my case, we have 4 disks in a single resource. According to our MS tech, this isn't a supported configuration.
The solution is to set up the disks as individual cluster resources. Then, we can choose the specific disk we want when we set up MSMQ.
Comment: To become separate resources, each disk must present as a unique LUN to the OS, not just a partition on a single large RAID array.

Move clustered MSMQ storage location


Are subgradients bounded on compact subsets of an open set?

Question: Context & Motivation: This is a preliminary question that I wanted to answer in order to generalize the nonconvex projected gradient descent method in Chapter 3 of the book Non-convex Optimization for Machine Learning to the nonsmooth case. Specifically, I wanted to know if the classic subgradient could be analyzed in the nonconvex setting using the same principles in the convex case, i.e., by looking at the size of the subgradients of the objective function in the nonconvex setting.
Question: Let $\Omega \subseteq {\mathbb R}^n$ be a possibly nonconvex open set, and suppose $X$ is a compact subset of the interior of $\Omega$, i.e., $X\subseteq {\rm int}\ \Omega$. Moreover, let $f:\Omega \mapsto {\mathbb R}$ be such that for every $x\in\Omega$ there exists an open ball $\cal B$ around $x$ such that $f$ is convex on $\cal B$.
Does there exist a constant $L > 0$ such that $\|v\| \leq L$ for every $v\in\partial f(x)$ and $x\in X$ (where $\partial f(x)$ is the convex subdifferential of $f$ at $x$)? In other words, are the subdifferentials of $f$ uniformly bounded when restricted to a compact subset?
Comment: Prove the claim on the balls $\mathcal B$, cover $K$ by such balls, then the claim follows by compactness
Comment: Thanks! From your hint, the (slightly) more detailed argument seems to be as follows: (1) assign the "right" ball to each $x \in X$, (2) $f$ is locally Lipschitz for each ball and hence $\partial f$ is bounded in each ball, (2) since the balls cover $X$ and $X$ is compact, there is a finite subcover, (4) the desired constant $L$ is just the largest bound of $\partial f$ over the balls in the finite subcover.
Comment: What is variational about this?
Comment: Since $\Omega$ is nonconvex, I wasn't sure if we needed any of the machinery from variational analysis. Should I remove the tag now that I know the solution follows from basic principles in convex analysis?
Answer: Too long for a comment.
Here is the idea of the proof.
Suppose $\varphi$ a convex locally lipschitzian function that has a closed support hyperplane (which by definition, is a continuous linear form). Given a unit vector $u,$ and $x$ a centre of the ball, you can restrict the function $\varphi$ on the line segment inside this ball that passess through $x$ in direction $u.$ $\varphi$ restricted to this line segment is a convex function from an interval to the reals, which therefore has lateral derivatives (a.k.a. side derivatives), both of which are non-decreasing. Since $\varphi$ is lipschitzian, these lateral derivatives are bounded by the lipchitzian control-constant, a fortiori, the bounds are independent of $u.$ In finite dimensions, your hyperplane is necessarily given as a row matrix, this will show that all entries in this row matrix are bounded by constants independent of $u$ and therefore, the associated linear transformation will also have bounded movement (i.e. the support hyperplane can only tilt a little on every direction). QED
Comment: The argument ought to show that if $f$ is defined on a ball, convex and $\lambda$-lipschitz there, then the directional side-derivatives of $f$ exists and are bounded (in absolute value) by $\lambda.$ If $X$ is compact, cover it by $k$ balls, and then the directional side derivatives of $f$ will be bounded everywhere  by $\max(|\lambda_1|,\ldots,|\lambda_k|).$ Or so the idea goes.
Comment: There are a few details that are unclear to me here:

(1) What is the relation between $\varphi$ and $f$? Certainly, we cannot have $f=\varphi$ as $f$ here is only defined on the nonconvex set $\Omega$.

(2) The "lipschitzian control-constant" may be independent of $u$, but it may not be independent of $x$. Does your argument somehow imply that $\partial f(x)$ is uniformly bounded on $X$ without requiring $X$ to be compact?


What is zeroed page in Linux kernel?

Question: In Linux kernel, what does 'zeroed page' actually mean?
I have tried corelate it with free pages but it does not make a lot of sense.
Answer: Zeroed pages are pages where all bits in the page are set to 0. Not all zeroed pages are free, nor are all free pages necessarily zeroed (implementation specific).
A free page doesn't necessarily mean it is zeroed. It could be a page that is set to invalid (not in use by any process), but has old data from when it was last used. For security reasons, the OS might zero out pages before giving it to another program.
A zeroed page also doesn't mean it's a free page. When a process uses malloc() and then does a read (tested in Ubuntu 20.04), it's possible that the memory that is allocated is all zeros, but, of course, at this point the page is not free. See if your system's malloc implementation gives you zeroed pages to work with:
#include <stdio.h>
#include <stdlib.h>

#define PAGE_SIZE 4096
int num_pages = 32;

int main(){
    int i;
    int bytes = num_pages * PAGE_SIZE;
    char * test = (char *)malloc(bytes);
    if (test == NULL){
        printf("Malloc failed.\n");
        return -1;
    }

    for(i =0; i < bytes; i++){
        // A zeroed page will have all (char) zeros in it
        if (test[i] != (char) 0)
            printf("Not (char) 0: %c\n", test[i]);
    }
    return 0;
}

As pointed out in the comments by @0andriy, my original example using calloc is implemented using the "Zero page", a single page filled with zeroes that all callocs can return using the copy-on-write optimization described here.
Comment: Ha-ha, `calloc()` actually is cheating due to CoW mechanisms used in kernel. So, no, `calloc()` does not return 'zeroed' pages, it returns Zero Page — special one which is zeroed and always mapped. https://stackoverflow.com/questions/35547665/linux-kernel-role-of-zero-page-allocation-at-paging-init-time/
Comment: Good catch, I'll update my example. Do you agree that `malloc` returns zeroed pages if the OS zeroes them out before allocating? If so, I'll change my example to `malloc` instead.
Comment: No, `malloc()` returns an address from page list and marks that address space occupied. You really need to read something about modern MMU hardware and OS support of memory management. And if you got zeroed memory from `malloc()`, it's libc allocator, not kernel one.
Comment: Yes and then after you read or write the memory it's truly allocated, as I wrote in the post. I also said implementation specific so my answer still stands

What is zeroed page in Linux kernel?


Specification of a random slopes model with two grouping factors

Question: Suppose people take a 10-item exam. For each item, $k = 1,2,…,10$, exactly one rater assigns a score to exactly one person, with the constraint that no person sees the same rater twice. There are $i = 1,2,…,5000$ people and $j = 1,2,…,500$ raters. So people and raters are partially crossed, with most person-rater pairs having 0 data points, and the rest having exactly 1 data point.
Update: items were randomly assigned to positions.
Suppose I want to estimate a random slopes model where scores vary linearly with item position and the variability in scores is due to person intercept variability, person slope variability, rater intercept variability, rater slope variability, and residual error variability – in R,
lmer(rating ~ itemPosition + (itemPosition | personID) + (itemPosition | raterID))
Firstly, is there a better way to write the model down in non-matrix form than what I have below? Because there are two grouping factors, I am confused about the indices. If I let $q$ index data points, I want something like
$Y_q = \beta_0 + \beta_1 ItemPosition_q + p_{0i} + p_{1i} ItemPosition_q + r_{0j} + r_{1j} ItemPosition_q + e_q$
where $p_{0i} \sim N(0, \sigma_{p0}^2)$ denotes a person-level random intercept, $r_{0j} \sim N(0, \sigma_{r0}^2)$ denotes a rater-level random intercept, $p_{1i} \sim N(0, \sigma_{p1}^2)$ denotes a person-level random slope, $r_{1i} \sim N(0, \sigma_{r1}^2)$ denotes a rater-level randoms slope, $e_q \sim N(0, \sigma^2)$ is the residual error, the person random effects are uncorrelated with the rater random effects, the random effects are uncorrelated with the error term, $cov(p_{0i}, p_{1i}) = \sigma_{p01}$, and $cov(r_{0i}, r_{1i}) = \sigma_{r01}$. More specifically, can I replace the index $q$ with $ijk$?
Secondly, do I have the correct expression for $$Var(p_{0i} + p_{1i} ItemPosition_q + {r_0j} + r_{1j} ItemPosition_q + e_q) ?$$ I get
$(\sigma_{0p}^2 + 2\sigma_{p01} ItemPosition_q + \sigma_{1p}^2 ItemPosition_q^2)$ + $(\sigma_{0r}^2 + 2\sigma_{r01} ItemPosition_q + \sigma_{1r}^2 ItemPosition_q^2)$ + $\sigma^2.$
I want to use this as the denominator to calculate the proportion of variance due to persons, for example.
Lastly, any general comments about the appropriateness of the model are also welcome but not at all necessary (as I haven't provided any information about the data).
Answer: I believe both your model formulation and variance are fine for your purposes (and with the stated independences). Indeed, indexing with ijk is a good idea (note that you can then replace ItemPosition simply with k).
Word of warning though: your question does not explicitly hold this: this kind of variance is the variance between subjects for given question.
Second word of warning: is it reasonable to expect linearity of the rates with item position?
Comment: thanks for your answer. In regards to using $Y_{ijk}$, do I need not to subindex two of the indices – e.g.,  $Y_{i j_i k_{ij}}$ --  (because persons, raters, and items are only partially crossed) or is that understood in such notation? I think I understand your first point that the between person variance depends on $k$ (items were randomly assigned to item position). The linearity is hypothetical.
Answer: Let's think of a rating of test item $k$ as a function of a three latent variables: the intrinsic difficulty of the question, $u_k$, an item specific ability of test subject $i$, $u_{ik}$, a question specific rating 'leniency', $u_{jk}$.
Assuming a rating is a linear function of these factors we can say:
$$
\text{Rating}_{ijk} = u_k + u_{ik} + u_{jk} + \varepsilon_{ijk}
$$
If $u_k$ is drawn at random conditional on $k$, we can get a valid estimate of item position specific ability learning and leniency from this model:
$$
\text{Rating}_{ijk} = \beta_0 + u_{ik} + u_{jk} + \varepsilon_{ijk}
$$
Where $\beta_0$ is the average difficulty of the questions and variance of difficulties is aborbed into the error term. This model is estimable but it has a lot of parameters. If you are interested in detecting linear trends then you can simplify the model as follows.
$$
\begin{align}
u_{ik} = p_{0i} + p_{1i}\text{Item Position}_k \\
u_{jk} =r_{0j} + r_{1j}\text{Item Position}_k
\end{align}
$$
And in the combined model:
$$
\text{Rating}_{ijk} = \beta_0 + p_{0i} + p_{1i}\text{Item Position}_k + r_{0j} + r_{1j}\text{Item Position}_k + \varepsilon_{ijk}
$$
This is similar to your proposed model except it does not include a predictor for specific item difficulty, which makes sense because if item difficulties are random, your $\beta_1$ term should equal 0.
You might consider adding higher order polynomials of item position to allow for more flexibility in learning and leniency rates.
Comment: thanks for your suggestion. I am familiar with the approach and the package, but I'm not sure how an item response model would help. I want to distinguish the mean and item-position effects of persons and raters in some parsimonious way, and the only approach using latent variables I can think of is to regress the latent ability variable on persons, raters, and their interactions with item position (using, e.g., R's `lavaan` or in Mplus). This would be analogous to a linear fixed effects model and would generate a lot of parameters. If you had another approach in mind, please share!
Comment: In your model $p_{0i}, p_{1i}, r_{0j}, p_{1j}$ are already latent variables.
Comment: you're right - I should have said "an item response model", as I thought you originally meant to model ratings conditional on latent ability. Thanks for updating your answer. I think I wasn't clear in my post though: item characteristics like difficulty are not a concern because items were randomly assigned to positions. The linear effect of item position is due to a person practice effect or a rater leniency effect that increases with time, or both. My fault if that was unclear.


How can i handle a camera direction parallel to the y-axis my raytracer

Question: I'm working on my raytracer and it seems I can't manage to handle the case where the direction vector of my camera is parallel to the vector (0,1,0).
I think it is linked to my way to compute the vector up and right for camera but I can't manage to find a work around.
Here is how I do it:
<code>cam_up = vector_cross(cam_dir, {0, 1, 0});
camp_right = vector_cross(cam_right, cam_dir);
</code>
Can somebody enlighten me?
Comment: You need to add a programming language tag.
Comment: What direction do you want to choose in that case anyway?
Comment: i don't understand. What do you mean by choosing a direction?
Comment: The cross product didn't work out because what you're asking for is inherently ambiguous - it couldn't give an answer if it wanted to. Since the two vectors are parallel, essentially you're asking for "here is a direction, give me something perpendicular to it" - well, there's a lot of that. There's a whole plane to choose from. So you have to make the choice.
Comment: Can i choose something like {1, 0 ,0} as a replacement?
Comment: i did and it worked. thx a lot for your help
Answer: You have the correct formula for calculation of an orthogonal axis from a single cameraOut vector. However, as has been stated this formula will not account for the camera roll, which could be any direction in the plane perpendicular to the camera direction. This will be apparent when moving a camera across the pole (y-axis) as there will be undesireable behavior (yes it will be correctly aimed, but no doubt the roll won't be desired).
For more information, look into gimbal lock.
The roll itself is not really incorrect, however in reality for this camera transition to be smooth and appear correct (rather than suddenly flip or spin as it's direction becomes 0,1,0), you need to correct any roll incurred. This is a rotation about the cameraOut axis and ideally should be relative to the previous cameraAlong. This means in order to maintain the correct roll (or perceived correct roll) you need to consider the camera POSE (position and orientation) from the previous frame and ensure the roll is mitigated. Of course, if the camera doesn't move (i.e. your rendering a frame with a static camera position) you do not have a previous camera state so the position cannot be calculated and instead must be explicitly defined as part of the scene definition.
Personally I store an entire orthogonal axis for a camera so the orientation and roll is always clearly defined. This is only for completeness, to be honest you don't need to store the entire axis, 2 vectors cameraOut and cameraAlong (the third one being cameraUp) are enough. cameraAlong is dependant on the handed-ness of your coordinate system (e.g. for initial camera position say position (0,0,0) in left hand coordinate system, the cameraAlong direction will be in the right direction in relation to the viewer, for right hand system the cameraAlong would be the other way around. The cameraUp and cameraOut would are the same in both coordinate systems).
Hope this helps.
P.S This isn't ray tracing specific and the same principles apply for OpenGL/DirectX or any 3D representation.


Price comparison website

Question: I have two sets of taxonomy lists

Engine Codes
Vehicle Make and model

Now I'd like to link the two taxonomy terms from different lists/vocabs e.g.
Nissan Skyline R33 GTR (Vehicle make and model)  - - - > RB26DETT (engine code)
RB26DETT (engine code) --> Nissan Skyline R33 GTR (Vehicle make and model)
I'd like to do this without having to manually input it twice. In some cases the same vehicle may have different engine codes, and visa versa.
So If I look at the Taxonomy term page for Nissan Skyline R33 GTR, it lists the RB26DETT and visa - versa.
I'm not sure (i) which module to use, and (ii) whether I should use term reference, or entity reference.
I'm new to this and learning so appreciate any help/advice!
Thanks
Shah
Answer: While I don't have the detailed steps, I suggest you look to the Views module. The relationships and/or contextual filters provide WHERE and FROM type SQL queries.
If you have two views, one based on each vocabulary (taxonomy lists), and each has a contextual filter (with block settings to show only on specific page) then you will get a correlated listing on page/block sets.
If you have troubles getting it going, try exposed filters and AJAX refresh options - Get close enough to help your users help themselves. From a marketing angle, even if automatic/ideal results aren't automatic yet, IF views exposed filters get your customers/staff/partners to answers within 60 seconds from only a click or two, AND they also see message/indication you are actively working on the automatic results, the anticipated "better" site will up their anticipation and your reputation with most people (if, of course, presented with care).
Alternate possible "maybe" modules are "Views Field View" or "EVA". The "Better Exposed Filters" module might also be handy.
Try a search inurl:tutorial-6-10-views-relationships-and-contextual-filter for a great video.
Good luck.

Price comparison website


on 'Click' upload individual files at table row instead of multiple upload

Question: I have dynamic table table with 4 columns. The first 3 at each row has an input type='file' where a user can choose a file to upload and on the 4th column has a submit button in-line with the rows. Submitting files in the first row it will work fine but i am not able to do it for the rest of rows.

$("#UpSubmit").on("click", function() {

  var rowSub = $(this).closest('tr');

  var file_data = rowSub.find('.file-input').prop("files")[0];
  var form_data = new FormData();
  form_data.append('file', file_data);

  var file_data1 = rowSub.find('.file-input1').prop("files")[0];
  var form_data1 = new FormData();
  form_data1.append('file', file_data1);

  var file_data2 = rowSub.find('.file-input2').prop("files")[0];
  var form_data2 = new FormData();
  form_data2.append('file', file_data2);

  $.ajax({
    url: 'upload.php',

    cache: false,
    contentType: false,
    processData: false,
    data: form_data,
    type: 'post',

  });
  $.ajax({
    url: 'upload.php',

    cache: false,
    contentType: false,
    processData: false,
    data: form_data1,
    type: 'post',

  });
  $.ajax({
    url: 'upload.php',

    cache: false,
    contentType: false,
    processData: false,
    data: form_data2,
    type: 'post',

  });

});
Comment: What is the issue exactly? You don't see the other 2 requests in your network tab?
Comment: From the table The submit button does not work on 2nd or 3rd row to upload files  but on the 1st row i can select the 3 files on each column and hit the submit button @AnuragSrivastava
Answer: Add class UpSubmit to the button and use $(".UpSubmit")
ids in HTML are unique and you won't be able to have multiple buttons with the same id
Comment: I am calling the button   the button is echoed in each row
Comment: In the echo statement use ``


What are the most common optimization algorithms for confirmatory factor analysis?

Question: For confirmatory factor analysis, as I understand it, we have  the following set up:

Source: Sacha Epskamp's lecture notes
I then read that some authors have tried the following approaches

Source: A First Course in Factor Analaysis by Comrey, Lee
I was wondering if Fletcher-Powell or Newton-Raphson are commonly used? If not, what's th most common way people optimize their loss function in CFA?
Comment: With Newton-Raphson, you have to know the derivatives, which may or may not be complex for CFA; I never used their SEM program for CFA so I don't know the derivatives.   With the increased computational speed of most computers nowadays, there would have to be a lot of papers on use of metaheuristics to solve these optimizations through a derivative-free approach.  But if the derivatives are known, Newton-Raphson will probably be much faster.
Answer: The Newton-Raphson requires calculation of the second derivatives which are cumbersome to compute.  However, the first derivatives are readily available (see Stanley Muliak's book on Factor Analysis) so quasi-newton methods like Fletcher-Powell or BGFS should work well.


Manage View of a Table Row at runtime

Question: In my application i am creating and displaying a table at runtime. The table is developed in an Activity class. Everything working fine, only issue is the view of the table. There are four textviews in a row in the table. they are shown adjacently without seperation. How could i make a proper view with a definite space between textviews.
            text1.setText("24/02/2011"); //TextView text
            text2.setText("Andy");       //TextView text
            text3.setText("3");          //TextView text
            text4.setText("Repeat");     //TextView text
            tableRow.addView(text1);     //TableRow tableRow
            tableRow.addView(text2);     //TableRow tableRow
            tableRow.addView(text3);     //TableRow tableRow
            tableRow.addView(text4);     //TableRow tableRow
            dueTL.addView(tableRow);     //TableLayout dueTL

It display the data like : 24/02/2011Andy3Repeat
Answer: You can add weight to each TextView, also be sure that your TableView has fill_parent in its width. Also check the padding and margins of the TextViews
I hope this helps
Answer: If for some reason setting weights doesn't work for your situation, take a look at padding, paddingBottom, paddingLeft, paddingRight, and paddingTop in http://developer.android.com/reference/android/widget/TextView.html
Answer: You could either manually add a space to the strings in "setText" or you could set a right margin, if the surrounding ViewGroup supports it, on the TextViews either in XML (layout_marginRight) or via Code (LayoutParams).

Manage View of a Table Row at runtime


Querying with > (greater than) returns records >= (greater than or equal to)

Question: Can someone explain why the following query:
> modified_after = DateTime.parse "2012-12-06T17:40:36+00:00"
> Contact.unscoped.where("updated_at > :time OR deleted_at > :time", {:time => modified_after})

also returns records with updated_at equal to modified_after:
Contact Load (0.4ms)  SELECT "contacts".* FROM "contacts" WHERE (updated_at > '2012-12-06 17:40:36' OR deleted_at > '2012-12-06 17:40:36') => [
#<Contact id: 28, first_name: "John", last_name: "A", deleted_at: nil, created_at: "2012-12-06 17:40:36", updated_at: "2012-12-06 17:40:36", email: nil, notes: nil>,
#<Contact id: 29, first_name: "Mark", last_name: "B", deleted_at: nil, created_at: "2012-12-06 17:40:36", updated_at: "2012-12-06 17:40:36", email: nil, notes: nil>,
 #<Contact id: 30, first_name: "Michael", last_name: "C", deleted_at: nil, created_at: "2012-12-06 17:40:36", updated_at: "2012-12-06 17:40:36", email: nil, notes: nil>
]

Answer: It may be that those times are milliseconds greater than the query time.  What version of Rails are you running?  Check out this bug and see if it is related: https://github.com/rails/rails/issues/7385
Comment: Had Rails 3.2.8. Upgraded to 3.2.9 and everything works as expected. Thanks!


Method undefined for object in java cannot be compiled and deployed

Question: I am getting this error from the following:
<code>public class Application extends Controller {

    public static class Result {
        public Result(String contents, Status status) {
            this.contents = contents;
            this.status = status;
        }

        public final String contents;
        public final Status status;

        // "status":{"url":"https:\/\/mtgox.com\/api\/0\/data\/ticker.php","content_type":"application\/json","http_code":200

        public static class Status {
            public final String url;
            public final String content_type;
            public final int http_code;

            public Status(String url, String content_type, int http_code) {
                this.url = url;
                this.content_type = content_type;
                this.http_code = http_code;
            }
        }
    }

    public static void index() {
        render();
    }

    public static void options(String url, final String callback) {
        response().setHeader("Access-Control-Allow-Origin", "*");
        response().setHeader("Allow", "*");
        response().setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE, OPTIONS");
        response().setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Referer, User-Agent");

        return ok();
    }
}
</code>
However, the url and callback is being passed on the functions. I am unsure why I am getting this error:
<code> The file /app/controllers/Application.java could not be compiled. Error
 raised is : The method response() is undefined for the type Application
</code>
This is a controller file and I am unsure how to fix this syntax issue.
Comment: I am not sure what you are confused about. There is no response method that is defined inside the Application class (unless the Controller class has them). So it will complain that there is no response method. Is that the full extent of your code?
Comment: it starts out with a controller package

package controllers;

import com.google.gson.GsonBuilder;
import org.apache.commons.lang.StringUtils;
import org.yaml.snakeyaml.util.UriEncoder;
import play.libs.F;
import play.libs.WS;
import play.mvc.*;
Comment: If it is inside your controller class, is it declared public, protected, private?
Comment: This is a github file I've found trying to redeploy the same app on heroku
Comment: Is this code that you have copied and pasted from somewhere? Can you link to where you found it?
Comment: https://github.com/ripper234/Whatever-Origin/blob/master/app/controllers/Application.java
Comment: And you are sure that you correctly referenced and imported all of the required dependencies into your project?
Comment: I am looking at that. The only dependency listed on the dependencies.yml file I see was play, which I used as a buildpack. But I am probably missing something if I cannot deploy it.
Comment: Missing dependency/library is most likely the culprit for your error. Make sure your import statements are the same as listed in the github page.
Answer: Either you have to define the response() method inside your Application class file, or you need to define them in your Controller class which your Application class inherits. You are getting that error because it cannot find any declaration of a method called response() anywhere.
And you have to make sure that any external libraries/dependencies are imported correctly.


Tomcat application with self-signed certificate results in ERR_CERT_AUTHORITY_INVALID in the Chrome browser

Question: Tomcat application with self-signed certificate results in ERR_CERT_AUTHORITY_INVALID in the Chrome browser
I've set up a https and created a self-signed certificate. However, when I connect to the URL, I get a ERR_CERT_AUTHORITY_INVALID message.
https://{remote_host_name}:8443/
I've followed the instructions on the Tomcat website for SSL and self-signed certificates ( https://tomcat.apache.org/tomcat-7.0-doc/ssl-howto.html#Edit_the_Tomcat_Configuration_File ). One difference is that I'm connecting to a remote host, not a localhost, although I dont think that should matter.
This is a test environment, but unfortunately I cannot add an exception for the certificate in the browsers of the test hosts, as they create new FF profiles each test run.
Here is the command I have used to create the self-signed cert:
<code>./keytool -genkey -keyalg RSA -alias tomcat -keystore /var/tomcat/.keystore -storepass changeit -validity 360 -keysize 2048
</code>
Here is my Tomcat server.xml connector information:
<code>Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol"
maxThreads="150" SSLEnabled="true" scheme="https" secure="true"
clientAuth="false" sslProtocol="TLS"
keystoreFile="/var/tomcat/.keystore"
keystorePass="changeit"
</code>

Does the config in the Tomcat doc for self-signed certs only work when running Tomcat on localhost?
What is the best way to
resolve this?
Answer:
Tomcat application with self-signed certificate results in ERR_CERT_AUTHORITY_INVALID in the Chrome browser

Of course it does. Your tomcat server is presenting the browser a certificate which is not issued by a certificate agency trusted by the browser (i.e. shipped with the browser or with the OS). Thus the browser has no reason to trust the certificate and complains.
If the browser would check not if it trusts the issuer of the certificate this would mean that it would trust any certificate issued by some arbitrary person, which would include certificates issued by an attacker. Do you really want this?
To work with self-signed certificates you have to explicitly accept the certificate as trusted in each browser, but of course only after you've validated the fingerprint of the certificate manually to make sure that nobody has tampered with the connection. No server side reconfiguration can make the browser automatically trust such self-signed certificates. The only way to skip this step is to use certificates issued by a certificate agency already trusted by the browser.
Comment: A  great example is to perform a POST from some arbitrary site to your local machine (simulating an injection attack on that site sending stolen information to your server). If the browser didn't step in to double-check with the user, then that injection would mean incredibly easy information theft.

Chrome's message is appropriate: "Attackers might be trying to steal your information from {url} (for example, passwords, messages, or credit cards). NET::ERR_CERT_AUTHORITY_INVALID"


Iptables forward traffic from A to B where A is not gateway for B

Question: I want to forward ssh traffic from A port 2222 to B port 22. I do have ipv4 forwarding set to 1 on both interfaces. Still, this does not work. What is wrong?
Machine A:
eth0 192.168.0.150
eth1 184.108.40.206
Machine B:
eth0 192.168.0.200
iptables -L:
Chain INPUT (policy ACCEPT)
target     prot opt source               destination
ACCEPT     all  --  anywhere             anywhere
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:http
ACCEPT     icmp --  anywhere             anywhere             icmp echo-request

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination
ACCEPT     tcp  --  anywhere             192.168.0.200        tcp dpt:ssh state NEW,RELATED,ESTABLISHED

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

iptables -L -t nat:
root@lbpub01:~# iptables -L -tnat
Chain PREROUTING (policy ACCEPT)
target     prot opt source               destination
DNAT       tcp  --  anywhere             18.104.22.168       tcp dpt:2222 to:192.168.0.200:22

Chain POSTROUTING (policy ACCEPT)
target     prot opt source               destination
ACCEPT     tcp  --  184.108.40.206       192.168.0.200        tcp dpt:ssh

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

Update
I got help from the nice guys at irc@freenode, so here is my working iptables-save file:
*nat
:PREROUTING ACCEPT [0:0]
:POSTROUTING ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A PREROUTING -p tcp -m tcp -d 184.108.40.206 --dport 2222 -j DNAT --to-destination 192.168.0.200:22
-A POSTROUTING -o eth+ -j MASQUERADE
COMMIT
*mangle
:PREROUTING ACCEPT [0:0]
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
:POSTROUTING ACCEPT [0:0]
COMMIT
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -i lo -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -p tcp --dport http -j ACCEPT
-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
-A INPUT -j DROP
COMMIT

Answer: I've been working on this same problem for a while now.  The solution that seems to work for me (at least when I demoed it using VMs) wound up looking significantly different than what you have posted here.
Real quick, here are my configurations:
iptables -L:
Chain INPUT (policy DROP)
target     prot opt source               destination
ACCEPT     all  --  anywhere             anywhere
ACCEPT     all  --  anywhere             anywhere             ctstate RELATED,ESTABLISHED
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:ssh

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination
iptables -S:
-P INPUT DROP
-P FORWARD ACCEPT
-P OUTPUT ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p tcp -m tcp --dport 22 -j ACCEPT
(Just to clarify, that last INPUT rule is to allow ssh access into Machine A.)
iptables -t nat -L:
Chain PREROUTING (policy ACCEPT)
target     prot opt source               destination
DNAT       tcp  --  anywhere             anywhere             tcp dpt:2222 to:192.168.0.200:22
Chain INPUT (policy ACCEPT)
target     prot opt source               destination
Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination
Chain POSTROUTING (policy ACCEPT)
target     prot opt source               destination
SNAT       tcp  --  anywhere             anywhere             tcp dpt:22 to:126.96.36.199
iptables -t nat -S:
-P PREROUTING ACCEPT
-P INPUT ACCEPT
-P OUTPUT ACCEPT
-P POSTROUTING ACCEPT
-A PREROUTING -i eth0 -p tcp -m tcp --dport 2222 -j DNAT --to-destination 192.168.0.200:22
-A POSTROUTING -p tcp -m tcp --dport 22 -j SNAT --to-source 126.96.36.199

So, interestingly, I didn't need anything in the FORWARD chain, but it appears that the PREROUTING rule was enough to get the first packet from the client forwarded to Machine B.
iptables -t nat -A PREROUTING -i <external_interface> -p <tcp/udp> --dport <port_to_accept_connections_through> -j DNAT --to <destination_address:destination_port>
The problem, then, was the response packet getting lost by going through the Gateway.  I didn't realize this until I Wiresharked the eth1 on Machine A and noticed that the source address on the packet bound for Machine B was still that of the client machine.  I then used the POSTROUTING table to change the source address to Machine A's IP address on eth1 so that Machine B would know to send the response to Machine A and not the Gateway.
iptables -t nat -A POSTROUTING -p <tcp/udp> --dport <destination_port> -j SNAT --to <internal_IP_address_of_machine_a>
At this point, I was able to establish the connection from a client sitting on the same network as Machine A's eth0 interface to Machine B.  While I'm not 100% sure how the firewall knew what to do with the response packets sent from Machine B to the client machine, I think the most likely reason is the rule in the INPUT chain that allows established connections through the firewall:
iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
Comment: I forgot about this question. I should have posted my solution which I finally managed to make, with help from the nice guys at freenode. You solution differs a bit from mine but I think they work similarly. For reference, here is my iptables --save: http://pastebin.com/gXM2uwwx


Erro no WHMCS ao utilizar boleto fácil

Question: estou usando o módulo do boleto fácil para o whmcs
ele esta retornando o seguinte erro
array(2) { ["result"]=> string(5) "error" ["message"]=> string(51) "Admin User var is required if no admin is logged in" }

meu cod que gera este erro é este
function cpfcnpj($busca,$id){
        $dados['clientid'] = $id;
        $dados['stats'] = true;
        $dados['responsetype'] = 'xml';

        $cliente = localAPI('getclientsdetails',$dados);
        var_dump($cliente);
        foreach ($cliente['client']['customfields'] as $pos=>$val)
            if (in_array($busca, $val)) {
                $campo = $pos;
            break;
        }
        $valor = $cliente['client']['customfields'][$campo]['value'];

        return $valor;
    }

onde fica esse localAPI ? ou como deveria fazer para resolver?
Answer: consegui resolver
o parametro localAPI requisita um usuario de admin
entao alterando para
 $cliente = localAPI('getclientsdetails',$dados,'adm');

onde adm é meu usuário administrativo do whmcs o problema foi resolvido.

Erro no WHMCS ao utilizar boleto fácil


How to color/identify plot points by date

Question: I am trying to build a geom_line plot in ggplot2 to show some call center data over time.  I have my graph built as I want it, but I would like to identify specific dates (Monday's to be specific.. IE, 1/7, 1/14, 1/21, 1/28, 2/4, etc) with something like a special marker/color.. currently the dates are character format (how they were given to me), but with lubridate I believe they could be converted with little/no issue if needed.  Is this possible?
I am super novice at plotting with R, I have gotten to this point from other SO posts and a few 'cheat sheets'.
The only 'relevant' post I could find that directly mentions using any kind of function with ggplot is here: http://zevross.com/blog/2014/08/04/beautiful-plotting-in-r-a-ggplot2-cheatsheet-3/#use-a-function-to-alter-labels.  This doesn't exactly fit what I am looking for either.
Here is my code as it sits:
a <-  ggplot(cleantargetcounts)+
   geom_line(aes(x=DTE, y=TOTAL, color = DISPOSITION, group = DISPOSITION), size = 1.2)+
   scale_color_manual(values = c(Approval = "dark green",Denial = "red",Skip = "orange"))+
   geom_point(aes(x=DTE, y=TOTAL, color = DISPOSITION),size = 3.2)+
   geom_text_repel(aes(label=cleantargetcounts$TOTAL, x=DTE,y=TOTAL))+
   theme(axis.text.x = element_text(angle = 45, vjust = 1, hjust=1))+
   labs( x = "Date", y = "Disposition Count", title ="Disposition Count by Date")

Here is what my graph looks like currently:

and here is a basic idea of what I am looking for:

It would not matter to me HOW Monday's are identified.. whether it is a date colored, the plotted points are different.. just as long as they are easy to point out.
Here's my data:
    DTE        DISPOSITION TOTAL
   <chr>      <chr>       <int>
 1 2019-01-08 Approval      454
 2 2019-01-08 Denial        120
 3 2019-01-08 Skip          135
 4 2019-01-09 Approval      425
 5 2019-01-09 Denial        141
 6 2019-01-09 Skip          203
 7 2019-01-10 Approval      448
 8 2019-01-10 Denial        112
 9 2019-01-10 Skip          169
10 2019-01-11 Approval      666

Attempted codes provided by Heck1
cleantargetcounts$weekday <- wday(ymd(cleantargetcounts$DTE), label = TRUE, abbr = FALSE)

a <-  ggplot(cleantargetcounts)+
  geom_line(aes(x=DTE, y=TOTAL, color = DISPOSITION, group = DISPOSITION), size = 1.2)+
  scale_color_manual(values = c(Approval = "dark green",Denial = "red",Skip = "orange"))+
  geom_point(aes(x=DTE, y=TOTAL, color = DISPOSITION),size = 3.2)+
  geom_text_repel(aes(label=cleantargetcounts$TOTAL, x=DTE,y=TOTAL))+
  theme(axis.text.x = element_text(angle = 45, vjust = 1, hjust=1, color = ifelse(cleantargetcounts$weekday == "Monday", "red", "black")))+
  labs( x = "Date", y = "Disposition Count", title ="Disposition Count by Date")

which provides the following plot

Which is a bit odd as it correctly identified the days of the week in my data frame.
 DTE        DISPOSITION TOTAL weekday
  <chr>      <chr>       <int> <ord>
1 2019-01-07 Approval      455 Monday
2 2019-01-07 Denial         95 Monday
3 2019-01-07 Skip          154 Monday
4 2019-01-08 Approval      454 Tuesday
5 2019-01-08 Denial        120 Tuesday
6 2019-01-08 Skip          135 Tuesday

Attempting Jason's answer
I get an error that I am not familiar with
 df_tidy <- cleantargetcounts %>%
gather(DISPOSITION, TOTAL, -DTE) %>%
mutate(dow = wday(ymd(cleantargetcounts$DTE, abbr = TRUE, label = TRUE)))

Error: Column `dow` must be length 306 (the number of rows) or one, not 155
In addition: Warning message:
 2 failed to parse.

correction to Jason's answer
I had to modify part of Jason's answer to get it working correctly for me as follows:
df_tidy <- cleantargetcounts2 %>% mutate(dow = wday(DTE, abbr = TRUE, label = TRUE))
df_regions <- df_tidy %>% filter(dow == "Mon") %>% mutate(min = DTE - 0.5,
                                                          max = min + 1,
                                                          ymin = -Inf,
                                                          ymax = +Inf)

a <-  ggplot(df_tidy)+
  geom_line(aes(x=DTE, y=TOTAL, color = DISPOSITION, group = DISPOSITION), size = 1.2)+
  scale_color_manual(values = c(Approval = "dark green",Denial = "red",Skip = "orange"))+
  geom_point(aes(x=DTE, y=TOTAL, color = DISPOSITION),size = 3.2)+
  geom_text_repel(aes(label=df_tidy$TOTAL, x=DTE,y=TOTAL))+
  theme(axis.text.x = element_text(angle = 45, vjust = 1, hjust=1))+
  labs( x = "Date", y = "Disposition Count", title ="Disposition Count by Date")+
  geom_rect(data = df_regions,aes(xmin = min, xmax = max, ymin = ymin, ymax = ymax), fill = "blue", alpha = 0.2, color = NA)

Which produced the most accurate end result I was looking for like this:
Answer: Please try and make a reproducible example, however, based on your pictures, the following should get you what you want. In short, just pass "filtered" data into a geom call:
library(tidyverse)
library(lubridate)

set.seed(101)

df <- tibble(
  date = seq(ymd("2019-01-07"), ymd("2019-03-18"), by = "day"),
  approval = runif(n = 71, 225, 800),
  denial = runif(n = 71, 85, 120),
  skip = runif(n = 71, 120, 300)
)

df %>%
  gather(metric, value, -date) %>%
  mutate(
    dow = wday(date, abbr = TRUE, label = TRUE)
  ) %>%
  ggplot(aes(x = date, y = value, color = metric)) +
  geom_point() +
  geom_line() +
  geom_point(data = . %>% filter(dow == "Mon"), color = "deeppink", size = 3)

Alternatively, you could create a highlights data.frame like this and pass this to geom_rect:
df_tidy <-
  df %>%
  gather(metric, value, -date) %>%
  mutate(
    dow = wday(date, abbr = TRUE, label = TRUE)
  )

df_regions <-
  df_tidy %>%
  filter(dow == "Mon") %>%
  mutate(
    min = date - 0.5, # we want the highlighted region 'around' the point, not on the point.
    max = min + 1,
    ymin = -Inf,
    ymax = +Inf
  )

df_tidy %>%
  ggplot(aes(x = date, y = value, color = metric)) +
  geom_point() +
  geom_line() +
  geom_rect(
    data = df_regions,
    aes(xmin = min, xmax = max, ymin = ymin, ymax = ymax),
    fill = "orange", alpha = 0.2, color = NA
  )

Created on 2019-03-25 by the reprex package (v0.2.1)
Comment: I REALLY like the idea of the vertical bars highlighting the dates.. When I try to adapt your code I get a "failed to parse" error that I do not quite understand.  I will add the code I tried and the error to my OP.
Comment: @Checht - you need to make sure your `dates` field is actually a date, and not a character vector. Something like `cleantargetcounts %>% mutate(dates = mdy(dates))` is probably what you need towards the front of your code. Try working with that and if you get stuck, you may want to open a new question.
Comment: This works beautifully when I corrected the dates from CHARACTER to date.  The only other 'gripe' I have is this removed my dates under each data point and replaced it with a more general date with what appears to be 1 to 2 week breaks.. Is it possible to leave the dates under each data point?
Comment: @Checht yes, just add `scale_x_date(date_breaks = "1 day")` to the end.
Answer: without knowing your data, a solution with lubridate would look like this:
 library(lubridate)
 cleantargetcounts$weekday <- wday(ymd(cleantargetcounts$DTE), label = TRUE, abbr = FALSE)

Output of cleantargetcounts$weekday should be a vector with "Monday" "Tuesday" and so on. Then to mark mondays on your plot you could use:
a <-  ggplot(cleantargetcounts)+
   geom_line(aes(x=DTE, y=TOTAL, color = DISPOSITION, group = DISPOSITION), size = 1.2)+
   scale_color_manual(values = c(Approval = "dark green",Denial = "red",Skip = "orange"))+
   geom_point(aes(x=DTE, y=TOTAL, color = DISPOSITION),size = 3.2)+
   geom_text_repel(aes(label=cleantargetcounts$TOTAL, x=DTE,y=TOTAL))+
   theme(axis.text.x = element_text(angle = 45, vjust = 1, hjust=1,
colour = ifelse(cleantargetcounts$weekday == "Monday",
                                         "red","black)
    ))+
   labs( x = "Date", y = "Disposition Count", title ="Disposition Count by Date")

Comment: I will definitely be messing with this option.. though 'right out of the box' it isn't working quite 100%.  The added column is spot on (Mondays are tied to the correct dates) but the plot is also coloring the following Tuesday and wednesday as RED as well.  I will let you know if I can get this working.


Existe diferença entre ser explícito com o tipo do objeto que está sendo criado ou usar apenas new()?

Question: Existe diferença entre
var list = new List<string>();

e
List<string> list = new();

Eu sei que usar var ou o tipo explicitamente dá na mesma, mas não sei se essa nova forma é igual.
Se for igual por que criaram mais uma forma?
Answer: Dá na mesma. É só mais uma forma de expressar mesmo, não muda nada como é compilado ou como vai desempenhar na execução, eles geram exatamente o mesmo código, é quase como se fosse outra inferência, mas neste caso não é porque o tipo está sendo explicitado na declaração da variável.
Uma das vantagens é que pode ser usado em todos os lugares, não só em variáveis locais. Pode por exemplo usar em campos. Agora pode ter uma sintaxe mais curta e sem redundância onde antes não era possível descobrir inequivocamente qual era o tipo.
Mais ainda, pode ser usado em qualquer lugar onde o tipo já foi explicitado antes, por exemplo:
List<Carro> list = new() { new(), new() };

Os dois objetos criados e colocados na lista serão Carros. É exatamente o mesmo que escrever:
List<Carro> list = new List<Carro>() { new Carro(), new Carro() };

Em alguns casos não tem como usar, mas são casos que o var não fica muito bom, perde informação relevante para contextualizar na leitura, o compilador se vira bem, o programador não:
var s = GetListCarro();

Coloquei no GitHub para referência futura.
O compilador pode rodar um pouco mais rápido usando new() do que com var, mas nada muito significativo.
O nome disso é target type.