Finding the solutions of $x^y=y^x$ such that $x,y>e$

Question: I need to show that the set of solutions to the equation $x^y=y^x$ with $x,y>e$, consists precisely of points of the form $(a,a)$ with $a>e$. While this feels intuitively correct ($x,y$ can't both be large without being equal) and using a graphing calculator seems to confirm it, I'm having trouble showing it formally. How should I proceed?
Comment: $$\dfrac{\log x}x=\dfrac{\log y}y.$$
Comment: Hint: the equation is equivalent to $$\frac{x}{\log x} = \frac{y}{\log y} \, .$$Try showing that the function $f(z)=\dfrac{z}{\log z}$ is one-to-one for $z\geq e$.
Comment: @Joe your approach seems the easiest. $f'(z)=\frac{\log z-1}{(\log z)^2}>0$ for $z>e$, therefore $f(z)$ is injective and $x=y$, correct?
Comment: @YvesDaoust Has the easiest job to show that the function is decreasing by taking the derivative
Comment: @V.Ch.: Yes, since $f'(z)>0$ for $z>e$, the function $f$ is one-to-one. By definition, a function $\phi$ is one-to-one on the interval $[a,\infty)$ if $\phi(x)=\phi(y) \implies x = y$ for all $x,y\geq a$. Since $f$ is one-to-one on $[e,\infty)$, the equation $\frac{\log x}{x}=\frac{\log y}{y}$ (equivalent to $x^y=y^x$) only has the solutions $x=y$ on this interval.
Answer: Hint: the equation $x^y=y^x$ is equivalent to $$\frac{x}{\log x} = \frac{y}{\log y} \, .$$Try showing that the function $f(z)=\dfrac{z}{\log z}$ is one-to-one for $z\geq e$.
Comment: @V.Ch.: I'm very glad I could help.
Comment: The derivative is strictly positive for $z>e$, therefore $f(z)$ is injective and $x=y$. Thanks!


Como pegar id de um ImageView no android?

Question: Como consigo pegar um id de uma imagem de um ImageView.
Exemplo, para eu setar uma imagem no meu ImageView eu uso o seguinte código.

imageView.setImageResource(R.drawable.icone_x);

Como eu faço o processo inverso?
Por exemplo, quero receber um inteiro que referencia R.drawable.icone_x, queria mais ou menos isso.

int resID = imageView.getImageResource();

Mas não existe esse método.
Comment: Juarez, não entendi muito bem sua pergunta. Você quer armazenar apenas o resID de um drawable em uma variável? Se for isso, o `R.drawable.icone_x` já faz esse trabalho para você!
Comment: Essa ImageView é dinamica, conforme o usuario clica ela muda de imagem, eu criei um listener e preciso saber qual imagem ela está mostrando no momento.
Answer: Estou assumindo que sua intenção é obter um inteiro referenciando à sua imagem, mas isso não é o que realmente acontece quando você utiliza o método setImageResource. Você pode verificar em ImageView#setImageResource() o que o Android faz por trás, que é buscar um recurso que na maioria do caso é um BitmapDrawable, mas pode ser outro tipo, e então é aplicado ao ImageView.
A melhor solução para o seu caso acredito que seja guardar o nome ou a própria identificação em algum lugar para depois recuperar, por exemplo usando setTag():
imageView.setImageResource(R.drawable.image1);
imageView.setTag("image1");

E então você pode recuperá-lo assim:
int resId = getResources().getIdentifier(imageView.getTag(), "drawable", getPackageName());

Claro, é uma suposição que depende de como você está querendo implantar.
Answer: A resposta do @PauloRodrigues é bem legal. Mas deixo minha sugestão, que seria extender o ImageView, adicionando o comportamento que você quer. É claro que involve um refactoring caso já esteja usando ImageView's em seu aplicativo, mas não involve adicionar mais código (que você pode esquecer) ao setar uma tag no ImageView.
A subclasse ficaria:
public class CustomImageView extends ImageView {

    private int mImageResource;

    public CustomImageView(Context context) {
        super(context);
    }

    public CustomImageView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CustomImageView(Context context, AttributeSet attrs, int defStyle) {
        this(context, attrs, 0, defStyle);
    }

    public CustomImageView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);

        // Recupera o id do resource setado no xml
        final TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.ImageView, defStyleAttr, defStyle);
        mImageResource = a.getResourceId(com.android.internal.R.styleable.ImageView_src, 0);

        a.recycle();
    }

    @Override
    public void setImageResource(int resId) {
        mImageResource = resId;
        super.setImageResource(resId);
    }

    public int getImageResource() {
        return mImageResource;
    }
}

O uso em xml seria parecido com os demais, apenas trocando ImageView por nome.do.seu.pacote.CustomImageView.
Comment: Verdade, no havia pensado nessa soluçao. Obrigado


Xor of numbers in a range

Question: I just came across a question which goes like this
Given an array of n elements , there are m queries of type l,r,t where in the program must take out xor of all numbers less than t and  between index l,r (both inclusive and 0-indexed) .
Example :
Say
arr={2,3,5,1}
Our query is : 0 2 4
Output 1
I can only think of the naive solution of going through the range and just taking the xor of all the numbers less than t but I was just wondering is there any data structure like segment trees which could achieve the task in an efficient manner ?
Comment: Yes. I think Segment tree can work here. You can refer to this link for more info on similar kind of problem. It does XOR of elements in range l,r. I think your problem is an extension of the same problem.
http://www.geeksforgeeks.org/segment-tree-set-3-xor-given-range/
Comment: Don't know if you notice but I need xor of all elements less than t
Comment: Yes. I think we can apply that `t` constraint here in the link I mentioned. I am not sure as I am still trying to do it with that `t` constraint you mentioned. Will let you know if it is actually feasible.
Comment: This problem was at SO some times in last days. Definitely online contest or homework.
Answer: Here's a solution:

Save all the numbers with its index and sort them according to their values (let's call it an array a).
First save all the queries with query id and sort them according to t (let's call it an array q).
Take a segment tree where every node contains 0 by default. It is a segment tree that contains xor in range.
Iterate over q and add all the numbers from a in the segment tree those are less than t for each query and take the xor in the given query range of that and save it to an array using query id (let's all it ans).
Print the ans array.

Complexity of this solution is O(nlog(n) + mlog(n)).

Xor of numbers in a range


Provide instance without interface using Dagger

Question: There is way to provide instance without actual constructor calling.
class ModelImpl @Inject constructor(...): Model{}

@Provides
fun model(inst: ModelImpl): Model = inst

Is there way to do the same if there is no interface? Dagger knows already all dependencies for ModelImpl, so it can create an instance.
This gives obviously dependency cycle:
@Provides
fun model(inst: ModelImpl): ModelImpl = inst

Answer: When you use constructor injection Dagger can construct the object for you and you're already using Dagger to create ModelImpl to use it as a binding for Model in your example!
class ModelImpl @Inject constructor(...): Model{}

@Provides
fun model(inst: ModelImpl): Model = inst

// somewhere else...
// both variants would work!
@Inject lateinit var modelImpl : ModelImpl
@Inject lateinit var model : Model

The same would work without the interface
class ModelImpl @Inject constructor(...)

// somewhere else...
@Inject lateinit var model : ModelImpl

If you annotate the constructor then Dagger can create the object for you (if all dependencies can be resolved). This works the same wherever you request the object / dependency,

as a parameter in a @Provides annotated method (as your example)
as a field injection property (@Inject lateinit var)
as a parameter in another objects constructor
as a provision method in a component (fun getFoo() : Foo)

All of the following would work
// foo and bar can both be constructor injected
class Foo @Inject constructor()
class BarImpl @Inject constructor(val foo : Foo) : Bar

@Module
interface BarModule() {
  @Binds  // you should prefer Binds over Provides if you don't need initialization
  // barImpl can be constructor injected, so it can be requested/bound to its interface here
  fun bindBar(bar : BarImpl) : Bar
}

@Component(modules = BarModule::class)
interface BarComponent {
  fun getBar() : Bar // returns barImpl due to binding
}

@Inject lateinit var bar : BarImpl // but we could as well use the implementation directly
@Inject lateinit var bar : Foo // or just foo

I recommend you to start with a small example, then compile the project and have a look at the generated code. If something is wrong you'll get errors immediately, while you can play around and try different setups!
Comment: Thanks! That makes it clear. It turns out that `Module` is not even required for providing instances.
Answer: An addition to David Medenjak anwser. If there is no interface and there is no requirement to group instances into modules, then module could be omitted completely:
class Model @Inject constructor(...){
  //...
}

@Component
interface SomeComponent{
  fun model(): Model
}

val model = someComponent.model()


ssh not working after docker installation

Question: I have created a virtual machine which has centos7 installed. I have installed docker CE successfully too using offical docs. After I add my user to docker group, I tried starting the docker service using this command:
sudo systemctl start docker

but it gets stuck & I am exited from putty. When I try to login again through putty, it says connection refused.
ssh login through putty does not work unless I restart the system.
any suggestions?
Comment: @fragmentedreality docker is not starting. so no container is yet open
Comment: Have you by any chance started a container inside that VM, that 'steals' the port 22, which starts with docker agent?
Answer: May be the he Docker default bridge (docker0) network conflicts with your internal network hosts access.
Try to configure the default bridge to a different subnet.
Look at Use bridge networks documentation for details.
May be intersting this post too How do I configure the default bridge (docker0) network for Docker Engine to a different subnet?
Comment: For those that end up here from Google. I had to create the daemon.json file as @gile points out.


checkbox inside gridview item template is generating a span

Question: I have the following grid:
<asp:GridView ID="myGrid"
                    AutoGenerateColumns="true"
                    runat="server" CellPadding="4" ForeColor="#333333" GridLines="None" Width="100%">
                    <AlternatingRowStyle CssClass="rowEven" />
                    <HeaderStyle CssClass="rowHead" />
                    <RowStyle CssClass="row" />
                    <Columns>
                        <asp:TemplateField>
                            <ItemTemplate>
                                <asp:CheckBox ID="CheckBox1" runat="server" data-flag="false" />
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                </asp:GridView>

and its generating
 <input id="ctl00_PlaceHolderMain_myGrid_ctl02_CheckBox1" type="checkbox" name="ctl00$PlaceHolderMain$myGrid$ctl02$CheckBox1" />

I want the data flag inside the checkbox. not as an span
Comment: Handle `RowDataBound` event; find the checkbox and set it manually: `cb.Attributes["data-flag"] = "false";`
Answer: Possible and simple workaround is to use the simple html checkbox with a runat="server"
<ItemTemplate>
    <input id="Checkbox1" runat="server" type="checkbox" data-flag="false" />
</ItemTemplate>

Answer: I think you should use Checked="false" instead of data-flag.


Jmeter validating response

Question: In the below code  'ScenarioName' represents the test case name and 'DeviceID' as input parameter, while fetching response. Now I need to crosscheck each field of the response data with the field that are given in the input csv. So if it gets matched then only we will say the result is pass or else fail..
Code as of now:(It just hit the service and write the response in result CSV. But before writing it in resultant CSV, we need to validate whether all the field in the response are gets matched corresponding to the value for that particular scenario specified in the input CSV, only then we would come to a conclusion. whether the test case is pass or fail. )
Beanshell post processor code:
scenario = vars.get("ScenarioName");
deviceid = vars.get("DeviceID");
eventname = vars.get("C_EventName");
eventtype = vars.get("C_EventType");
areaName = vars.get("C_AreaName");

n = vars.get("counter");

filename = "C:\\RestService\\"+ n +".csv";

f = new FileOutputStream(filename, true);

p = new PrintStream(f);

this.interpreter.setOut(p);

print( scenario + ", " + etrTimestamp + ", " + eventname + ", " + eventtype + ", " + areaName + ", " + areaType  + ", " + additionalInfo  + ", " + resultStatusCode + ", " + resultStatusMessage);

f.close();

Now My input file:
ScenarioName   DeviceID  Execution

Validate event   52226406   Yes

invalid ID       11501233   Yes

But input file should be:
ScenarioName       DeviceID     Execution   EVENTNAME     REsultCODE

Validate event      52226406      Yes       Hurricane         200

invalid ID          11501233      Yes        Tornado          404

Now my Output is:
ScenarioName      DeviceID     Execution    EVENTNAME      REsultCODE

Validate event    52226406       Yes        Hurricane          200

invalid ID        11501233       Yes        Tsunami            404

But It should be:
ScenarioName       DeviceID           EVENTNAME      REsultCODE    Result

Validate event     52226406           Hurricane       Event        Pass

invalid ID         11501233           Tsunami         404          Fail

So let's say for DeviceID  52226406 if we are validating the test case, then we would say the result as pass only if all the fields exactly match with data present in the input csv….But For DeviceID 11501233   Event type should be Tornado But in response we are getting as Tsunami so it should fail(After we match with the input CSV)
What should my code and how?
Answer:
Be aware that starting from JMeter 3.1 it is strongly recommended to use JSR223 Test Elements and Groovy language for scripting so consider migrating to JSR223 Assertion and Groovy language on next available opportunity.
Your requirement can be accomplished without any scripting, like:

You already have expected variable in the CSV file which can be extracted using CSV Data Set Config
You can extract actual variables from the response using suitable JMeter PostProcessor, given you have Rest in your code my expectation is that it would be JSON Extractor
2 variables can be compared using Response Assertion like:

If you need to store the actual data for any reason you can use Sample Variables property or Flexible File Writer
Comment: In beanshellpostprocessor  facing error:
if((vars.get("C_EventName").equals("${EventName}"))&& (vars.get("C_AreaName").equals("${AreaName}")) && (vars.get("C_resultStatusMessage").equals("${ResultStatusMessage}")) ;
{IsSuccess = true;
n = vars.get("counter");
fname = "C:\\RestService\\Results\\"+ n +".csv";
f = new FileOutputStream(fname, true);
p = new PrintStream(f);
this.interpreter.setOut(p);
print( scenario + ", " + etrTimestamp + ", " + eventname + ",  " + areaName + ",  " + resultStatusCode + ", " + resultStatusMessage);
f.close();
}else{IsSuccess = false;
}
Comment: just before writing if I go for validation in bean shell postprocessor. getting error

Jmeter validating response


The relationship between ε and δ in the (ε, δ)-definition of limitor

Question: Does the biggest δ also get smaller as ε is getting smaller ? why ?(exclude the case when f(x) is a constant function.)
P.S.I must declare I only have some basic knowledge of limit ,I started to learn calculus a few days ago .
Comment: What do you mean by biggest $\delta$?
Comment: no matter how small ϵ is, you can find countless  δ that can meet the requirement ,then there should be a biggest δ of them ,i.e. the  supremum of them .
Comment: That may be true in some cases, but I have a strong feeling that there are times when the set you speak of does not have a supremum.
Comment: I think you'd better give an example !
Comment: How about this one: Let $f(x)=\ln(x)$. Using the $\epsilon$-$\delta$ definition of continuity, you should be able to verify that given $\epsilon>0$, and $x,y \in \Bbb{R}$ with $\delta = y(e^{\epsilon}-1)$, then $|\ln(x)-\ln(y)|<\epsilon$ anytime that $|x-y|<\delta$. But notice that $y$ can be as large as we want and it won't affect $\epsilon$. However, it will make $\delta$ as large as we want.
Comment: @graydad: I'm sure I'm misunderstanding something here, but isn't $y$ the point at which the limit is being evaluated?  In which case, wouldn't $y$ be held constant during the evaluation?  Therefore wouldn't the supremeum user1485853 mentions also be computed with $y$ held fixed?
Comment: I don't mean to suggest that there aren't cases in which the supremum is $\infty.$  There of course are.  A constant function is one example: $\sup\delta=\infty$ for any $\epsilon.$  Another is the $\sin$ function.  Suppose we apply the definition to the evaluation of $\lim_{x\to 0}\sin x.$  For any $\epsilon>1,$ we have $\sup \delta=\infty.$  If you decrease $\epsilon$ from $3$ to $2,$ $\sup\delta$ does not decrease.  But clearly it can never increase, as is shown in Umberto P.'s answer.
Comment: @WillOrrick I was evaluating at $x$, which is why I thought it would be okay to let $y \to \infty$. But I definitely agree my example isn't air tight! :) I was trying to come up with an example for OP that wasn't the constant function. You have an argument for the sine function though?
Comment: I think you mean lnx→1 when x→e here, so $y$ cannot be too large . @Umberto P.'s proof is very convincing ,you can have a look .
Comment: @graydad: $\sin$ takes values in $[-1,1].$  So if $\epsilon>1$ then $\lvert\sin x-0\rvert<\epsilon$ for all $x.$
Comment: @Will Orrick  For every  ϵ>0 in the definition ,not just  ϵ>1.
Comment: If $\epsilon=0.5$ then $\lvert\sin x-0\rvert<\epsilon$ for $\lvert x-0\rvert<\frac{1}{6}\pi$ but not for all $x.$
Comment: @Will Orrick I don't know why you require it for all x ?
Comment: As I understood it, the question was to find an example of a non-constant function for which $\sup\delta$ was $\infty$ or, more generally, for which  $\sup\delta$ was constant rather than strictly decreasing (as a function of $\epsilon$).  The sine function provides such an example: $\sup\delta$ takes the constant value $\infty$ for all $\epsilon\in(1,\infty).$  For $\epsilon\in(0,1],$ $\sup\delta$ is strictly decreasing.
Comment: To add to my previous comment: if $\lvert f(x)-L\rvert<\epsilon$ for all $x,$ that's the same thing as $\Delta(\epsilon)=\infty.$  I wanted to show an example where the condition $\Delta(\epsilon)=\infty$ held over a range of $\epsilon$ values (to show that $\Delta(\epsilon)$ doesn't always decrease).  Equivalently, I wanted to exhibit a limit for which $\lvert f(x)-L\rvert<\epsilon$ held for all $\epsilon$ in a range of values with no restriction whatsoever on $x.$
Comment: In the comments to Umberto P.'s answer, I give an example where $\Delta(\epsilon)$ remains constant for all $\epsilon,$ not just for all $\epsilon$ in some range of values.  Certainly there are many such examples.  However, I think a better answer to your original question is that $\Delta(\epsilon)$ generally decreases with $\epsilon,$ but that there are examples where it remains constant rather than decreasing.
Comment: In $\epsilon$-$\delta$ arguments, there is no reason to have $\delta$ be as large as it can be.  People often let $\delta$ be smaller than it could be for the sake of a simpler mathematical argument.  Furthermore, if the $\epsilon$-$\delta$ definition of limit holds, then it is correct to say that that $f(x)$ gets arbitrarily close to $L$ as $x$ gets closer and closer to $a.$  That's because as $x$ gets closer and closer to $a,$ it will eventually be less than a distance of $\delta$ from $a.$  Beyond that point, $f(x)$ is guaranteed to be within $\epsilon$ of $L.$  No matter how small...
Comment: ... $\epsilon$ is, there will always be such a point beyond which $f(x)$ is within $\epsilon$ of $L.$  That's what the "there exists a $\delta$" business is all about.
Answer: Let's quantify $\displaystyle \lim_{x \to x_0} f(x) = L$.
For every $\epsilon > 0$ there exists $\delta > 0$ so that $0 < |x-x_0| < \delta$ implies $|f(x) - L| < \epsilon$.
Define $\Delta(\epsilon) = \sup \delta$, where the supremum (maybe $\infty$) is taken over all $\delta$ satisfying the quantified statement for a fixed $\epsilon$. $\Delta(\epsilon)$ is the "biggest $\delta$" you are talking about.
Suppose that $0 < \epsilon_1 < \epsilon_2$.
Let $\delta > 0$ be any value for which $0 < |x-x_0| < \delta$ implies $|f(x) - L| < \epsilon_1$. Then in turn $0 < |x-x_0| < \delta$ implies $|f(x) - L| < \epsilon_2$. Thus $\delta \le \Delta(\epsilon_2)$. Take the supremum over all such $\delta$ to conclude $$\Delta(\epsilon_1) \le \Delta(\epsilon_2).$$
That is, $0 < \epsilon_1 < \epsilon_2$ implies $\Delta(\epsilon_1) \le \Delta(\epsilon_2)$ so that the "biggest $\delta$" is nonincreasing as $\epsilon \searrow 0$.
Comment: I wonder when Δ(ϵ1)=Δ(ϵ2), does the function has to be a constant function ?why ?It would be better to give some proof .thanks in advance !
Comment: @user1485853: for the example of $\sin x$ in the comments to your post, we have $\Delta(2)=\Delta(3)=\Delta(1.1)=\ldots.$  This answers your question in the negative, since $\sin$ is not a constant function.
Comment: @Will Orrick but you require ϵ>1 there ,in the formal definition ,only require ϵ>0 ,i.e.it could be any positive real number .
Comment: Are you asking about the case where $\Delta(\epsilon_1)=\Delta(\epsilon_2)$ for all $\epsilon_1,\epsilon_2>0,$ or the case where $\Delta(\epsilon_1)=\Delta(\epsilon_2)$ for some $\epsilon_1,\epsilon_2>0?$  Your question didn't specify the former, so I came up with an example for the latter.
Comment: @user1485853: OK, here's an example of a non-constant function for which $\Delta(\epsilon)$ takes a finite constant value.  Let $f$ be defined by $$f(x)=\begin{cases}17 & x=5\\ 8 & x>5\text{ or }3\epsilon,$ contradicting the assumption that $\lvert f(x)-L\rvert<\epsilon$ whenever $x\in(a-c,a+c)\setminus\{0\}.$  So $f$ is constant in the interval $(a-c,a+c),$ except possibly at $a.$
Comment: Thanks for your great help !!! yes , f is constant in the interval (a−c,a+c), except possibly at a, and perhaps not in the entire domain.

as @Umberto P. said the "biggest δ" is nonincreasing as ϵ↘0 in this question .


How set charset in a primefaces webapp?

Question: Let me share my unique disapointment with the primefaces 3.1, until now...
I'm using a phew components in a RichFaces app, everthing fine when i realized an issue, some characters in my native language are displayed wrong, even UTF-8 charset being declared in all places i know it's required.
The problem occur when is entered some special character like "São Paulo" in a  and submited the page. The data after submit is redisplays as "São Paulo"
I already tried the folowing work-around:
1)Eclipse IDE : text file enconding option
2)jsf files:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

3)JBOSS server.xml:
<Connector protocol="HTTP/1.1" URIEncoding="UTF-8" port="${jboss.web.http.port}" address="0.0.0.0"
         redirectPort="${jboss.web.https.port}" />

4)web.xml:
<?xml version="1.0" encoding="UTF-8"?>

5)jsf file:
<h:form acceptcharset="UTF-8" enctype="application/form-data">

6)upgrade the primefaces version to 3.2
Thanks for any help!
;-)
Comment: It's worth noting that PrimeFaces 3.2 has been released. I don't know if that fixes your problem, but I guess it can't hurt to try.
Comment: Are you using RichFaces or PrimeFaces? You yelled "RICHFACES" which is rather confusing. If RichFaces, are you using JSP or Facelets? Please describe the problem in more detail, it's not clear how and where exactly the problem is occurring. Describe the steps in detail how to reproduce the problem. Describe the expected/unexpected results in detail. E.g. "I entered XYZ in a `h:inputText`, after submit it redisplays as ZYX in `h:outputText`" and so on.
Comment: tried that right now, doesn't fix my issue...thanx anyway!
Comment: Yes i'm using both, facelets. ok i'll edit the post with more detail...
Comment: Thank you. What exactly does `Content-Type` response header contain? You can find it in Network tab of webbrowser's developer tool (press F12 in Chrome/IE9/Firebug). Is the form submit request been issued by ajax or a normal synchronous request? What if you try the other type of request?
Comment: `Server: Apache-Coyote/1.1
X-Powered-By: Servlet/3.0; JBossAS-6, JSF/2.0
Pragma: No-cache
Cache-Control: no-cache
Expires: Wed, 31 Dec 1969 21:00:00 BRT
Content-Type: text/html;charset=UTF-8
Transfer-Encoding: chunked
Date: Thu, 15 Mar 2012 13:17:39 GMT

200 OK`

I'm using a normal request, but i've tried with ajax and also occured  the issue. Let me tell more details, when i put a break-point at the ManageBean the field returns the right value, but when it will be send back to the view its encoding is corrupted.
Answer: i've been forced to create a filter who sets the charset for every request...
public class CharacterEncodingFilter implements Filter {

    @Override
    public void destroy() {
        // TODO Auto-generated method stub
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {
        response.setCharacterEncoding("UTF-8");
        request.setCharacterEncoding("UTF-8");
        chain.doFilter(request, response);
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
        // TODO Auto-generated method stub
    }

}

that's solve my issue
Answer: I just uncomment that portion in conf/web.xml (Tomcat server web.xml) that filter all request and convert into UTF-8.

 <filter>
        <filter-name>setCharacterEncodingFilter</filter-name>
        <filter-class>org.apache.catalina.filters.SetCharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
 </filter>

  <filter-mapping>
        <filter-name>setCharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
  </filter-mapping>

How set charset in a primefaces webapp?


Possible Ecommerce Product, Size, and Option combinations

Question: I have an ecommerce site where you can specify the size of a product and any number of options depending on the different products.  Each option has a category.  For example, for each product you can choose:
Size - 8.5 x 11, 11 x 17, 8.5 x 5.5
Paper - 100#, 14pt, 80#
Coating - Aqueous, UV
Coating is a category while UV is an option.  The customer can only choose one size, one type of paper, and one coating option.
The products have different numbers of categories and different numbers of options in those categories.  Also, sizes can cause the number of options and categories to vary.
Update - To clarify, not every option is available for every size.  So some sizes have 3 coating options available, for example, and some sizes have 2 coating options available.
How do I calculate the total number of possible size and option combinations?  It could be these are variations or permutations.
Answer: The total number of combinations can be found by multiplying together the number choices over each of the categories. From what I gather from your post, this would be something like:
$$
(\text{Number of paper sizes}) \times (\text{Number of types of paper}) \times (\text{Number of coating options}) \times \dotsb
$$
Then for something like UV, you treat it like a category where the customer has two choices: either UV or not UV.
To address the edited question and @fanda455's comment:
You would then have to break it up into cases. To simplify the situation, suppose we have two classes of paper size called large and small and that the possible paper type/coating options for large and small paper are  different. Then the total number of combinations would be:
$$
(\text{Number of large paper sizes}) \times (\text{Number of types of large paper}) \times \dotsb \\
+ \\
(\text{Number of small paper sizes}) \times (\text{Number of types of small paper}) \times \dotsb
$$
If there are any further sub-restrictions, like if there are only certain types of coating options for different types of large paper, the you would have to break it down further into sub-cases.
Comment: That would work if every type of paper and every type of coating was available for every size.  But some sizes only have 2 coating options instead of 3 coating options for the other sizes.  I've updated the question to clarify the point.  How would I then calculate the possible combinations?


spliting in c++ like what we do in c#

Question:
Possible Duplicates:
How to split a string in C++?
Splitting a C++ std::string using tokens, e.g. ";"

think I have this string :
string a = "hello,usa,one,good,bad";

I want to splitting this string with ,
so I need a array of string like here :
string *a ; a = { hello , usa , one , good , bad }

what shoudl I do ?
Answer: If you really don't want to code this on your own you can do a web search for "c++ tokenize string" and take, for example, a look here: CPPHOWTO
Comment: This should be a comment too!
Answer: This simple AXE parser will do it:
std::vector<std::string> strings;
auto split = *(*(axe::r_any() - ',') >> e_push_back(strings));
split(a.begin(), a.end());

spliting in c++ like what we do in c#


For any two finite sets $S$, $T$ show that the average of $|S|$and $|T|$ does not exceed $|S \cup T|$

Question: I have this problem for my mathematics course and I am not exactly sure how to approach it. If I could just get some hints about how to start this problem it would be greatly appreciated.
I have some ideas about how I should start:
I was thinking I could do $(|S|+|T|)/2$ and have its less than or equal to $|S|+|T|-|S \cap T|$. I got this far but I am not sure what to do after this.
Thanks in advance :)
Comment: Hint:  the average can not exceed the maximum.  The union can not be less than the maximum.
Comment: @parsiad The second inequality does not hold (for instance take $S=T=\{1\}$)
Answer: Inclusion/exclusion gives you
$$|S|+|T|=|S\cup T|+|S\cap T|\leq 2|S\cup T|\ .$$


Calculating $\int x dx$ using trigonometric functions

Question: Well, I tried to solve the integral: $$\int x dx$$ using trigonometric functions instead of using the general formula for it. (If $n \neq -1$,$\int x^n dx=\frac{x^{n+1}}{n+1}+C$)
So I gave it shot in this way:
$$\int x dx = \int \sin\theta \cos\theta d\theta = \dfrac{1}{2}\int \sin2\theta d\theta=\dfrac{1}{2}\big(\dfrac{-1}{2}\cos^2\theta\big)+C=\dfrac{-1}{4}(\cos^2\theta-\sin^2\theta)+C$$
$$x=\sin\theta ,\cos\theta=\sqrt {1-x^2}, dx = \cos\theta d\theta$$
Thus we substitute them:
$$\int x dx = \dfrac{1}{2}\int \sin2\theta d\theta=\dfrac{-1}{4}(\cos^2\theta-\sin^2\theta)+C=\dfrac{-1}{4}+\dfrac{x^2}{2}+C'$$
If I had solved the integral with the general formula I wouldn't have got partial amount of the integration constant($\dfrac{-1}{4}+C'$) as my final answer.
Simply, my question is why another constant would rise up when I do the integration with trigonometric substitution?I know that I can disregard the appeared constant but why does it even rise up?
If I'm still not clear enough, please tell me to correct my question.
Comment: It must be "if $\;n\neq\color{red}{-1}\;$ ..."
Comment: $C'-\frac{1}{2}$ is just a constant. Name it $D$.
Comment: @DonAntonio Thanks, I edited the post.
Answer: There is no other constant, because you see, $\int\sin 2\theta\, d\theta = \dfrac{1 - \cos 2\theta}{2} = \sin^2 \theta$. Oh, what's that, you're saying it's just $\dfrac{-\cos 2\theta}{2}$? Well okay then, I'll say that $\int x\, dx = \dfrac{x^2}{2} -\dfrac{1}{4}$.
I hope you see what's going on. There's no unique anti-derivative. You always make a choice when you write it as some particular function. My favourite example is, $$\int \dfrac{-1}{\sqrt{1 - x^2}} dx = \cos^{-1} x$$ because $\dfrac{d}{dx} \cos^{-1}x = \dfrac{-1}{\sqrt{1 - x^2}}$, but hey $$\int \dfrac{-1}{\sqrt{1 - x^2}} dx = -\int \dfrac{1}{\sqrt{1 - x^2}} dx = -\sin^{-1} x$$ because $\dfrac{d}{dx}\sin^{-1} x = \dfrac{1}{\sqrt{1 - x^2}}$. What's going on? $\dfrac{\pi}{2} - \sin^{-1} x = \cos^{-1} x$.
The example in your question is similar, only there the constant is explicit, it is visible. But there's no reason to say that $1 - \cos2\theta$ is any less of a function that $-\cos2\theta$, so you cannot fundamentally discriminate between the two (when deciding which one the anti-derivative "ought to be").
Comment: I was using the same example, but you got there first.
Comment: @robjohn I wondered what the second answer was that showed up in the homepage where it said "2 Answers" but wasn't there in this page!
Comment: Let me try my best, I'm not asking the difference between the final answers and I'm not claiming they're different answers, what I'm asking is why the $\frac {-1}{4}$ constant would rise up when we use the substitution rather than the general formula?
Comment: why $\frac {-1}{4}$ would be detached from the general constant(I call it $C$) and join the integration answer when we use the trigonometric substitution?
Answer: The constant of integration is arbitrary and two anti-derivatives are equivalent if they differ by a constant.
For example, since
$$
\int0\,\mathrm{d}x=C
$$
we get not only
$$
\int\cos(x)\,\mathrm{d}x=\sin(x)+C
$$
but also
$$
\begin{align}
\int\cos(x)\,\mathrm{d}x
&=\int(\color{#C00000}{\cos(x)}+\color{#00A000}{0})\,\mathrm{d}x\\
&=\int\color{#C00000}{\cos(x)}\,\mathrm{d}x+\int\color{#00A000}{0}\,\mathrm{d}x\\[6pt]
&=\color{#C00000}{\sin(x)+C}+\color{#00A000}{C}
\end{align}
$$
where the constants $\color{#C00000}{C}$ and $\color{#00A000}{C}$ are possibly different constants.

In the particular case you give, using $x=\sin(\theta)$,
$$
\begin{align}
\int x\,\mathrm{d}x
&=\int\sin(\theta)\,\cos(\theta)\,\mathrm{d}\theta\\
&=\int\tfrac12\sin(2\theta)\,\mathrm{d}\theta\\
&=-\tfrac14\cos(2\theta)+C\tag{$\ast$}\\[3pt]
&=-\tfrac14(1-2\sin^2(\theta))+C\\[3pt]
&=\tfrac12\sin^2(\theta)+C-\tfrac14\\[3pt]
&=\tfrac12x^2+C-\tfrac14
\end{align}
$$
In step $(\ast)$, note that although $x=0$ corresponds to $\theta=0$, $-\frac14\cos(2\theta)=-\frac14$ at $\theta=0$. This is where the $-\frac14$ is introduced, if that is what you are asking about.
However, even simpler alterations to the method of integration can yield different, but equivalent, forms of the constant of integration:
$$
\begin{align}
\int x\,\mathrm{d}x
&=\frac12\int 2x\,\mathrm{d}x\\
&=\frac12\left(x^2+C\right)\\[6pt]
&=\tfrac12x^2+\tfrac12C
\end{align}
$$


rust image post request

Question: I use qrcode-rust which returns its result as image::ImageBuffer. I need to post the png result to thumbor server. How to convert this image buffer to Vec  ?.
I try code below but my buf moved and I can do nothing about it.
let code = QrCode::new(arg1.as_bytes()).unwrap();
let images = code.render::<Luma<u8>>().build();
let mut buf: Vec<u8> = Vec::new();
let dims = images.dimensions();
let mut headers = HeaderMap::new();

image::png::PNGEncoder::new(buf)
    .encode(&images.into_raw(), dims.0, dims.1, ColorType::Gray(8))
    .expect("Error on encoding to png");

let len = buf.len(); //error here
headers.insert(CONTENT_TYPE, "image/png".parse().unwrap());
headers.insert("Slug", "photo.jpg".parse().unwrap());

Comment: What do you mean by "error here"? What is the exact error message?
Answer: I copied an answer from How do I encode a Rust Piston image and get the result in memory? and changed
image::png::PNGEncoder::new(buf.by_ref()))
    .encode(
         &images.into_raw(),
         dims.0,
         dims.1,
         ColorType::Gray(8),
    ).expect("Error on encoding to png");

And everything works now.

rust image post request


Delete a iptables chain with its all rules

Question: I have a chain appended with many rules like:
> :i_XXXXX_i - [0:0]
> -A INPUT -s 218.104.22.168/32 -j i_XXXXX_i
> -A INPUT -s 126.96.36.199/32 -j i_XXXXX_i
> -A INPUT -s 188.8.131.52/32 -j i_XXXXX_i
> -A INPUT -s 22.214.171.124/32 -j i_XXXXX_i
> -A OUTPUT -d 2188.8.131.52/32 -j i_XXXXX_i
> -A OUTPUT -d 188.8.131.52/32 -j i_XXXXX_i
> -A OUTPUT -d 18.104.22.168/32 -j i_XXXXX_i
> -A OUTPUT -d 184.108.40.206/32 -j i_XXXXX_i

when I try to delete this chain with:

iptables -X XXXX

but got error like (tried iptables -F XXXXX before):

iptables: Too many links.

Is there a easy way to delete the chain by once command?
Comment: Try this: `iptables-save | grep -v i_XXXXX_i | iptables-restore`
Comment: I've not seen iptables barf like that before when trying to flush.
Comment: 2 many is many :) if I try to delete the rules first, it will like typing many times: iptables -D OUTPUT -d XXX/32 -j i_XXXXX_i
Comment: Just curious... *how* many rules is "many" ?
Comment: @StevenMonday why not write as answer, this is the most useful one (alternative do this via file and edit file).  Only thing it does not remove is complete tables ("raw" anyway)
Comment: @StevenMonday You ingenious bastard!  This is the best answer here! ♥
Answer: You can't delete chains when rules with '-j CHAINTODELETE' are referencing them. Figure out what is referencing  your chain (the link), and remove that. Also, flush then kill.

-F, --flush [chain]
Flush the selected chain (all the chains in the table if none is given).  This is equivalent to deleting all the rules one by one.
-X, --delete-chain [chain]
Delete the optional user-defined chain specified.  There must be no references to the chain.  If there are, you must delete or  replace  the
  referring  rules  before  the  chain can be deleted.  The chain must be empty, i.e. not contain any rules.  If no argument is given, it will
  attempt to delete every non-builtin chain in the table.
Comment: @timy StevenMonday's comment will single-pass remove any references to the chain. Perhaps not ideal, but darned close.
Comment: I just want to find a way to delete the chain(has many '-j CHAINTODELETE' ref rules) directly, but from your answer, it seems impossible :(
Comment: Works like a charm.

iptables -nvL|grep "^Chain.*0 references"|awk '{print $2}'|while read LINE; do iptables -X $LINE; done
Answer: This is potentially off-topic, but it's what I did after I found this post!
For some use cases the iptables -D  option might be useful. Since it allows you to clear out referring rules added programmatically with -A (if you know precisely how you added them).
E.g
    iptables -N MYCHAIN
    iptables -A INPUT -i interface -j MYCHAIN
    iptables -A MYCHAIN -j ACCEPT

can be reversed with
   iptables -D INPUT -i interface -j MYCHAIN
   iptables --flush MYCHAIN
   iptables -X MYCHAIN

Answer: You need two steps, but this does it in one command.
Create a file, and place this in it.
# Empty the entire filter table
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
COMMIT

Save the file as "clear-all-rules".  Now, do this command:
iptables-restore < clear-all-rules

Now you can clear it anytime with just one command.
Comment: +1 This is actually the fastest way to start with a clean fw config.
Answer: Here's an alternate plan. It involves three commands, not one, but with luck, it should work.
Dump your iptables ruleset to a file:
iptables-save > /tmp/iptables.txt

Remove ALL uses of (and references to) the offending chain:
sed -i '/i_XXXXX_i/d' /tmp/iptables.txt

Then reload the ruleset:
iptables-restore < /tmp/iptables.txt && rm /tmp/iptables.txt

Answer: In the iptables man file there is an option -S

S, --list-rules [chain]
                Print  all  rules  in  the selected chain.  If no chain is selected, all chains are printed like iptables-save. Like every other iptables
                command, it applies to the specified table (filter is the default).

By using iptables -S | grep <CHAINNAMEHERE>. For examples:

root@root:~# iptables -S | grep TRAFFICLOG
-N TRAFFICLOG
-A FORWARD -i eth0 -j TRAFFICLOG

you can then see which rules are blocking the deletion of the chain from the table. Go through each rule (except the iptables -N <CHAINNAMEHERE> and delete the rule by using the -D option

-D, --delete chain rulenum
                Delete  one  or more rules from the selected chain.  There are two versions of this command: the rule can be specified as a number in the
                chain (starting at 1 for the first rule) or a rule to match.

For example iptables -D FORWARD -i eth0 -j TRAFFICLOG. After you have deleted each rule for your chain flush the chain with the -F option, iptables -F <CHAINNAMEHERE>.

-F, --flush [chain]
                Flush the selected chain (all the chains in the table if none is given).  This is equivalent to deleting all the rules one by one.

Then delete your chain with the -X option, iptables -X <CHAINNAMEHERE>

-X, --delete-chain [chain]
                Delete  the  optional  user-defined chain specified.  There must be no references to the chain.  If there are, you must delete or replace
                the referring rules before the chain can be deleted.  The chain must be empty, i.e. not contain any rules.  If no argument is  given,  it
                will attempt to delete every non-builtin chain in the table.

Iptables is a complicated tool set so an ideal tutorial is needed. You can try one out at www.iptables.info
Comment: This helped a lot because flush cleans the chain itself but not the references to it in the other chains.
Answer: Something along these lines will get all of them in a single line without taking iptables down in any way.
for chain in `iptables -L |grep i_XXXXX_i|awk '{ print $2 }'`; do iptables -X $chain; done

Answer: This will spit out chains and delete them
for i in $(iptables -S | awk '{print $2}' | uniq ); do iptables -F $i && iptables -Z $i && iptables -X $i  ; done

Answer: I have found that you can remove the rules and chain by editing the rules file in /etc/iptables/rules.v4. If you delete the unwanted chain in this file and then reload iptables, you should no longer see the chain when doing a iptables -L.
Comment: This file exists only on certain Linux distributions, and then only on certain _versions_ of certain Linux distributions.


What does the right side of Hoeffding's Inequality tells me?

Question: The following is Hoeffding's Inequality:
$P(|\nu - \mu| > \epsilon) \leq 2e^{-2\epsilon^2N}$
The left side looks like a probability notation but the right side becomes $2$ when the exponential part becomes very close to zero, then I would get $2$ for the right side. What does the number $2$ mean?
Answer: The Hoeffding's inequality tells that how likely $\nu$ is more than $\epsilon$ away from $\mu$. More specifically, it upper bounds the probability that $\nu$ is more than $\epsilon$ away from $\mu$. As you can see, the term in the RHS decreases as $\epsilon$ gets larger; that is, $\nu$ is more likely to be near $\mu$ and is less likely to be very distant from $\mu$.
The number $2$ here is just an upper bound. It states that the probability that $\nu$ is more than $\epsilon$ away from $\mu$ is not greater than $2$ when $\epsilon$ is very small. Actually, the upper bound $2$ here is quite loose here and it does not provide any insight. However, when $\epsilon$ gets larger, the upper bound can be much smaller than $1$, and in this case, we can use it to estimate the probability rather than computing the probability exactly.
Comment: Thank you for your explanation and could you please let me have an example of this? and do we actually use this?
Comment: @user122358 One example is to set $\epsilon = \sqrt{\ln N / N}$ and therefore the RHS is equal to $\frac{2}{N^2}$. That is, with probability at least $1 - \frac{2}{N^2}$, the value of $\nu$ would be in the range $[\mu - \epsilon, \mu + \epsilon]$.
Comment: Uhmm.... could you show me the step by step calculations? You set $\epsilon=\sqrt{\ln dfrac{N}{N}$ then the hoffding's inequality will look like

$P(|\nu - \mu|) > \sqrt{\ln dfrac{N}{N} \leq 2e^{-2(\sqrt{\ln dfrac{N}{N})^2N}$
Comment: @user122358 $-2\epsilon^2N = -2 \cdot \frac{\ln N}{N} \cdot N = -2\ln N$ and $2e^{-2\ln N} = \frac{2}{N^2}$.
Comment: How can I practically use it?
Comment: @user122358 See also this example. http://stats.stackexchange.com/questions/161303/how-to-use-hoeffdings-inequality-to-find-a-confidence-interval
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/56485/discussion-between-user122358-and-yikai).


Visual signature with pdfbox 1.8.8

Question: I'm trying to produce PDF with visual signature and pdfbox. I have two streams and it seems that pdfbox can deal only with files. I didn't manage to make it work without three temporary files. I can see from here that API has changed, but still it deals with files.
public void signPdf(InputStream originalPdf, OutputStream signedPdf,
        InputStream image, float x, float y,
        String name, String location, String reason) {

    File temp = null;
    File temp2 = null;
    File scratchFile = null;
    RandomAccessFile randomAccessFile = null;
    OutputStream tempOut = null;
    InputStream tempIn = null;
    try {
        /* Copy original to temporary file */
        temp = File.createTempFile("signed1", ".tmp");
        tempOut = new FileOutputStream(temp);
        copyStream(originalPdf, tempOut);
        tempOut.close();

        /* Read temporary file to second temporary file and stream */
        tempIn = new FileInputStream(temp);
        temp2 = File.createTempFile("signed2", ".tmp");
        tempOut = new FileOutputStream(temp2);
        copyStream(tempIn, tempOut);
        tempIn.close();
        tempIn = new FileInputStream(temp2);

        scratchFile = File.createTempFile("signed3", ".bin");
        randomAccessFile = new RandomAccessFile(scratchFile, "rw");

        /* Read temporary file */
        PDDocument document = PDDocument.load(temp, randomAccessFile);
        document.getCurrentAccessPermission().setCanModify(false);

        PDSignature signature = new PDSignature();
        signature.setFilter(PDSignature.FILTER_ADOBE_PPKLITE);
        signature.setSubFilter(PDSignature.SUBFILTER_ADBE_PKCS7_DETACHED);
        signature.setName(name);
        signature.setLocation(location);
        signature.setReason(reason);
        signature.setSignDate(Calendar.getInstance());

        PDVisibleSignDesigner signatureDesigner = new PDVisibleSignDesigner(
                document, image, document.getNumberOfPages());
        signatureDesigner.xAxis(250).yAxis(60).zoom(-90).signatureFieldName("signature");

        PDVisibleSigProperties signatureProperties = new PDVisibleSigProperties();
        signatureProperties.signerName(name).signerLocation(location)
                .signatureReason(reason).preferredSize(0).page(1)
                .visualSignEnabled(true).setPdVisibleSignature(signatureDesigner)
                .buildSignature();

        SignatureOptions options = new SignatureOptions();
        options.setVisualSignature(signatureProperties);

        document.addSignature(signature, dataSigner, options);

        /* Sign */
        document.saveIncremental(tempIn, tempOut);
        document.close();
        tempIn.close();

        /* Copy temporary file to an output stream */
        tempIn = new FileInputStream(temp2);
        copyStream(tempIn, signedPdf);
    } catch (IOException e) {
        logger.error("PDF signing failure", e);
    } catch (COSVisitorException e) {
        logger.error("PDF creation failure", e);
    } catch (SignatureException e) {
        logger.error("PDF signing failure", e);
    } finally {
        closeStream(originalPdf);
        closeStream(signedPdf);
        closeStream(randomAccessFile);
        closeStream(tempOut);
        deleteTempFile(temp);
        deleteTempFile(temp2);
        deleteTempFile(scratchFile);
    }
}

private void deleteTempFile(File tempFile) {
    if (tempFile != null && tempFile.exists() && !tempFile.delete()) {
        tempFile.deleteOnExit();
    }
}

private void closeStream(Closeable is) {
    if (is!= null) {
        try {
            is.close();
        } catch (IOException e) {
            logger.error("failure", e);
        }
    }
}

private void copyStream(InputStream is, OutputStream os) throws IOException {
    byte[] buffer = new byte[1024];
    int c;
    while ((c = is.read(buffer)) != -1) {
        os.write(buffer, 0, c);
    }
    is.close();
}

Apart from file madness I don't see any text on the signature. This is how result looks like:

and this is how it looks, when I do similar thing with itext library

Why name, location and reason missing from the visual signature representation? How can I fix that?
Comment: I can see there is difference in produced PDF commands produced by itext and pdfbox, but I'm not PDF format expert. Not yet. So I will appreciate any help.

You should say in `PDVisibleSignDesigner.zoom()` javadoc that image is scaled to `(100 - N)%` of original image, where `N` is a parameter of the method.
http://pdfbox.apache.org/docs/1.8.8/javadocs/org/apache/pdfbox/pdmodel/interactive/digitalsignature/visible/PDVisibleSignDesigner.html#zoom%28float%29
Comment: It actually should be `(100 + N)%`.
Answer: Why name, location and reason missing from the visual signature representation?
They are not there because they are not drawn.
The default way of iText to represent a visualized signature is by adding those information to the visualization.
The default way of PDFBox' PDVisibleSigBuilder to represent a visualized signature is without such information.
Neither is wrong or right, both merely are defaults.
The canonical place where people shall look for such information is the signature panel after all.
How can I fix that?
The actual contents of the signature visualization are created by a PDVisibleSigBuilder instance during signatureProperties.buildSignature():
public void buildSignature() throws IOException
{
    PDFTemplateBuilder builder = new PDVisibleSigBuilder();
    PDFTemplateCreator creator = new PDFTemplateCreator(builder);
    setVisibleSignature(creator.buildPDF(getPdVisibleSignature()));
}

Thus, by replacing
    signatureProperties.signerName(name).signerLocation(location)
            .signatureReason(reason).preferredSize(0).page(1)
            .visualSignEnabled(true).setPdVisibleSignature(signatureDesigner)
            .buildSignature();

in your code by
    signatureProperties.signerName(name).signerLocation(location)
            .signatureReason(reason).preferredSize(0).page(1)
            .visualSignEnabled(true).setPdVisibleSignature(signatureDesigner);

    PDFTemplateBuilder builder = new ExtSigBuilder();
    PDFTemplateCreator creator = new PDFTemplateCreator(builder);
    signatureProperties.setVisibleSignature(creator.buildPDF(signatureProperties.getPdVisibleSignature()));

for a customized version ExtSigBuilder of this PDVisibleSigBuilder class, you can draw anything you want there, e.g.:
class ExtSigBuilder extends PDVisibleSigBuilder
{
    String fontName;

    public void createImageForm(PDResources imageFormResources, PDResources innerFormResource,
            PDStream imageFormStream, PDRectangle formrect, AffineTransform affineTransform, PDJpeg img)
            throws IOException
    {
        super.createImageForm(imageFormResources, innerFormResource, imageFormStream, formrect, affineTransform, img);

        PDFont font = PDType1Font.HELVETICA;
        fontName = getStructure().getImageForm().getResources().addFont(font);

        logger.info("Added font to image form: " + fontName);
    }

    public void injectAppearanceStreams(PDStream holderFormStream, PDStream innterFormStream, PDStream imageFormStream,
            String imageObjectName, String imageName, String innerFormName, PDVisibleSignDesigner properties)
            throws IOException
    {
        super.injectAppearanceStreams(holderFormStream, innterFormStream, imageFormStream, imageObjectName, imageName, innerFormName, properties);

        String imgFormComment = "q " + 100 + " 0 0 50 0 0 cm /" + imageName + " Do Q\n";
        String text = "BT /" + fontName + " 10 Tf (Hello) Tj ET\n";
        appendRawCommands(getStructure().getImageFormStream().createOutputStream(), imgFormComment + text);

        logger.info("Added text commands to image form: " + text);
    }
}

writes "Hello" in Helvetica at size 10 atop the lower left of the image form (the form actually displaying something).
PS: In my opinion the object oriented structure behind this should be completely overhauled.
Comment: Hard to say, but from the source it looks like idea was to override `PDVisibleSigProperties.buildSignature()`. Otherwise `PDVisibleSigProperties.signerName()`, `PDVisibleSigProperties.signerLocation()`, `PDVisibleSigProperties.signatureReason()` make no sense and not used anywhere.
Comment: `PDVisibleSigProperties#signerName` and the other mentioned properties are not even used at all in PDFBox (as of version 1.8.10).
Comment: Those properties have corresponding entries in the PDF signature field value; if implemented properly, they can be seen e.g. in Adobe's signature panel.
Answer: Display the text over the signatory some time it doesn't look nice. For me, I create new image base on the text that I want to display. And merge it with the signatory image. I can add background for signatory image (company name  watermark)
Here is the code create new signatory image with text and  background:
public class ImageSignatory {

public static void main(String[] args) {
    DateFormat df = new SimpleDateFormat("MM.dd.yyyy");
    Date today = Calendar.getInstance().getTime();
    String reportDate = df.format(today);
    String text = "Signature eletronic Company AA DUC NGUYEN  - Date " + reportDate;
    String background = "background.png";
    String signImage = "sign.jpg";
    String textImage = createImageFromText(text);
    String imageResultURL = null ;
    try {

        String mergedImage = mergeTwoImage(signImage, textImage);
        imageResultURL = addBackgroundToImage(background, mergedImage);
    } catch (Exception ex) {

    }

}

public static String StringDivider(String s) {

    StringBuilder sb = new StringBuilder(s);
    int i = 0;
    while ((i = sb.indexOf(" ", i + 30)) != -1) {
        sb.replace(i, i + 1, "\n");
    }
    return sb.toString();

}

public static BufferedImage toBufferedImage(Image img) {
    if (img instanceof BufferedImage) {
        return (BufferedImage) img;
    }
    BufferedImage bimage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
    Graphics2D bGr = bimage.createGraphics();
    bGr.drawImage(img, 0, 0, null);
    bGr.dispose();
    return bimage;
}

public static String addBackgroundToImage(String backgroundPATH, String imagePath) {
    try {
        String imageResult = "result.jpg";
        Image backgroundImage = ImageIO.read(new File(backgroundPATH));
        int width = backgroundImage.getWidth(null);
        int height = backgroundImage.getHeight(null);

        Image signAndText = ImageIO.read(new File(imagePath));
        signAndText = signAndText.getScaledInstance(width, height, Image.SCALE_SMOOTH);
        signAndText = toBufferedImage(signAndText);

        BufferedImage combined = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g2 = combined.getGraphics();
        g2.drawImage(backgroundImage, 0, 0, null);
        g2.drawImage(signAndText, 0, 0, null);
        g2.dispose();
        ImageIO.write(combined, "JPG", new File(imageResult));
        return imageResult;
    } catch (IOException ex) {
        return null;
    }
}

public static String mergeTwoImage(String first, String second) {
    try {
        String tempFileName = "merged_image.png";
        Image signatoryImage = ImageIO.read(new File(first));
        Image addtionalTextImage = ImageIO.read(new File(second));
        float ratio = (float) signatoryImage.getWidth(null) / (float) addtionalTextImage.getWidth(null);
        addtionalTextImage = addtionalTextImage.getScaledInstance((int) (ratio * (float) addtionalTextImage.getWidth(null)), (int) (ratio * (float) addtionalTextImage.getHeight(null)), Image.SCALE_SMOOTH);
        addtionalTextImage = toBufferedImage(addtionalTextImage);
        BufferedImage combinedTemp = new BufferedImage(signatoryImage.getWidth(null), signatoryImage.getHeight(null) + (int) (ratio * (float) addtionalTextImage.getHeight(null)), BufferedImage.TYPE_INT_ARGB);

        Graphics g = combinedTemp.getGraphics();
        g.drawImage(signatoryImage, 0, 0, null);
        g.drawImage(addtionalTextImage, 0, signatoryImage.getHeight(null), null);
        g.dispose();
        ImageIO.write(combinedTemp, "PNG", new File(tempFileName));
        return tempFileName;
    } catch (IOException ex) {
        return null;
    }
}

public static String createImageFromText(String text) {
    String tempFileName = "text.png";
    text = StringDivider(text);
    String[] textParts = text.split("\n");

    BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = img.createGraphics();
    Font font = new Font("Arial", Font.PLAIN, 48);
    g2d.setFont(font);
    FontMetrics fm = g2d.getFontMetrics();
    int width = 0;
    for (String textPart : textParts) {
        int tempWidth = fm.stringWidth(textPart);
        if (tempWidth > width) {
            width = tempWidth;
        }
    }
    width += 10;
    int oneLineHeight = fm.getHeight();
    int height = (oneLineHeight) * textParts.length;
    g2d.dispose();

    img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    g2d = img.createGraphics();
    g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
    g2d.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
    g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
    g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
    g2d.setFont(font);
    fm = g2d.getFontMetrics();
    g2d.setColor(Color.BLACK);
    int index = 0;
    for (String textPart : textParts) {
        g2d.drawString(textPart, 5, (oneLineHeight) * index + fm.getAscent());
        index++;
    }

    g2d.dispose();
    try {
        ImageIO.write(img, "PNG", new File(tempFileName));
    } catch (IOException ex) {
        return null;
    }
    return tempFileName;
}

 public static void removeFile(String fileName) {
    try {
        File file = new File(fileName);
        file.delete();
    } catch (Exception ex) {

    }
}

}

Visual signature with pdfbox 1.8.8