Setting up routing in CentOS 6.4 as a router/DHCP server with two nics

Question: I am stumped about how to setup centOS 6.4 to route packets.
|Local Network| -eth0- |CentOS 6.4 box|  -eth1- |Internet|
The centOS box has a dhcp server running. Currently it is handing out IP address on 192.168.3.0/24 but I don't think DNS is working correctly either.  I have two boxes 192.168.3.5 and 192.168.3.6 that can ping each other all day but nslookup raid_array will not work.  Here is my setup right now.
I want all 192.168.3.0/24 traffic to forward over eth0.  Any traffic headed for the internet should be masqueraded as the 172.16.0.72 over eth1. Where does DNS fit into this?
/etc/sysconfig/network-scripts/ifcfg-eth0
DEVICE=eth0
TYPE=ETHERNET
ONBOOT=yes
NM_CONTROLLED=no
BOOTPROTO=none
IPADDR=192.168.3.1
NETMASK=255.255.255.0

/etc/sysconfig/network-scripts/ifcfg-eth1
DEVICE=eth0
TYPE=ETHERNET
ONBOOT=yes
NM_CONTROLLED=no
BOOTPROTO=static
NETMASK=255.255.255.0
IPADDR=126.96.36.199
GATEWAY=172.16.0.1

/etc/sysconfig/network
NETWORKING=yes
GATEWAY=192.168.3.1
NOZEROCONF=true

route -n
Destination     Gateway    Genmask       Flags    Metric  Ref   Use   Iface
192.168.3.0     0.0.0.0   255.255.255.0   U           0    0     0     eth0
0.0.0.0       172.16.0.1  0.0.0.0         UG          0    0     0     eth1

iptables
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT
-A INPUT -m state --state NEW -m tcp -p tcp --dport 443 -j ACCEPT
-A INPUT -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -j REJECT --reject-with icmp-host-prohibited

Comment: your eth1 configuration is not correct, DEVICE=eth1 not eth0
Answer: You will also need to add this to your /etc/sysctl.conf:
net.ipv4.ip_forward = 1

and then run:
sysctl -p /etc/sysctl.conf

The default behavior for Red Hat is not to forward packets, but just to be an end point.
You are also going to want to accept traffic going through the box (or it won't work very well as a router)
iptables -A FORWARD -i eth1 -j ACCEPT

You'll also want to add postrouting masquerade rules for the traffic.
BTW, in your ifcfg-eth1 file, change the device name to eth1, otherwise you may have problems.
DNS is there to provide domain name <=> ip addressing, you might need to have your own DNS server if you have servers inside the 192.168.3.X network, so you do not have to remember IP addresses, though you will want to configure those machines with static IPs or set up DHCP to always assign them the same IP. If however you do not have a need for internal DNS, use the ones your ISP provides, or Google's (220.127.116.11).


Showing that $|g(x)| \leq M$

Question: I was working on the following problem

Let $\{g_{k}\}_{k=1}^{\infty}$ be a sequence of continuous real-valued functions on $[0,1]$. Assume that there is a number $M$ such that $|g_{k}(x)| \leq M$ for every $k$ and every $x \in [0,1]$ and also there is a continuous real-valued function $g$ on $[0,1]$ such that
  $$ \int^{1}_{0} g_{k}(x)p(x)dx \to \int^{1}_{0} g(x)p(x)dx$$
  as $k \to \infty$ for every polynomial $p$. Prove that $|g(x)| \leq M$ for every $x \in [0,1]$ and that
  $$ \int^{1}_{0} g_{k}(x)f(x)dx \to \int^{1}_{0} g(x)f(x)dx$$ for every continuous $f$.

I am having trouble showing $|g(x)| \leq M$
I was able to show that $ \int^{1}_{0} g_{k}(x)f(x)dx \to \int^{1}_{0} g(x)f(x)dx$ assuming that $|g(x)| \leq M$. I did this by estimating
$$E= \vert \int^{1}_{0} g_{n}(x)f(x)dx- \int^{1}_{0} g(x)f(x)dx \vert$$. We then have by the triangle inequality that
$$
E \leq E_{1}+ E_{2}
$$
where
\begin{align*}
E_{1} &=  \vert \int^{1}_{0} g_{n}(x)p_{k}(x)dx - \int^{1}_{0} g_{n}(x)f(x)dx \vert \\
E_{2} &= \vert  \int^{1}_{0} g_{n}(x)f(x)dx-\int^{1}_{0} g(x)f(x)dx \vert \\
\end{align*}
I can make $E_{1}$ "small" using the Stone-Weierstrass Theorem, but to make $E_{2}$ "small", I needed to assume that $|g(x)| \leq M$.
Answer: I don't quite follow how you split things into two terms. Seems to me the natural thing is
$$|\int g_nf-\int gf|\le|\int g_nf-\int g_np_k|+|\int g_np_k-\int gp_k|+|\int gp_k-\int gf|=E_1+E_2+E_3.$$
Now. You're given that $g$ is continuous. So there exists $N$ such that $|g|\le N$. This works just as well as if you already knew $|g|\le M$. Suppose $p_k\to f$ uniformly. If $k$ is large enough then $E_1<\epsilon$ for all $n$ and if $k$ is large enough then $E_3<\epsilon$ for all $n$. Now fix $k$ "large enough" that both those conditions are satisfied; if $n$ is large enough then $E_2<\epsilon$.
So that gives a proof that $\int g_nf\to\int gf$ for every continuous $f$.
This implies that $|\int gf|\le M \int|f|$ for  every continuous $f$. And it follows from that (leaving something for you) that $|g|\le M$.
Comment: (1) If you say so - I cannot see how your error is smaller than your $E_1+E_2$, simply doesn't add up as far as I can see. (2) If $|a_n|\le 1$ and $a_n\to a$ then $|a|\le 1$.
Comment: Thanks, the $E_{2}$ that I wrote above  I think actually splits into the $E_{2}$ and $E_{3}$ that you wrote, I was too lazy to write it there. I forgot to notice that $g$ was continuous on a compact set. I can complete the estimate I had. I can see why $|\int gf | \leq M \int |f|$ by taking $f=1$. But is there a way to see rigorously,  how $\int g_{n} f \to \int gf$ implies that $| \int gf | \leq M \int |f|$?

Showing that $|g(x)| \leq M$


robotframework installed from exe:

Question: I've install robotframework from exe on Windows 7 and now getting error running pybot --version
"C:\Python27\python.exe: No module named robot"
My PYTHONHOME is set to C:\Python27\Scripts
My PYTHONPATH is set to C:\Python27\Lib
Path contains C:\Python27\Scripts
There are following files in C:\Python27\Scripts:
<code>ipybot.bat
jybot.bat
pybot.bat
rebot.bat
robot_postinstall.py
robot_postinstall.pyc
robot_postinstall.pyo
</code>
Answer: What exe did you install?  My advice would be to forget what you've done and follow the official installation instructions here:
https://code.google.com/archive/p/robotframework/wikis/Installation.wiki
Answer: On Windows it's best to append the path of your folder to the PATH variable.
You can see this more clearly here https://www.java.com/en/download/help/path.xml
Add the folder path to the PATH variable as said in the instructions above and reset the cmd.

robotframework installed from exe:


Rate at which flu spreads

Question: Here's the question:
Say the rate at which the flu spreads is proportional to the number of people currently have the flu.
    Assuming an unlimited population, if one person is sick at 9:00 AM, and two people are sick at 3:00 PM, how many people will be sick at 9:00 AM the next morning (rounding to the nearest whole number)?
Here's my answer:
9 am - 1
3 pm - 2
9 pm - 4
3 am - 16
9 am - 256
My understanding is that proportional means exponentially.
Please let me know if my logic is correct and if my answer is right.
Answer: "Proportionally" does mean "exponentially" - but you have misunderstood what "exponentially" means.
"Proportional to the number of people currently sick" means that each sick person has the same chance to infect someone else. The data given tell you that it takes six hours for the number of infected people to double. That means your list should proceed
$$
1, 2, 4, 8, 16, \ldots .
$$
You have squared the infecteds. That can't make any sense if you think about the numbers as counting people, since you can't have a square person.
(PS I find reading and responding to such a ridiculous "word problem"  very painful. That's your teacher's fault, not yours.)
Comment: "That can't make any sense.." - good point
Answer: You have a solid intuition about this problem: let's make it rigorous.
If we define $F(t)$ to be the number of people infected at time $t$, then we know that $$\frac{dF}{dt} = kF$$ where $k$ is a constant.
Hence, $$\frac{dF}F=k\cdot dt$$$$\int \frac{dF}F = \int k\cdot dt$$$$\ln |F| = kt + C$$ $$F(t) = e^{kt+C} = Ae^{kt}$$.
This demonstrates that $F(t)$ should be an exponential function.
However, your data is wrong, since the relationship between your numbers seems to be proportional to $F(t)=t^2$, not an exponential function.
So since you know $F(1)=1$ and $F(2)=2$, we can plug those into our function.
$$Ae^{k\cdot1}=1$$$$Ae^{k\cdot2}=2$$
Substituting the first equation in the second gives
$$\frac{e^{k\cdot2}}{e^{k\cdot1}}=2$$
$$e^k = 2$$
$$k = \ln 2$$
Now, going back to the first equation
$$Ae^{\ln 2} = 1$$
$$2A = 1$$
$$A = \frac 1 2$$
Hence, your final function is $$F(t) = \frac {e^{t\cdot\ln 2}}2$$
Comment: Correct, of course, but I very much doubt that a calculus explanation is what the OP is looking for.
Comment: I wasn't sure what level of explanation he wanted, but this is okay to keep as a reference.

Rate at which flu spreads


Surface area of $\frac{x^2}{a^2}+\frac{y^2}{b^2}=1$ about $x,y$ axis.

Question: So I need to find the Surface area of $\frac{x^2}{a^2}+\frac{y^2}{b^2}=1$ about $x,y$ axis.
For $x-$axis, I found that
$$y=\frac{b}{a}\sqrt{a^2-x^2}$$
Then
$$y'=-\frac{bx}{a\sqrt{a^2-x^2}}.$$
Then
$$(y')^2=\frac{b^2x^2}{a^2(a^2-x^2)}.$$
Then
$$1+(y')^2=\frac{x^2b^2+a^2(a^2-x^2)}{a^2(a^2-x^2)}$$
Then according to $S= 2\pi \int_a^b f(x)\sqrt{1+(f'(x))^2}dx$ we have
$$S = 2 \pi \int_{-a}^a \frac{b}{a^2}\sqrt{x^2b^2+a^2(a^2-x^2)} dx.$$
where am I going wrong? And for the $y-$axis do we just solve for $x$ and integrate $-b$ to $b$?
Comment: Hint: $\int \sqrt{c^2 \pm x^2}dx$ is a standard intergral.
Comment: @BotnakovN. so was I off to the right start then? I didnt make any mistakes?
Comment: Yes, you didn't make a mistake. But the integral was not taken.
Comment: @BotnakovN. in order to apple your rule do I rewrite what's inside the radical as $a^4+x^2(b^2-a^2)$?
Comment: Yes. I wrote it below.
Comment: To find the surface area of $\frac{x^2}{a^2}+\frac{y^2}{b^2}=1$ when rotated about $x,y$ axes.
Answer: If $b \ge a$ we have
$$S = 2 \pi \int_{-a}^a \frac{b}{a^2}\sqrt{x^2b^2+a^2(a^2-x^2)} dx =  2 \pi \frac{b}{a^2} \sqrt{ a^4+(b^2-a^2)x^2}dx =\\$$
$$ = 2 \pi \frac{b}{a^2\sqrt{b^2-a^2}}\int \sqrt{c^2+x^2}dx  $$
where $c^2 = \frac{a^4}{b^2-a^2}$. If $b \le a$ we use $\int \sqrt{c^2-x^2}dx$ instead of $\int \sqrt{c^2+x^2}dx$.
If we swap $a$ and $b$ and swap  $x$ and $y$ we will get an answer for the second question.
Comment: Please check. Surface area does not tally to degree 2.
Answer: $\frac{x^2}{a^2}+\frac{y^2}{b^2}=1$ is the equation of an ellipse
Not required but the area of ellipse is:
$$\begin{align} x&=a\cos t, y=b\sin t\\ A&=4\int_0^{\frac{\pi}{2}}{ydx}\\&=-ab\int_0^{\frac{\pi}{2}}{\sin^2t dt}\end{align}$$
About x-axis the area of ellipsoid is
$$2\int_0^{\frac{\pi}{2}}{2\pi y dx}= \pi A$$
About y-axis the area of ellipsoid is
$$2\int_0^{\frac{\pi}{2}}{2\pi x dy}= 4\pi \cdot (-ab)\int_0^{\frac{\pi}{2}}{\cos^2 t dt} $$


Test set error estimation under a small sample size

Question: What are some of the plausible approaches to estimate the test set error when you have a very small sample set available (specifically, when the small sample size does not justify using a hold-out set)?
When using a linear regression model or a model that adopts a Maximum-Likelihood-based approach to estimate the parameters, I can think of using Adjusted R^2, AIC, or BIC as estimators of the test set error.
Are there any other sound approaches to adopt?
Comment: The methods you mentioned are model selection criteria. They can be used to select a model out of multiple alternatives, or to tune hyperparameters, but they don't directly estimate generalization performance. Is model selection actually what you're asking about?
Comment: I'm asking about the generalization error. The reason we can use the above-mentioned methods to select between models is that they provide an estimate of the generalization error.
Answer: I would not call any of those metrics (adjusted $R^2$, AIC, BIC) estimations of the testing error, but they are intended to perform a similar function, and all of them can be informative. Nothing will be as unbiased as using an actual testing set, of course.
To get something that takes a form that is more similar to testing error, I would suggest using cross validation and looking at the average of the cross validation error across each folds. One option in R is the caret package, which lets you do cross validation multiple times and average across of them (e.g. 5-fold CV 3 times, so it's training/testing 15 regressions).
Comment: Thanks. The problem is that, I think, with a small sample size the estimation obtained from cross validation would be highly variable.
Comment: It likely will be, but doing repeated CV instead of a single pass of CV should help you arrive at a mean error that is more reliable. Also, your full training set is only 10-25% larger than each CV fold, assuming you do 5-10 fold CV. So if you look at your CV models and notice their coefficients (assuming you're doing linear regression) vary wildly, that's a good sign that you simply don't have enough data to be confident about the generalizability of your model.


What is the optimal strategy when playing `head or tail` per team

Question: Introduction
Once a week, we are playing head or tail in my favorite bar.
There are $N$ people in the room and each person is guessing whether head or tail will come up to the next toss. If you lose you sit down. If you win you remain standing. The last person to be standing brings the victory to its team.
The are $n$ different teams and the number of members in each team is $[x_1, x_2, ...,x_{n-1}, x_n]$ such that $\sum_i^n x_i = N$. Let's call my team "team 1". There are therefore $x_1$ members in my team.
Strategy
A friend of mine came with the strategy that at each toss, half of the team is playing head, while the other half is playing tail.
Question
If everybody is playing randomly, our probability of winning is $\frac{x}{N}$.

Does my friend's strategy affect this probability?
What would be the optimal strategy?
Is the best strategy different depending on what strategy the other teams are playing (and depending the number of individuals in each team)?
Comment: Your friend's strategy is optimal and dominates random play. Random play yields $\frac x N$ only if other groups play randomly. If they don't, you'll get less.
Comment: The intuition is that you want your "worse" case to be as good as possible which yields even (or almost) split. Expected number of survivors after $n$ plays is $x/2^n$, so the more concentrated you are around the mean, the higher $P(X>0)$ (what you care about) is. Random choice leads to higher variance.
Comment: You need to specify what happens if *everyone* guesses wrong on the final round -- i.e., does everyone lose, or is it a "partial" win for each team (and if so, how is it apportioned)?
Answer: If you split your team of $x$ into $t$ tails and $h$ heads, you'll get the average of the game values with $t$ and $h$ people left. If the game value is concave with respect to the number of people on your team, this average is optimal for an even split $t=\lfloor\frac x2\rfloor$, $h=\lceil\frac x2\rceil$. My guess would be that this will always be the case, independent of the other teams' strategies, but the details of proving that seem messy.
Let's look at the game with two teams to get a feel for things. We can derive the game values $v(x_1,x_2)$ starting from the initial values $v(x_1,0)=1$ for $x_1\gt0$ and $v(0,x_2)=0$ for $x_2\gt0$. You didn't specify $v(0,0)$; I'll take it to be $\frac12$ (a split prize).
Here's a table of game values if both teams always split, for $x_1,x_2\le4$ (with $x_1$ downward and $x_2$ to the right):
\begin{array}{c|cc}
&0&1&2&3&4\\\hline
0&\frac12&0&0&0&0\\
1&1&\frac12&\frac14&\frac3{16}&\frac18\\
2&1&\frac34&\frac12&\frac38&\frac14\\
3&1&\frac{13}{16}&\frac58&\frac12&\frac38\\
4&1&\frac78&\frac34&\frac58&\frac12\\
\end{array}
The value is concave in $x_1$ (and accordingly convex in $x_2$), so splitting is indeed optimal. We can also derive the game values if your team splits while the other plays randomly:
\begin{array}{c|cc}
&0&1&2&3&4\\\hline
0&\frac12&0&0&0&0\\
1&1&\frac12&\frac5{14}&\frac{19}{70}&\frac{471}{2170}\\
2&1&\frac34&\frac{33}{56}&\frac{269}{560}&\frac{13987}{34720}\\
3&1&\frac{13}{16}&\frac{305}{448}&\frac{5231}{8960}&\frac{566131}{1111040}\\
4&1&\frac78&\frac{173}{224}&\frac{3079}{4480}&\frac{342339}{555520}\\
\end{array}
Here, too the value is concave in your team count, so your split play is optimal also against random play. Here's a direct comparison with approximate decimal values (split play first):
\begin{array}{c|cc}
&0&1&2&3&4\\\hline
0&0.500&0&0&0&0\\
1&1&0.500&0.250/0.357&0.188/0.271&0.125/0.217\\
2&1&0.750&0.500/0.589&0.375/0.480&0.250/0.403\\
3&1&0.813&0.625/0.681&0.500/0.584&0.375/0.510\\
4&1&0.875&0.750/0.772&0.625/0.687&0.500/0.616\\
\end{array}
For completeness, here are the game values for random play by both teams:
\begin{array}{c|cc}
&0&1&2&3&4\\\hline
0&0.500&0&0&0&0\\
1&1&0.500&0.357&0.271&0.217\\
2&1&0.643&0.500&0.407&0.343\\
3&1&0.729&0.593&0.500&0.433\\
4&1&0.783&0.657&0.567&0.500\\
\end{array}
The values are much closer to $\frac12$ than for optimal play by both teams, since random play is worse at taking advantage of superior numbers.
Here's the code I used to compute the game values.
Comment: I appreciate the work +1 :) I understand you simulated the values rather than calculating them.
Comment: To help me build my intuition could you please tell more about 1) what is meant by this statement `The value is concave in x1`,  2) how you came about this statement (if not just by looking at the results of your simulation) and 3) how does it result into `so splitting is indeed optimal`.
Comment: @Remi.b: What made you think I simulated the values rather than calculating them? Would be rather crazy of me to write fractions with $6$-digit denominators if these were just approximate simulations :-) No, I linked to the code that does the computations; these are the exact numbers. (For random play I didn't put the exact fractions in a table, but the code produces them.)
Comment: @Remi.b: About your questions: 1) see [Concave function at Wikipedia](https://en.wikipedia.org/wiki/Concave_function)  2) because we're dealing with averages of function values further apart or closer together, and that's sort of what convexity and concavity is about; 3) "so splitting is indeed optimal" because if the function is concave, the average of two function values at arguments with a given sum is maximal in the symmetric case where both arguments are half the sum.


how to assign a value from scanner to a object?

Question: I am trying to assign a value to class object from a Scanner. I don't want to use Teacher a = new Teacher("Ali","SCF333",'M'); because its already setted, I want the user to input the data
This is my driver class:
public class TeacherDriver {
    public static void main(String[]args){

        String data;
        Teacher a = new Teacher();

        Scanner input = new Scanner(System.in);

        System.out.println("Please enter Employee Name: ");
        data=input.nextLine();
        a.setEmpName();
        System.out.println("Please enter Employee ID: ");
        data2=input.nextLine();
        a.setEmpID();
        System.out.println("Please enter Employee Gender: ");
        data3=input.nextLine();
        a.setGender();

        System.out.println(a.toString());

    }
}

and this is the class:
public class Teacher {
    private String empID;
    private String empName;
    private Address address;
    private char gender;
    private String [] Subject;

    Teacher(){

    }

    Teacher(String empName){
        this.empName=empName;
    }

    Teacher(String empName,String empID){
        this.empName=empName;
        this.empID=empID;
    }

    Teacher(String empName,String empID,char gender){
        this.empName=empName;
        this.empID=empID;
        this.gender=gender;
    }

    Teacher(String empName,String empID,char gender,Address address){

        this.empName=empName;
        this.empID=empID;
        this.gender=gender;
        this.address=address;
    }

    Teacher(String empName,String empID,char gender,Address address,String[]Subject){

        this.empName=empName;
        this.empID=empID;
        this.gender=gender;
        this.address=address;
        this.Subject=Subject;
    }

    public void setEmpID(){
        this.empID=empID;
    }

    public void setEmpName(){
        this.empName=empName;
    }

    public void setGender(){
        this.gender=gender;
    }

    public String getEmpID(){
        return empID;
    }

    public String getEmpName(){
        return empName;
    }

    public char getGender(){
        return gender;
    }

    public Address getAddress(){
        return address;
    }

    public String[] getSubject(){
        return Subject;
    }

     public String toString()
     {
         String viewteacher = new String("Name: " + empName + "\nID: "+ empID +"\nGender: "+ gender + "\nSubjects: "+ Subject);
          return viewteacher;
     }
}

Comment: `Teacher t = new Teacher(data,data2,data3.charAt(0));`
Answer: I am not quite sure what you exactly want but here you go,
System.out.println("Please enter Employee Name: ");
data=input.nextLine();
a.setEmpName(data);
System.out.println("Please enter Employee ID: ");
data2=input.nextLine();
a.setEmpID(data2);
System.out.println("Please enter Employee Gender: ");
// Assuming that the user is entering correct data
data3=input.nextLine();
a.setGender(data3.charAt(0));

Answer: It is wrong way of creating setter methods, Here you are just setting your instance variable empName to same instance variable empName.
public void setEmpName(){
    this.empName=empName;
}

You have to pass argument to set method, and then that argument will set.
public void setEmpName(String empName){
    this.empName=empName;
}

TeacherDriver class will need to be modified as follows,
  System.out.println("Please enter Employee Name: ");
  data=input.nextLine();
  a.setEmpName(data);

Answer: Create object after getting input.
      a.setEmpName();
      a.setEmpID();

Above calls will not set the value as it dont have any parameter been passed to set. Modify the Teacher object creation  as below
    Teacher a = new Teacher(data1,data2,data3);

Include the  above call after  storing input  in the data1,data2 and data3 variables.
Answer: Your setters do not have any parameters passed to set the values. Below's how they should typically look
public void setSomething(String something) {
    this.something=something;
}

and then you invoke them thus:
MyClass myObject = new MyClass();
myObject.setSomething(scanner.nextLine());

You can check javadocs for how Scanner works


How to add a confirm dialog to node add and edit forms?

Question: Note: This has an accepted bounty, but no accepted answer because I still want to know how to add a node save confirm dialog using drupal code, not javascript.  If you can write up a good answer on that I'll definitely accept it, and probably open and award you another bounty for your trouble.
Trying to implement part of the functionality mentioned in How can I add or remove links to nodes in a list depending on the values of some of the fields I would like to give users a warning, if the node they are submitting would end up being a stub.
I've been trying to implement this by following lots of examples related to confirm_form, especially this one.
I'm think my issue must be that I'm starting from hook_form_alter, so in hook_form_alter it doesn't work very well to return an entirely different form (the confirm_form).  Realizing that hook_form_alter must be the wrong starting place though, doesn't help me know where I should start.
So here's what I need to be able to do:
When the user clicks 'Save' on a node edit form, I need to then evaluate whether the field values meet some criteria, and then provide the user a warning, that saving in the current state will have some effect on the way the node is displayed and give them an option to confirm or cancel.
Here is one of the many iterations of what I've tried:
function MYMODULE_form_node_form_alter(&$form, &$form_state, $form_id) {

    if (in_array(strstr($form_id, '_', TRUE), $GLOBALS['conf']['publication_types'])) { // only work on the publication forms
        if( !isset($form_state['storage']['submitted'] )) { // if the form hasn't previously been submitted
            $form['actions']['submit']['#submit'] = array('MYMODULE_node_form_submit');

            return $form;
        } else { // this is the confirmation step
            $form = _MYMODULE_build_confirm_form($form_state);
            return $form;
        }

    }
}

/**
 * invoke hook_node_validate
 */
function MYMODULE_node_validate($node, $form, &$form_state) {
    if (MYMODULE_is_stub($node)) {
        $form_state['storage']['stub'] = True;
        if ($form_state['triggering_element']['#value'] === 'Preview') {
//            dpm($form_state);
            drupal_set_message($message = 'If saved in this form, your publication will not have enough information to merit its own publication page.', $type = 'warning', $repeat = TRUE);
        }

    } else {
        $form_state['storage']['stub'] = False;
    }
}

function MYMODULE_node_form_submit($form, &$form_state) {

    if( !isset($form_state['storage']['submitted'] )) // this is the first time this has been submitted
    {
        // not confirmed yet.
//        $form_state['storage']['confirm'] = TRUE; // this will cause the form to be rebuilt, entering the confirm part of the form

        $form_state['storage']['submitted'] = TRUE;
        $form_state['rebuild'] = TRUE;
    }

    else // if we get here, confirm should have been clicked on the confirm form
    {
        node_form_submit($form, $form_state);

    }
}

function _MYMODULE_build_confirm_form(&$form_state) {
    $path = current_path();

    $form['processed'] = array(
        '#type' => 'hidden',
        '#value' => 'true'
    );
    return confirm_form($form, t('Do you really want to save a publication stub?'), $path, 'Confirm', 'Cancel');
}

This code doesn't work.  When you click save gets through returning the form created by _MYMODULE_build_confirm_form, but in the processing afterwards, it seems clear that the system is expecting a node edit form and doesn't like what it is getting instead.  The confirmation form is never displayed.  I've tried using the node edit form as an input into confirm_form and the actions of the node edit form show up instead of the confirm_form buttons.
I'm at the end of my rope, how do I do this?  I guess I need to override the menus so that I can run a callback function to determine which form should be displayed at node/%id%/edit before it gets to the stage of altering the form that has been specified?  If so, how can I do that?  I just need a solution that will use my existing MYMODULE_is_stub() feature to determine whether there needs to be a confirmation form, and then display the warning to the use and ask them to confirm or cancel.  Please help!
Comment: Are you familiar with jQuery? You could do it with jQuery and make it that when the user hovers over the save button or clicks the save button for the first time, or when the save button is in view, if field X and/or field Y is empty, show popup message. You would have to add the jQuery to your Drupal admin theme. The default **admin theme** is **Seven**.
Comment: The validation would be a little bit complicated with jQuery (abstract field has at least 300 characters or the related website field has at least one url added or the public files field has at least one file in it.).  I'm already going to need to use my is_stub function to strip out the links from node teasers when they should be stubs, so it would be nice to just maintain that code in one place, and it would be nice to make sure the users at least have to stop and think briefly until they've memorized the form.  A modal popup would work, but a hover would be less useful.
Comment: Please remove _better_ or _good way_ from the question. Those are subjective terms.
Comment: I've removed them everywhere where it isn't me expressing opinion.
Comment: Have you seen [Is there a way to alter a node save confirmation form?](http://drupal.stackexchange.com/questions/85272/is-there-a-way-to-alter-a-node-save-confirmation-form)?
Comment: Yes, I've seen it, and know the answer is that it is possible. I just couldn't make it work myself, and watched a deadline blow by trying.
Comment: Can you tell my shortly,what you want exactly? you want before save or edit submit occur  user confirm it?
Comment: Sure. When a user clicks save, if the MYMODULE_is_stub($node) function returns true, the user should get a confirmation dialogue allowing them to continue with the save or go back and edit.
Comment: @UltraBob wow 21 days later and you're still on this... `abstract field has at least 300 characters or the related website field has at least one url added or the public files field has at least one file in it.` you should be able to check all of this with jQuery.  Would you like me to provide you some code?
Comment: Thanks, I have been working on other things.  Re: Jquery, I'm sure I could probably figure out that code, though at least one file might take a while. So if it wouldn't take you a long time, that code would be nice as a backup, what I really want though is 1) to be able to use the same stub checking code everywhere instead of once in php and once in Jquery 2) understand more about the Drupal code was of doing this so I can be better at doing things like this in the future. (Though maybe everything I'm learning is a waste when and if I move to 8?)
Comment: And I WOULD rather award an answer about how to do it in Jquery than the answer I currently have.
Comment: @nosssweat It isn't because you are using the $() notation for Jquery is it?  The second thing I realized about this idea is that I would then have to override the admin template too to insert the jquery in the admin form wouldn't I?  Og maybe I can do that from my module.  All this time and drupal still has me twisted.
Comment: @UltraBob nvm all of the sudden it is working, I changed jquery update module to use latest jquery for admin pages, perhaps that fixed it... I will have an answer soon.
Comment: Is an answer still coming?
Answer: You can also add the Javascript inside a custom module, using your hook_form_alter() from the question as a base:
function MY_MODULE_form_node_form_alter(&$form, &$form_state, $form_id) {

    if (in_array(strstr($form_id, '_', TRUE), $GLOBALS['conf']['publication_types'])) { // only work on the publication forms
        $form['#attached']['js'][] = drupal_get_path('module', 'MY_MODULE') . '/js/cool.js';
    }
}

In this version your cool.js file will go in the js folder in your module.
cool.js
(function ($) {

    (function Forever(){ // we create a function called Forever

        $('html').ready(function(){

            $('.cke_editable.cke_editable_themed.cke_contents_ltr.cke_show_borders').hide();

            var characters = $('#edit-field-doc-abstract-und-0-value').val().length;
            var field1 = $('#edit-field-doc-website-und-0-url').val();
            var field2 = $('#edit-field-doc-pub-files-und-0-upload').val();

            if (characters < 300 || field1 == '' || field2 == '') {
                var submit_button = document.getElementById("edit-submit");
                try {
                    submit_button.type = 'newId';
                } catch(e) {

                }

                $('#edit-submit').attr("id","msg").css({"width": "34px"});
            } else {
                var fake_button = document.getElementById("msg");
                fake_button.type = 'submit';
                $('#msg').attr("id","edit-submit");
            }

        });

        setTimeout(Forever, 1);

    })();

})(jQuery);

(function ($) {

    $( document ).ready(function() {

        $("#msg").click(function(){

            var characters = $('#edit-field-doc-abstract-und-0-value').val().length;
            var field1 = $('#edit-field-doc-website-und-0-url').val();
            var field2 = $('#edit-field-doc-pub-files-und-0-upload').val();

            if (characters < 300) {
                var a = '
Abstract is less than 300 characters.
';
            }
            else { a = ''; }
            if (field1 == '') {
                var b = '
No website to go for more information.
';
            }
            else { b = ''; }
            if (field2 == '') {
                var c = '
No public files available for download.
';
            }
            else { c = ''; }

            div1 = $("

").css({"background-color": "rgba(0, 0, 0, 0.5)", "width": "100%", "height": "100%", "position": "absolute", "z-index": "5", "left": "0"})
            div = $("
In its current form, your publication doesn't contain enough information to merit its own publication page because:
" + a + b + c + "

 Save  Edit
").css({"width": "350px", "height": "180px", "position": "fixed", "top": "0", "bottom": "0", "left": "0", "right": "0", "margin": "auto", "z-index": "10", "background-color": "#cfd2cc", "padding": "10px"});

            $("#page").prepend(div1).prepend(div);
            $('.yes').css({"background-color": "#89c640", "padding": "5px 10px 5px 10px", "font-weight": "bold", "cursor": "pointer"});
            $('.no').css({"background-color": "#d2cd4c", "padding": "5px 10px 5px 10px", "font-weight": "bold", "cursor": "pointer", "margin-left": "10px"});

            $(".yes").click(function(){
                var fake_button = document.getElementById("msg");
                fake_button.type = 'submit';
                $('#msg').attr("id","edit-submit");;
                $('#edit-submit')[0].click();

            });

            $(".no").click(function(){

                $('.blackbg').remove();
                $('.msgbox').remove();

            });

        });

    });

})(jQuery);

Result
After clicking the save button you will get:

Caviat: The character count of the abstract field will work only if you are not using CKEditor for the abstract field.
Comment: I'm trying desperately to test this before the bounty is required to be awarded.  I got updated the characters field1 and field2 id values with mine (`var characters = $('#edit-field-doc-abstract-und-0-value').val().length;
            var field1 = $('#edit-field-doc-website-und-0-url').val();
            var field2 = $('#edit-field-doc-pub-files-und-1-upload').val();`) in 2 places.  It's still not doing anything when I submit.  Is there anything else I should be changing?
Comment: I should probably mention I'm using media for the files field
Comment: @UltraBob did you replace it in 2 places? there are 2 of `var characters`
Comment: Yes, I mentioned that I had, but thanks for checking.
Comment: Maybe you need to use [jQuery Update](https://www.drupal.org/project/jquery_update) module and assign jquery 1.10 to the admin section
Comment: I really hesitate to do so for fear of it breaking something else and putting this project further behind than it already is.  I'll try it now thought to check if that does it, cause then I can work on adjusting the jquery to work with an older version.
Comment: OK, that caused it to start working, but it seems the file check doesn't work
Comment: A stub won't be created because:
Your abstract field is less than 300 characters.
Your website url field does not have atleast 1 url.
Comment: Inspect the element of the file field and use the ID you see, since you're using media as your field perhaps the name changes a bit.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/41795/discussion-between-ultrabob-and-no-sssweat).
Comment: I'm editing this to put in a version compatible with the default version of JQuery.  The problem was with trying to change the type of the button.  JQuery had a weird built in error message in older versions to stop the changing of types from messing up older versions of ie
Comment: @UltraBob ok, feel free to.
Answer:
When the user clicks 'Save' on a node edit form, I need to then evaluate whether the field values meet some criteria, and then provide the user a warning, that saving in the current state will have some effect on the way the node is displayed and give them an option to confirm or cancel.

You could get pretty close to what you're trying to do by simply (and only) using the Rules module. Some more details about this approach:

Use Rules Event "Before saving content".
Use as many Rules Conditions as needed, for any of your fields you want to validate.
Use Rules Action "Set a Drupal message*" (of type "error") for any validations that fail.

However, be aware that using Rules Event "Before saving content", you do not prevent the node from being saved. So with a rule as described above, you only show an extra error message when saving the node. This is true for either creating new nodes, or for updating existing nodes. There are a few approaches to somehow get around that node being saved anyway, such as:

Delete the node that just got created (or updated). Obviously this destroys all data entered before saving the node.
Unpublish the node, which avoids that all data entered before saving the node are destroyed. And wait for something to happen afterwards to get the node published later on.

To continue with the approach to unpublish a node that fails a validation, have a look at this rule (in Rules export format):
{ "rules_field_validations_before_saving_nodes" : {
    "LABEL" : "Field validations before saving nodes",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_presave--article" : { "bundle" : "article" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_optionlist" } },
      { "data_is" : { "data" : [ "node:field-optionlist" ], "value" : "C" } },
      { "NOT data_is" : { "data" : [ "node:field-free-format-text" ], "value" : "ignore" } },
      { "NOT user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "4" : "4" } }
        }
      }
    ],
    "DO" : [
      { "node_unpublish" : { "node" : [ "node" ] } },
      { "drupal_message" : {
          "message" : "The option list value = \u0022[node:field-optionlist]\u0022 is no longer allowed for nodes of content type \u0022[node:type]\u0022. Its status is automatically changed to \u003Cstrong\u003EUnpublished\u003C\/strong\u003E until an appropriate corrective action has been applied.\u003Cbr \/\u003E\u003Cbr \/\u003E\r\n\r\nTo still use that value: (a) enter \u0022\u003Cstrong\u003Eignore\u003C\/strong\u003E\u0022 in the field \u0022Free Format Text\u0022 to overrule this validation, or use another allowed value for option list and (b) change the node status back to \u003Cstrong\u003EPublished\u003C\/strong\u003E again.",
          "type" : "error"
        }
      }
    ]
  }
}

Some more details to further explain the above above sample:

The Rules event is "After saving new content", but as a sample I've limited it to content type "article" only (omit or adapt that extra verification as needed).
In my case I have a selection list field with machine name field_optionlist.
This field actually has 3 possible values, like so:

A (=Advanced).
B (=Basic).
C (=Custom).

As a sample, I decided to add these Rules Conditions (validations), in the order specified:

a validation to ensure that this rule only applies for nodes that have a field with machine name field_optionlist.
a validation about attempts to save a node where "The selected value" of field_optionlist equals Custom.
a validation to check if the text field with machine name field_free_format_text does NOT contain the exact value (case sensitive!) of ignore.
a validation to check that the user editing the node does NOT have a role with rid = 4 (change to whatever rid fits for your case), which could be like a content editor or so (so that users with special roles can still edit such nodes without being stuck by this rule).

If all these Rules Conditions are satisfied, then the Rules Action will perform 2 actions:

mark the node as unpublished.
display a message which looks like so (feel free to change that to whatever you want):

The option list value = "Custom" is no longer allowed for nodes of content type "article". Its status is automatically changed to Unpublished until an appropriate corrective action has been applied.
To still use that value: (a) enter "ignore" in the field "Free Format Text" to overrule this validation, or use another allowed value for option list and (b) change the node status back to Published again.

If you want, you can use the Rules UI to import the above rule in your own site. But before doing so, make sure you have defined 2 similar fields (with machine names field_optionlist and field_free_format_text). As a variation, adapt the machine names to similar fields you already have (attention about field-optionlist versus field_optionlist though, same for the 2nd field, important!).
If you're not familiar (enough/yet) with Rules, checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework, organized in 7 chapters.
Voilà, the above solution depends on Rules, nothing but Rules. Read on if you're in for adding some additional modules (and further refine it all) ...
Refinement
If you have a lot of validations to implement, you could simply add as many similar rules as you want/need, or you might want to add the Conditional Rules module to further enhance this approach. Using this extra module, you could consolidate multiple rules in a single one, which IMO makes these rules easier to maintain.
Heading for the golden cradle
If you want to take this approach (using Rules) a step further, you should have a look at the Rules Forms Support module. Some details from its project page:

Rules Forms Support provides a Rules based method for controlling forms and their elements. The module can be used to alter any form provided by Drupal core or contributed modules. Change element titles, descriptions, weights, and more, or validate form data and set form errors. Rules forms saves time and cost by affording site builders the ability to monitor and alter forms without the need to implement a custom module.

Have a look at its Community Documentation to get started with it.
Comment: Pierre!  Thank you so much for this detailed answer!  None of the answers was quite what I wanted, I want to be able to use my MYMODULE_is_stub() function for all instances if checking whether the document should be a stub.  Your answer doesn't quite work for me for a couple of reasons: 1) I can't delete or unpublish these entries, they may already be on the site either as full entries or stubs, removing them from the site, and especially trashing the data is unacceptable.  2) I was able to implement the other answer without installing a module I'm not already using.
Comment: I also intend to try modifying the query in the other answer to work without jquery update.
Answer: You can know which button has been clicked by the user with $form_state['triggering_element']
function MYMODULE_node_validate($node, $form, &$form_state) {
 if ($form_state['triggering_element']['#value'] === 'Preview') {
   if (MYMODULE_is_stub($node)) {
     dpm("This would be a stub");
   } else {
     dpm("This would not be a stub.");
   }
 }
}

Comment: Ok, so I can actually limit validation to submit only. Thanks, that is handy. Any idea on how add the confirm_form in place of dpm("This would be a stub");?
Comment: There is a very good example in [Drupal.org](https://api.drupal.org/comment/52683#comment-52683).
Comment: I read that example, and I'm sure it's because I'm new to Drupal development, but it is not clear how I integrate that with the existing content entry forms.
Comment: @UltraBob have a look at the core node module. [node_form_delete_submit](https://api.drupal.org/api/drupal/modules!node!node.pages.inc/function/node_form_delete_submit/7.x) is also a form submit callback (of the node delete button on the node edit page) and it redirects to another path where a new form is shown. However that is part of the form submit part. You should not do any redirects in validation as shown here. Validation is just to make sure all required properties are there and within valid ranges.
Comment: Thanks, I've looked at it, but I'll look again.  I'm a bit frazzled.  I'm not actually doing any redirect in the validation hook, just setting information on whether the node qualifies to be have its own page or not.


MvvmCross binding iOS Gestures

Question: I'm searching a way how can i bind ios gesture like UILongPressGestureRecognizer to ICommand or MvxCommand in MvvmCross, thanks.
PS : I found an example here but i can't figure out how to do that.
Comment: Which bit of the example can't you figure out? If you replace `Tap` with `LongPress` then what does/doesn't work - are there compile errors? Or runtime exceptions?
Comment: i added the class LongPressBehaviour and BehaviourExtensions but when i make label.LongPress(); it does not recognize it.
Answer: From the example you found and from the current MVVM Cross source I did the following
public static class MvxBehaviourExtensions
{
    public static MvxLongPressGestureRecognizerBehaviour LongPress(this UIView view)
    {
        var toReturn = new MvxLongPressGestureRecognizerBehaviour(view);
        return toReturn;
    }
}

and
public class MvxLongPressGestureRecognizerBehaviour
    : MvxGestureRecognizerBehavior<UILongPressGestureRecognizer>
{
    protected override void HandleGesture(UILongPressGestureRecognizer gesture)
    {
        // Long press recognizer fires continuously. This will ensure we fire
        // the command only once. Fire as soon as gesture is recognized as
        // a long press.
        if (gesture.State == UIGestureRecognizerState.Began)
        {
            FireCommand();
        }
    }

    public MvxLongPressGestureRecognizerBehaviour(UIView target)
    {
        var lp = new UILongPressGestureRecognizer(HandleGesture);

        AddGestureRecognizer(target, lp);
    }
}

and to bind
set.Bind(this.LongPress()).For(lp => lp.Command).To(c => c.DoTheStuffCommand);

MvvmCross binding iOS Gestures


Ionic - ng-src load icons based on conditions

Question: In my ionic app, I need to load icons using ng-src. Depending on the format of the document, corresponding icon needs to be displayed.
I was trying to do something like

If the format is docx (I have verified that format value is coming correctly), then display Word-icon.png. For everything else display PDF-icon.png.
This is not working. In fact the page stops loading when I do this. It does not throw an error in the browser console but also does not load the page. Icons are stored in the img directory inside the www folder in the ionic app.
Answer: You had unnecessary ) at the end of expression.

Comment: Thanks for pointing the extra brace. Now the page has started loading, however, the image still does not load. Image shows as blank in the Ionic app.
Comment: Do you have `ng-app="myApp"`(myApp would be your app module) directive on page to run angular on page?
Comment: Yes, there are several other angular statements on the page which work fine.
Comment: @kayasa are you sure it's not just a path issue? What do you see in the developer tools when you look at the element where the image is suppose to be?
Comment: can you check `src` attribute on that element? Then you might messed up with image path issue


Qual o risco desse injection?

Question: Fala pessoal, qual risco eu correria se alguém quisesse dar um injection nesse exemplo:
<code>$valorGet = $_GET["valor"];
$sql = "SELECT * FROM tabela WHERE caminho = '$valorGet'";
</code>
Minha dúvida é, o cara consegue deletar (DELETE) ou inserir (INSERT) algo no meu banco? Ou apenas dar um outro tipo de SELECT?
Existe a necessidade de fazer um antijection com PDO nesse caso para aumentar a segurança?
Comment: Eu sei que da pra fazer um injection, mas minha pergunta foi se o meu banco corre algum risco, pois estou fazendo só um SELECT, ele teria como dar um DELETE ou INSERT?
Answer: Sim, existe o risco de alguém deletar todo o seu banco ao explorar essa vulnerabilidade. A solução não passa necessariamente por PDO, e sim por prepared statements, que você consegue usar tanto com PDO quanto com mysqli. Note que não basta trocar o driver de conexão ao banco para resolver o problema, você precisa parametrizar a query como explicado em Como prevenir injeção de código SQL no meu código PHP.
Comment: Então, mas o cara só daria um SELECT diferente, ele não deletaria nada, não?
Comment: Como eu disse, tem sim o risco de ele deletar.
Answer: A N maneiras de inserir dados, apagar, unir tabelas, etc. Numa query simples como essa... Aqui um exemplo clássico e básico para ignorar o caminho:
<code>$valorGet = "';DELETE FROM tabela WHERE 1=1;-- ";

$sql = "SELECT * FROM tabela WHERE caminho = '$valorGet'";
</code>
neste caso a estrutura receberia:
<code> $sql = "SELECT * FROM tabela WHERE caminho = 'aqui entra o valor injetado: (';INSERT INTO tabela VALUES ('1','2','3','4');-- )'";
</code>
Cuja a saída seria algo assim:
<code>$sql = "SELECT * FROM tabela WHERE caminho = '';DELETE FROM tabela WHERE 1=1;--";
</code>
Comment: Então, mas o cara só daria um SELECT diferente, ele não deletaria nada, não?
Comment: Dá pra deletar também, vou editar a pergunta para você ver.
Comment: Era isso, valeu!

Qual o risco desse injection?


How can I add template suggestions by UUID?

Question: I'm looking for a solution to migrate content between environments (dev->staging->production) and currently I think I'll use UUID and Node Export (as far as I see UUID Features is still in alpha and isn't recommended by the community).
Sometimes I want to use template files or hooks (e.g. theme_preprocess_node) specific to a node created on my dev and then to upload the changes to production - this thing is impossible with the use of nids, but must be possible with uuids.
Is there any way out of the box to add theme_hook_suggestions by uuid, or do I need to implement it on my theme?
Thanks.
Answer: You should add a hook in your template.php, like this:
function MYTHEME_preprocess_node(&$vars) {
  if ($vars['node']->uuid == '12345') {
    $vars['theme_hook_suggestions'][] = 'my-best-tpl';
  }
}

Comment: Now I don't remember if it's $vars['node'] or $vars['#node'] :)
Comment: It is `$vars['node']`.  I ended up adding this line `$vars['theme_hook_suggestions'][] = 'node__' . strtr($vars['uuid'],'-', '_');` , so I guess there isn't an 'out of the box' functionality to do it. Thanks any way :)


jaxb xmlelement marshalling with custom attributes

Question: trying to map my class to xml and add custom attributes.
public class MyXmlMappings  {
    @XmlElement
    protected String username;
    @XmlElement
    protected String password;
    @XmlElement
    protected Integer age;
}

after marshalling to xml looks like something like this:
<myXmlMappings>
<username/>
<password/>
<age/>
</myXmlMappings>

I need to have xml like this:
<myXmlMappings>
<username type="String" defaultValue="hello" />
<password type="String" defaultValue="asdf" />
<age type="Integer" defaultValue="25" />
</myXmlMappings>

As you can see I added type and defaultValue attributes. How can I add them to myXmlMappings class to be visible after marshalling?
Adding extra fields to myXmlMappings class is not viable I would like to do it somehow with annotations.
Comment: Where do the default values come from?
Answer: XML Representation
I would recommend the following XML representation:
<myXmlMappings>
    <xmlMapping name="username" type="String" defaultValue="hello" />
    <xmlMapping name="password" type="String" defaultValue="asdf" />
    <xmlMapping name="age" type="Integer" defaultValue="25" />
</myXmlMappings>

Java Model
With the following Java model:
XmlMappings
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class MyXmlMappings  {
    @XmlElement(name="xmlMapping")
    protected List<XmlMapping> xmlMappings;

}

XmlMapping
@XmlAccessorType(XmlAccessType.FIELD)
public class XmlMapping {
    @XmlAttribute
    protected String name;
    @XmlAttribute
    protected String type;
    @XmlAttribute
    protected String defaultValue;
}

Answer: Try this:

public class MyXmlMappings {

    @XmlPath("username/@type")
    protected String userType;
    @XmlPath("password/@type")
    protected String passwordType;
    @XmlPath("age/@type")
    protected String ageType;
    @XmlPath("username/@defaultValue")
    protected String userDefaultValue;
    @XmlPath("password/@defaultValue")
    protected String passwordDefaultValue;
    @XmlPath("age/@defaultValue")
    protected Integer ageDefaultValue;
    @XmlElement
    protected String username;
    @XmlElement
    protected String password;
    @XmlElement
    protected Integer age;
}

Comment: +1 - This solution leverages the `@XmlPath` extension in EclipseLink JAXB (MOXy):  http://blog.bdoughan.com/2010/07/xpath-based-mapping.html


Derivative of $x^2e^{-x}$

Question: So I have to function $x^2e^{-x}$. Do I derivative that like $f' g+g' f$ or $f' g'$?
I'm not sure because it is derivative over x so if you can help me.
Comment: product rule: $(fg)'=f'g+g'f$
Comment: Note that $e^{-x}$ is a function inside function
Answer: It is the product rule that you need. So with $f(x) = x^2$ and $g(x) = e^{-x}$, you get the derivative of $f(x)g(x)$
$$f'(x)g(x) + f(x)g'(x).
$$
Answer: Any time you have multiplication, use the product rule $(fg)' = f'g + fg'.$
Any time you have one function inside another function (composition), use the chain rule.
In this case, you have $x^2$ times $e^{-x}$, so you use the product rule. $f(x) = x^2$, $g(x) = e^{-x}$. Can you manage from here?

Derivative of $x^2e^{-x}$


Understanding Proof of Poisson Summation Formula

Question: Consider a proof from a textbook on Harmonic Analysis:

Note that $\mathcal{S}(ℝ)$ denotes the Schwartz Space.
Question 1: Why does the top left formula in the proof start out as:
$$
\int_0^1 \left( \sum_{m ∈ ℤ} \phi(x+m) \right) \mathrm{e}^{-2 \pi i n x} \,\mathrm{d}x?
$$
Shouldn't the integrand be $\int_{-\infty}^{\infty}$?
Question 2: What justifies the leap from
$$
\sum_{m ∈ ℤ} \int_0^1 \phi(x+m) \mathrm{e}^{-2 \pi i n x} \,\mathrm{d}x = \sum_{m ∈ ℤ} \int_m^{m+1} ϕ(y) \mathrm{e}^{-2 \pi i n y} \,\mathrm{d}y ?
$$
Comment: (1) Is just the computation of the $n$-th Fourier coefficient.  Recall that the $n$-th Fourier coefficient of a $1$-periodic function $f$ is the integral $\int_{0}^{1} f(x) \mathrm{e}^{-2\pi inx}\,\mathrm{d}x$.  (2) This is a change of variables (let $y=x+m$) plus the observation that $\mathrm{e}^{-2\pi inm} = 1$.
Comment: But how do we know that $f$ is 1-periodic?
Comment: $\phi((x+m )+ 1) = \phi( x + (m+1))$.  Both terms are in series.
Comment: Out of curiosity, what book is this from?
Comment: The book is called *Harmonic Analysis: From Fourier to Wavelets* by Pereyra and Ward.
Answer: Elias Stein (famous analyst) tells a story about this theorem (folklore that I am going to mess up). He says (he gives names to at least one of these people, but I don't remember their names) a [math] professor has a class where he is talking to some of his three students. He asks the students, "Ok, given a Schwartz function, how can one get a periodic function?"
Student A says, "We can take the Fourier transform $\hat{\phi}$, apply it to integers getting $\hat{\phi}(n)$ and then form the trigonometric series $\sum_{n \in \mathbb{Z}}\hat{\phi}(n)e^{2\pi i n x}$."
The Teacher says, "Good."
Student B says, "We can take the function $\phi$ and the value at $x$ should be the value gotten by adding the value of $\phi$ at all points on the real line an integer distance from $x$ getting $\sum_{n \in \mathbb{Z}}\phi(x+n)$."
The Teacher responds well.
Student C (who is presumably Poisson), says, "These are both good... and they are equal!"
So, what we see that the idea is that we start with a function $\phi$ that is a Schwartz function on the real line. We then create a periodic function of period $1$ using both these formulas and the theorem says that they are equal. So, when the proof says that it just needs to make sure that they have the same Fourier coefficients, it is talking about these periodic functions that we were given have same Fourier coefficients because they are continuous. That is why in your first question they are only integrating on the interval $[0,1]$.
They are both continuous because $\phi$, being a Schwartz function, decays faster than any polynomial and so does its Fourier transform. In particular, there is a constant $C$ such that $\hat{\phi}(n) \leq \frac{C}{n^2}$ and $|\phi(y)| \leq \frac{C}{(1+y)^2}$ for all $n \in \mathbb{Z}$ and all $y\in\mathbb{R}$. Both of these bounds means that the the series converge uniformly and so the periodic functions that we made are continuous so their Fourier coefficients determine what function they are and we can interchange the integral and summation that you were wondering about.
Comment: Where you wrote "We can take the function $f\, [\ldots]$" did you mean "We can take the function $\phi\, [\ldots] \text? \qquad$
Comment: Oops.... missed that mistake.
Answer: Question 1:  Define the function $f$ by
$$ f(x) := \sum_{m\in\mathbb{Z}} \phi(x+m). $$
Observe that
$$ f(x+1)
= \sum_{m\in\mathbb{Z}} \phi((x+1)+m)
= \sum_{m\in\mathbb{Z}} \phi( x + (m+1) )
= \sum_{m'\in\mathbb{Z}} \phi(x+m')
= f(x), $$
where $m' = m+1$.  Thus $f$ is a $1$-periodic function.  Since $f$ is a $1$-periodic function, we may compute its $n$-th Fourier coefficient using the usual integration, i.e.
$$ \hat{f}(n)
= \int_{0}^{1} f(x) \mathrm{e}^{-2\pi inx}\,\mathrm{d}x= \int_{0}^{1} f(x) \mathrm{e}^{-2\pi inx}\,\mathrm{d}x
= \int_{0}^{1} \sum_{m\in\mathbb{Z}} \phi(x+m) \mathrm{e}^{-2\pi inx}\,\mathrm{d}x, $$
which answers your first question.
Question 2:  This is a fairly straight-forward change of variables.  Let $y = x+m$.  Then (using the usual shorthand) $\mathrm{d}y = \mathrm{d}x$, which gives us
\begin{align} \sum_{m\in\mathbb{Z}} \int_{0}^{1} \phi(x+m) \mathrm{e}^{-2\pi inx} \,\mathrm{d}x
&= \sum_{m\in\mathbb{Z}} \int_{m}^{m+1} \phi(y) \mathrm{e}^{-2\pi in(y-m)} \,\mathrm{d}y && (\text{change of variables}) \\
&= \sum_{m\in\mathbb{Z}} \int_{m}^{m+1} \phi(y)\, \mathrm{e}^{-2\pi iny}\mathrm{e}^{2\pi inm}\, \mathrm{d}y \\
&= \sum_{m\in\mathbb{Z}} \int_{m}^{m+1} \phi(y) \mathrm{e}^{-2\pi iny}\, \mathrm{d}y. && (\text{since $\mathrm{e}^{2\pi ik} = 1 \forall k\in\mathbb{Z}$})
\end{align}
This seems to answer your second question.
Comment: Is there a definition of the nth Fourier coefficient that doesn't depend on knowing the periodicity of the function in question?

Or does the definition of a Fourier coefficient always depend on the specific periodicity of the function in question? If so, what if the function isn't periodic? Does that mean there's no Fourier coefficient definable?
Comment: @user1770201 The basic answer to your question is that when we talk about Fourier coefficients, we are talking about the values of the Fourier transform of a function defined on the circle (a periodic function).  There is a lovely theory that generalizes this idea to locally compact abelian groups; under this generalization, the Fourier coefficients are related to the inverse Fourier transform.  However, the term "Fourier coefficient" is typically only meaningful for periodic functions.  In other groups, the objects are a little different, with different language used to describe those ideas.
Answer: there is lot easier than that
consider the fourier series expansion for the 1-periodic function
$$ \lfloor x\rfloor = x - \frac{1}{2} + \frac{1}{\pi}  \sum_{k=1}^\infty \frac{\sin(2 \pi k x)}{k} $$
and get this into the Euler sum formula
and use Euler sum formula plus integration by parts
$$ \sum_{n=-\infty}^{\infty}f(n) = - \int_{-\infty}^{\infty}f'(x)\lfloor x] $$
and you have the Poisson sum formula, very easily
Answer: This was meant to be a comment in reply to a comment in Xander Henderson's nice answer, but it got too long.
The abelian group $A = \{x\}$ of the domain of complex-valued functions $f(x)$ we are thinking about is always understood in the context of the problem, and then the Fourier transform $\mathcal F\colon f(x)\mapsto \hat f(\xi)$ yields a complex-valued function $\hat f(\xi)$ on the "dual" group $\hat A = \{\xi\}$.
Also it's very common that the abelian groups $A$ and $\hat A$ have topological structure (because we want to talk about convergence), or in other words a notion of "open sets," and usually a rather descript one at that (locally compact is often assumed, as well as Hausdorff), or even smooth structure if we want to study  the relationship between the operator $\mathcal F$ and differential operators, or use said relationship as (a collection of) tools for something else we're working on.
When passing from a rapidly decaying function $f(x)$ on $\mathbb R$ to its periodization, $f_{per}(x) = \sum_{n=-\infty}^\infty f(x-n)$ (say as a tool to prove the Poisson summation formula, for example), we consider $f_{per}(x)$ as a function on the circle ($S^1$). Then we need to keep in mind that although

$\hat{\mathbb R} = \mathbb R$, hence $\hat f(\xi)$ is a function of $\xi\in\mathbb R$
$\hat{S^1} = \mathbb Z$, so $\hat{f_{per}}(\xi)$ is a function of $\xi\in \mathbb Z$.  So we usually use the psychologically convenient variable $n$ instead of $\xi$ and write $\hat{f_{per}}(n)$.


Consensus and Profile from Rosalind Problems

Question: I am working on Rosalind problem and specifically problem titled "Consensus and Profile"
The data input is as follows:
 >Rosalind_1
 ATCCAGCT
 >Rosalind_2
 GGGCAACT
 >Rosalind_3
 ATGGATCT
 >Rosalind_4
 AAGCAACC
 >Rosalind_5
 TTGGAACT
 >Rosalind_6
 ATGCCATT
 >Rosalind_7
 ATGGCACT

The above are seven DNA sequences with their IDs or headers and the output should be something like:
ATGCAACT
A: 5 1 0 0 5 5 0 0
C: 0 0 1 4 2 0 6 1
G: 1 1 6 3 0 1 0 0
T: 1 5 0 0 0 1 1 6

Now, So far this is my code and I want to generate the matrix above which counts all A's Cs, Gs, and Ts in column-wise:
import sys
import Bio.SeqIO

count = {}
count=OrderedDict()
list_seq = []
for seq in Bio.SeqIO.parse(sys.stdin, 'fasta'):
    sequn = str(seq.seq)
    print "sequn",sequn
    for i,nuc in enumerate(sequn):
            print "nuc", nuc
            key = (nuc,i)
            try:
                    count[key] = count[key]+1
            except KeyError:
                    count[key] = 1

The output for the dictionary count looks something like this:
([(('A', 0), 5), (('T', 1), 5), (('C', 2), 1), (('C', 3), 4), (('A', 4), 5),
(('G', 5), 1), (('C', 6), 6), (('T', 7), 6), (('G', 0), 1), (('G', 1), 1),
(('G', 2), 6), (('A', 5), 5), (('G', 3), 3), (('T', 5), 1), (('A', 1), 1),
(('C', 7), 1), (('T', 0), 1), (('C', 4), 2), (('T', 6), 1)])

I want to generate the output matrix from the above output dictionary, how can this be done?
Thanks a lot in advance.
Comment: Which part are you having trouble with? Switching data structures from a dict of tuples to a list of dicts would probably make the problem a lot easier.
Comment: Hey @tripleee I am done with the part for designing the matrix output. But the problem I am having now is how do I get the resulted sequence that is ATGCAACT. It is a result from the most common base in each column. Thats what I am stuck with right now.
Answer: d = {}

count = ([(('A', 0), 5), (('T', 1), 5), (('C', 2), 1), (('C', 3), 4), (('A', 4), 5),(('G', 5), 1), (('C', 6), 6), (('T', 7), 6), (('G', 0), 1), (('G', 1), 1),
(('G', 2), 6), (('A', 5), 5), (('G', 3), 3), (('T', 5), 1), (('A', 1), 1),
(('C', 7), 1), (('T', 0), 1), (('C', 4), 2), (('T', 6), 1)])

for each in count:
    if each[0][0] in d:
        li = d[each[0][0]]
        spot = each[0][1]
        li[spot] = each[1]
        d[each[0][0]] = li
    else:

        li=[0]*8
        spot = each[0][1]
        li[spot] = each[1]
        d[each[0][0]] = li

for each in sorted(d):
    print each," ",d[each]

sol=""
for each in range(8):
    sol+=max(d, key=lambda x:d[x][each])
print sol

I just Iterated the whole dict and created a new dict as your question stated.
But you could do that while modifying the dict count. I have assumed the length of list to be 8. If it is above 8. The the above should be modified accordingly.
It would be nice if you could just edit the question to the point.
Comment: Hi @WannaBeCoder, thanks for your reply. I tested the code you wrote and error occurred saying that  spot = each[0][1] IndexError: string index out of range
Comment: I am not getting any such error at spot. Is count what I think it is?
Comment: I fixed the issue it worked thanks a lot but there is one thing I am having trouble with that is how can I output the sequence above the matrix?
Comment: thanks a lot but still the index out range is still there     spot = each[0][1]
IndexError: string index out of range.
Comment: That is very strange I checked my code and I don't get why I am getting the error.
Comment: I think it has something to do with Python Version. I will check it and will let you know meanwhile I truly appreciate your outstanding help
Answer: Here is a solution using BioPython and collections.Counter
from Bio import SeqIO
from collections import Counter

def main(fasta_file):
    """
    >>> print main(r'./data/CONS_sample.fa')
    ATGCAACT
    A: 5 1 0 0 5 5 0 0
    C: 0 0 1 4 2 0 6 1
    G: 1 1 6 3 0 1 0 0
    T: 1 5 0 0 0 1 1 6
    """
    with open(fasta_file) as fh:
        dna_strings = [str(fasta.seq) for fasta in SeqIO.parse(fh, 'fasta')]
        transposed = zip(*dna_strings)
        counters = [Counter(column) for column in transposed]

        # create consensus
        consensus = ''.join([counter.most_common(1)[0][0] for counter in counters])

        # create profile matrix
        matrix = ''
        for base in 'ACGT':
            matrix += '{}:'.format(base)
            for counter in counters:
                matrix += ' {}'.format(counter[base])
            matrix += '\n'
        matrix = matrix.rstrip()

        return '\n'.join([consensus, matrix])

if __name__ == '__main__':
    import doctest
    doctest.testmod()

    print main(r'./data/CONS.txt')


Ajax Random characters in text input by click button

Question: This is random PHP code:
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$length = 5;
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
    $randomString .= $characters[rand(0, $charactersLength - 1)];
}//end loop

Form
<form>
  <input type="text" id="show_random">
  <button onclick="genCode()">gen</button>
</form>

Comment: Where is ur JS code ?
Comment: i want JS code function you can help me #thankyou
Answer: Using jQuery,
var genCode = function() {
  'use strict';

  $.ajax('/path/to/your/file.php', {
    success: function(response) {
      $('#show_random').val(response);
    }
  });
}

Answer: Try this
<?php
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $length = 5;
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++)
    {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }//end loop
?>

<form>
    <input type="text" id"first_textbox">
    <input type="text" id="show_random" value="<?php echo $randomString; ?>">
    <button onclick="genCode()">gen</button>
</form>

Comment: I want display id "show_random" after click button
Comment: What do you exactly need? the random code within the textbox with id "show_random" or anything else?
Comment: yes but i want random code within the textbox with id "show_random" after click button
Comment: for that only i asked you to put the value attribute there
Comment: this code is awesome, but i want to gen code by ajax i don't want to refresh my page #thank you so much
Answer: You may try the script below:
function genCode() {
    var r = new XMLHttpRequest();
        r.open("POST", "index.php", true);
        r.onreadystatechange = function () {
            if (r.readyState != 4 || r.status != 200) return;
            document.getElementById("show_random").value = r.responseText;
        };
        r.send("");
}

Note: replace index.php on where your php code for random text is located.
Answer: Don't forget to include Jquery lib first
    function genCode()
    {
        $.ajax({
            url : '/path/to/your/file.php',
            success: function(response) {
              $('#show_random').val(response);
            }
        });
    }


"TypeError: 'NoneType' object is not callable" sometimes appears, sometimes - not

Question: I have 2 functions for reading data from file and putting it to dictionary.
def read_input():
  f = open(r"D:\data.txt","r")
  g = {}
  for ln in f.readlines():
  ...g = ...
  f.close()
  return g

almost the same with the second function:
def reverse():
  f = open(r"D:\data.txt","r")
  g = {}
  for ln in f.readlines():
  ....
  f.close()
  return g

after that I had such code:
g = read_input()
g_rev = reverse()

works fine for small g & g_rev (for small input files). After that I need to do deep recursion so I added these lines and included both read_input and reverse to main1
if __name__=="__main__":
  sys.setrecursionlimit(100000)
  threading.stack_size(67108864*3)
  thread = threading.Thread(target=main1)
  thread.start()
  thread.join(0)

still works fine wil small g... But with big input files I got such error:
g = reverse()
 TypeError: 'NoneType' object is not callable.

If I swap read_input() and reverse() and call reverse() it passed, but there is the same error for read_input
Comment: You start out with "I have 2 functions for reading data from file and putting it to dictionary."  I don't see how that leads to threading and recursion.  Could you connect the dots for me?
Comment: Does the `...` bit include `reverse = (something)` somewhere?
Comment: no, just reading data to init dictionary. Both functions are called just once
Comment: Why are you doing ``for ln in f.readlines():``? You can just do ``for ln in f:`` which iterates, rather than creating a list. More efficient.
Comment: What does this have to do with (a) Stack Overflow?
Comment: Stack Overflow - it was just suggestion, because for small input files everything works
Comment: "I don't see how that leads to threading and recursion" I got segmentation fault for big input files, so I tried this way... Regarding threading - the same, to increase stack size
Answer: There might be a mistake with either the read_input() or reverse().
Scenario 1
By the time return g is executed, g is already a NoneType
Scenario 2
There's a defect with the functions that prevent them to reach the return g statement.

Either way, to really help you, we'll need more piece of your code especially the functions part.


How to create multi-value, multi-bundle entity reference fields in code?

Question: I'm looking for example code that demonstrates creating a new entity reference field with multiple values, referring to multiple different bundles.
Answer: Sorry for the long code dump but there's really no other way to do this:
field_create_field(array(
  'translatable' => '0',
  'entity_types' => array(),
  'settings' => array(
    'target_type' => 'node',
    'handler' => 'base',
    'handler_submit' => 'Change handler',
    'handler_settings' => array(
      'target_bundles' => array(
        'article' => 'article',
        'page' => 'page',
        'webform' => 'webform',
      ),
      'sort' => array(
        'type' => 'none',
        'property' => 'nid',
        'field' => 'body:value',
        'direction' => 'ASC',
      ),
      'behaviors' => array(
        'views-select-list' => array(
          'status' => 0,
        ),
      ),
    ),
  ),
  'storage' => array(
    'type' => 'field_sql_storage',
    'settings' => array(),
    'module' => 'field_sql_storage',
    'active' => '1',
    'details' => array(
      'sql' => array(
        'FIELD_LOAD_CURRENT' => array(
          'field_data_field_entity_reference' => array(
            'target_id' => 'field_entity_reference_target_id',
          ),
        ),
        'FIELD_LOAD_REVISION' => array(
          'field_revision_field_entity_reference' => array(
            'target_id' => 'field_entity_reference_target_id',
          ),
        ),
      ),
    ),
  ),
  'foreign keys' => array(),
  'indexes' => array(
    'target_id' => array(
      'target_id',
    ),
  ),
  'field_name' => 'field_entity_reference',
  'type' => 'entityreference',
  'module' => 'entityreference',
  'active' => '1',
  'locked' => '0',
  'cardinality' => '-1',
  'deleted' => '0',
  'columns' => array(
    'target_id' => array(
      'description' => 'The id of the target entity.',
      'type' => 'int',
      'unsigned' => TRUE,
      'not null' => TRUE,
    ),
  ),
  'bundles' => array(
    'node' => array(
      'page',
    ),
  ),
));

The target_bundles in the handler_settings is where you assign the different bundles, and the cardinality of -1 ensures unlimited values for the field.
In case you're interested, this is the code that allowed me to build the above definition from an existing entity reference field (which seems to have originated at this blog post):
$entity_type = 'node';
$field_name = 'field_entity_reference';
$bundle_name = 'article';

$info_config = field_info_field($field_name);
$info_instance = field_info_instance($entity_type, $field_name, $bundle_name);
unset($info_config['id']);
unset($info_instance['id'], $info_instance['field_id']);
include_once DRUPAL_ROOT . '/includes/utility.inc';
$output = "field_create_field(" . drupal_var_export($info_config) . ");\n";
$output .= "field_create_instance(" . drupal_var_export($info_instance) . ");";
drupal_set_message("<textarea rows=30 style=\"width: 100%;\">". $output .'</textarea>');

It's a handy little script; I'm sure I've posted it somewhere here before but I can't find it at the moment.
Comment: I've seen the same script before (and commented on it to) ... I saw it first at this [blog post](http://steindom.com/articles/exporting-and-creating-field-definitions-drupal-7)
Comment: @tenken Thanks I always wondered where I got that from; now I can provide proper attribution


How is Reflection Implemented in Java?

Question: The Java 7 Language Specifications say pretty early on:

"this specification does not describe reflection in any detail."

I'm wondering just that: how is Reflection implemented in Java?
I'm not asking how it's used, and I understand there might not be as specific an answer I'm looking for, but any information would be much appreciated.
I've found this on Stackoverflow, the analogous question about C#: How is reflection implemented in C#?
Comment: Pretty much smoke and mirrors.  Lots of `native` methods that dork around in the innards of objects.  A `native` method pretty much can do anything it wants.
Answer: The main entry point of any Reflection activity is the Class class. From it you can get Method, Field, Class, Constructor, and Annotation instances.
If you look at the source code, you will notice that to retrieve any of the above, Java has to make a native call. For example,
private native Field[]       getDeclaredFields0(boolean publicOnly);
private native Method[]      getDeclaredMethods0(boolean publicOnly);
private native Constructor<T>[] getDeclaredConstructors0(boolean publicOnly);
private native Class<?>[]   getDeclaredClasses0();
private native byte[] getRawAnnotations(); // get converted to Annotation instances later

The implementation is done in native C code (and/or C++). Each JDK might differ, but you can look up the source code if it's available and you have patience. Details on the OpenJDK source code can be found in this question.

How is Reflection Implemented in Java?


Protocolo TLS 1.2 CT-e 3.0 e NF-e 4.0

Question: Estou desenvolvendo a CT-e 3.0 e a NF-e 4.0, nas mesmas cita a necessidade em mudar o protocolo de segurança de SSL para TLS 1.2 com o prazo de 02/04/2018.
Nos webservice de recepção não tem informações sobre os protocolos, a documentação de ambos (CT-e e NF-e), deixa um pouco vago as alterações que são necessárias.
a aplicação é desenvolvida em c# e VB.NET.
Devido a isso, busquei implementações na internet chegando a seguinte implementação: ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 Or SecurityProtocolType.Ssl
Mesmo implementando isso não tivemos diferenças e também não conseguimos executar o teste para saber se é somente está alteração que deve ser feita ou se a alteração também deve ser feita em certificado digital e/ou cadeia de certificados.
Gostaríamos de ter certeza que são somente estas as alterações necessárias?
Caso tiver algo a mais a ser implementado gostaria da contribuição da comunidade.
OBS: Utilizamos Certificado A1 e A3.
Comment: Acredito que seja só isso mesmo, mas por acaso você chegou a alguma conclusão diferente?
Answer: Fiz o seguinte teste:
Usei um aplicativo para consultar status da SEFAZ MG no ambiente de homologação com .NET Framework 2.0, sem alterar o protocolo para TLS 1.2.
Abri o Wireshark e ativei um filtro de pacotes para protocolo TLS 1.2 desta forma:
ssl.record.version == 0x0303

O resultado foi que nenhum pacote foi exibido, ou seja, não transmitiu com o protocol TLS 1.2.
A seguir, alterei o código para usar o TLS 1.2. No .NET 2.0, não tem a constante na enumeração, mas é possível fazer o equivalente da seguinte forma:
System.Net.ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;

Ao executar o aplicativo com esta alteração, o Wireshark exibiu pacotes conta um IP da SEFAZ com o protocolo TLS 1.2.

Conclusão: Esta é a única alteração necessária.

Protocolo TLS 1.2 CT-e 3.0 e NF-e 4.0


Show blocks at a specific URL

Question: I'm trying to move some Blocks to a different Page.  None of the Blocks are defined in a region. They are specified to display on every Page.
In reality, they show up on only one Page. I tried deleting that Page, and when I navigate to the URL of that page, the Blocks still show up, along with the message that this page does not exist. I made a new Page, and I can't figure out how to get those Blocks to display on the new Page. I've been looking into this for weeks, and I just can't figure it out.
Any suggestions in this matter?
Comment: Well, I anticipate you have the source code in front of you. If you can't find it in the back-end (structure/blocks, panels, views, displays), it's probably done programmatically within custom modules/the theme. As there are plenty possible locations which even vary between Drupal 7 and 8, I fear you're on your own finding it first, or asking someone to help you review your code base. Surely out of the scope of what we can do at Drupal Answers without a lot of guesswork.
Comment: Thank you, @MarioSteinitz.  I have looked at the theme code.  I did a search for the URL in the whole folder, and I found nothing.  It leads me to believe that there is some setting in the database that is controlling its visibility.
Comment: Probably it's connected to the node ID, URL aliases (which you'd find in the database), ... - Try finding the block ID and check if it is hard-coded somewhere, locate probably used templates (e.g., by enabling theme debugging in Drupal 8, or searching for specific HTML/CSS classes), check according preprocess hooks in the theme or custom modules. That's what I'd try first having the source code in front of me. Yet, all things that are hard to help you with without access to the sources.
Comment: Cowards down vote a question without providing any feedback.
Answer: If you are in Drupal 7 you will need to check the block visibility settings for that block

structure > block
in the list find the block in question and click configure
change the visibility settings

On a default installation there are visility settings per URL / per content type / per role / per user but many more can be added by contributed modules.
On Drupal 8 something similar can be found on structure > block layout
Comment: There's probably a good technical reason context was installed in drupal 7. I believe on larger sites or sites with lots of blocks it improved performance instead of use the regular block admin.
Comment: The Blocks are being displayed at the URL even though this setting is blank.  (All pages except those listed.)  I tried this earlier, and I did get some results, but it just wasn't what I need.
Comment: Then you need to share more information about your setup. The procedure above is the most widely used way to put a block on a specific URL.  Of course some module can do such thing programmatically but we can't guess which module might be doing this.
Comment: That's what's so frustrating about this whole problem.  If the developer had followed "widely used" practices, I probably would not be in this situation.
Comment: Well, that is good to know, @Kevin.
Answer: Well, I figured it out.  There is a module called Context installed on the website, and, as I originally suspected, this module looks at the path and modifies (or "reacts") to the path when the user navigates to it.
I also had problems adding and modifying blocks to the regions available in the Context editor.  You have to select the item on the right side first, and then click on the +Add button on the left side in the region you want to add the block to.
After so many weeks, this is such a relief to be able to find out.  I sincerely hope that I do not have such issues again.  Thank you again, so much, for your help in all of this.  I know it doesn't seem like you helped much, but I think by just talking it out a little bit more, I was able to pinpoint the issue.
Comment: glad you figured it out ... content was going to be my next suggestion actually !!!

Show blocks at a specific URL


Show for all primes $p>11$ there are two consecutive quadratic residues

Question: I am supposed to use this fact to help prove it.
If $p$ is an odd prime, then at least one of the numbers $2,5,10$ is a quadratic residue mod $p$
I can prove this by saying let $(\frac{10}{p}) = 1$
Then $(\frac{2}{p}) = -1$  $(\frac{5}{p}) = -1$
let $(\frac{10}{p}) = -1$
Then $(\frac{2}{p})$ or $(\frac{5}{p}) = 1$
So to start off we know that p is a odd prime $>11$
$2,5$ or $10$ is a quadratic residue of p
I am assuming the best way to start this is to say
Let $(\frac{2}{p}) = 1$ where $p>11$ Then try to show that  $(\frac{3}{p}) = 1$ where $p>11$ is a quadratic residue
Then do the same for the other two.
But i am unsure about how to go about this
Comment: See [this question](http://math.stackexchange.com/questions/1267202/proving-consecutive-quadratic-residue-modulo-p).
Comment: In particular, see [this answer](http://math.stackexchange.com/a/292747/107671), which explains how you should finish your proof.
Answer: If $2$ and $3$ were both prime residues, that would suffice.  However, note instead that $1 = 1^2$ is always a quadratic residue, so there's no need to examine $\binom{\underline{3}}{p}$, which is not always $1$.  Note that $4 = 2^2$ and $9 = 3^2$ are similarly always residues.
(I will note that in your given argument you leave out the possibility that all three of $\binom{\underline{2}}{p}, \binom{\underline{5}}{p}, \binom{\underline{10}}{p}$ are equal to $1$.  The cleaner argument would be to note that $\binom{\underline{2}}{p} \cdot \binom{\underline{5}}{p}=  \binom{\underline{10}}{p}$ implies that not all three values are $-1$.)


How to get page_id from facebook url

Question: my question is how get facebook page_id starting from a simple fb url. For example:

http://www.facebook.com/vanityurl
http://www.facebook.com/pages/pagename/pageid

Actually if the url match the string "facebook.com/pages/" I call:

https://graph.facebook.com/pageid

else I call:

https://graph.facebook.com/vanityurl

This approach seems to work well, but it is really empirical and looking at documentation I don't see any suggestion.
What do you think about?
Comment: In most cases you'll already have the page ID from another API call, right? (from a user's feed, or list of likes, etc?) - otherwise the method you've outlined above is the best I can think of
Comment: @freedev your question is your answer, this is the best way I know of and I am using the same too..
Comment: Actually I only have a list of urls which I have to investigate for.
Answer: Simple Instructions:

Go to the desired Facebook page
Ctrl + U to view Page Source
Ctrl + F to open a search dialog box
Using the search dialog box, search "page_id=" in the code
The 'page_id' should follow the "=" symbol

TEST:
Search for the desired page using the 'page_id' in place of the page name:
www.facebook.com/[insert 'page_id' here]
Comment: This worked for me. Just one thing I was able to get page id by searching "pageid" not "page_id".
Answer: I'm not quite sure what you're asking but I think what you're talking about is trying to get the id of a page that you only know by its "vanity url" or "nickname".
Basically you can do a facebook graph api request to the "vanity url" and then grab the id from the provided request.
For example... if you open the Facebook graph API explorer
https://developers.facebook.com/tools/explorer?method=GET&path=coca.cola.
or make a request to http://graph.facebook.com/coca.cola
you can see in the response you get
  "id": "40796308305"
which is the page ID you are talking about.
Navigating to http://www.facebook.com/40796308305 should prove that.
Hope that helps.
Answer: For my OG meta <meta property="fb:app_id" content="010101010101010" />
I got my page app id by going here:
https://developers.facebook.com/docs/plugins/page-plugin
get code > appId
Line 6: js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.9&appId=
010101010101010";
The sharing debugger has now stopped complaining
https://developers.facebook.com/tools/debug/

How to get page_id from facebook url


Copy column data from one table to another

Question: I have two databases, one which is old and one which is new. I need to copy one particular column from the old to the new. Structure-wise they are both totally identical, although the new table is significantly larger than the old, and the only way i can connect these two tables together by a foreignkey is the uni_id, which is just a normal integerfield, but its unique.
So this is basically the structure of the table:
|    id    |    name    |    name_pseudo    |    uni_id    |
------------------------------------------------------------

I want to compare each row of new_db.mytable with old_db.mytable by uni_id and insert old_db.mytable.name_pseudo into new_db.mytable.name_pseudo.
Can such expression in pure MySQL be constructed?
Answer: From the MySQL manual on UPDATE

You can also perform UPDATE operations covering multiple tables. However, you cannot use ORDER BY or LIMIT with a multiple-table UPDATE. The table_references clause lists the tables involved in the join. Its syntax is described in Section 184.108.40.206, "JOIN Syntax". Here is an example:

UPDATE items,month SET items.price=month.price
    WHERE items.id=month.id;

Which in your case should read like:
UPDATE newdb.mytable AS new, old_db.mytable AS old
    SET new.name_pseudo=old.name_pseudo
    WHERE old.uni_id=new.uni_id;

Comment: Strange, `only 1 row affected`.


How can I read a custom section within the loader?

Question: I'm trying to embed information (a simple integer) inside the executable object file (Elf) of a process in Linux.
I've accomplished that by writing the integer value as binary inside a file, and then by copying the binary file content using the objcopy command.
objcopy --add-section .customsection=binaryfile processElfFile newProcessElfFile

In this way, inside newProcessElfFile I have a perfectly working copy of the process with a new section containing the integer value, and I can see the section by using
readelf -e newProcessElfFile

I have also verified the section value being correct by using some C code on top of the Libelf library. Everything works fine.
Now, I want to read the integer value contained in the new section and perform a printk when the elf file is loaded to be executed.
In order to achieve this, I need to modify the loader code, which is kernel side.
The problem now is that:

I cannot write code inside the kernel which uses the libelf library, so I cannot access directly the section value as I do with my user-side program.
The elf kernel loader, contained inside linux-VERSION/fs/binfmt_elf.c, in the function load_elf_binary(), doesn't read elf sections, but access the elf program headers, which point towards elf segments, not the single sections.

In order to solve the problem I guess I need to link my custom section within a segment such that I can access it.
So I have 2 related questions:

Can I somehow read directly my custom section within the loader?
If not, How can I make a segment link to the custom section, so that I can access it using the elf file program headers?

Another possibility may be to add the integer value as an element of the already existent .rodata section, but I unfortunately don't know how to perform it and again how to access that section in the kernel.
Answer: The ELF header (Elf32_Ehdr or Elf64_Ehdr) contains information pointing to the section header table (members e_shoff, e_shentsize).  Together with the section string table index (e_shstrndx), this information can be used to read the section headers and eventually locate the data you are interested in.
Comment: Thank you, I have used those informations and succeeded at reading the elf binary file by modifying the load_elf_binary() kernel function
Comment: Note however that (unlike segments) sections headers are *not* required at execution time, and will be missing from fully-stripped binaries (this is why the kernel only uses segments).
Comment: @AndreaB I am trying to do the same thing and having issues with viewing the new section (readelf -e). Where does it appear for you?
Comment: @AndreaB Rather, I do see the new section appear but I don't see it in the "Section to Segment mapping: Segment Sections..." portion


How to fit label element inside a div element

Question: I have a div element that covers the whole width of the window and a label inside of it. The label gets changed dynamically and sometimes the text inside it goes beyond the boundaries of the div. There is an example:
http://jsfiddle.net/VWNKC/
I tried with the:
white-space: nowrap

on both div and label but it just didn't work.
I am just wondering if it is possible to shrink the text inside the label so it fits the width of the parent div.
You can see that the label goes beyond the div if you scroll and try to select something after the end of the blue background of the div. There is still content.
EDIT:
I am not trying to shrink the text but to show parts of its content, Lets say the beggining of the text. I am not trying to change the size of the font, I just want to show the part of the text that fits inside the div.
Comment: You can only do that using Javascript, white-space: nowrap won't change the font size.
Comment: @Twan isn't it possible doing it without using javascript. I do believe there is a more rational way instead of using script.
Comment: Not if you want to shrink the text to fit your div. That can only be done with Javascript.
Comment: @Twan I updated my answer. I am not trying to change the size of the text.
Comment: Like stated in the answer below me, add this to your css file: #middle-section{
    overflow:hidden;
}
Answer: It seems you want the label to wrap inside the parent container?
In that case white-space: nowrap will not work, that will just cause the label text to go beyond the parent container's boundary without wrapping to the next line.
So there are two ways you could do this, either have the text wrap to the next line so that the label remains within the width of the div, or have it gracefully truncate by using the following CSS Properties:
text-overflow: ellipsis;
overflow: hidden;

Comment: Your answer gets the closest to what I am looking for. I just changed the parent container width from 200px to 100% because this is how I need it in my layout. I try it now and give a feedback for your answer.
Comment: I am just wondering why it is not possible to add left padding to the text itself?


Calculating Needed Alloy Using Linear System Of Equations

Question: I'm having troubles with this question which involves a linear system of equations. I keep encountering $x$ to be a negative number, which cannot be possible because you can't have a negative number of a physical item (ie: you can't have $-6$ school buses, $-2$ pencils, etc). Can someone help me figure this one out?
<code>An artist was commisioned to make a 500 gram statue composed of 60% tin. She has 70% tin alloy and 30% tin alloy available.

1. What mass of each alloy is required to produced the desired ally? Use an elimination method to solve this problem.
</code>
This is the equations I tried:
$x + y = 500 \\
0.70x + 0.30y = 0.60$
This is what I got to eliminate $y$:
$
(x+y=500)*3 = 3x+3y = 1500 \\
(0.70x + 0.30y = 0.60)*10 = 7x+3y=6
$
Here's how I did it:
$\require{cancel}
\space\space\space\space\space\space\space\space\space3x+\bcancel{3y}\space\space\space=1500\\
- (-7x-(\bcancel{3y})=-6)\\
\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\\
x = -4x \space\space\space\space\space\space\space\space\space\space\space\space\space\space\space= 1494\\
x = \frac{-4x}{-4} = \frac{1494}{-4} \\
x = \frac{1494}{-4} = -373.5
$
And since $x = -373.5$ then
$y = 500 - x \\\space\space= 500 - (-373.5) \\\space\space= 873.5$
If you do it backwards then it works but (like I said), I can't see how $x$ can be a negative number. Any ideas?
Answer: I haven't worked out the problem, so I don't know if this will solve all your issues, but it seems to me that your system of equations might be incorrect. Take a look at your second equation:
0.70x + 0.30y = 0.60
Now, from your first equation, we can assume that x is the necessary number of grams of alloy 1 and y is the necessary number of grams of alloy 2. Following this logic, your second equation is dealing with concentrations. Now, 0.70x + 0.30y should give you the amount of total tin being used. If that's correct, this expression should equal the desired amount of tin in the finished product (i.e. 0.60*500g). Ergo, your second equation should be 0.70x + 0.30y = 300.  Hopefully this helps.
Comment: Thanks! I guess you don't even need two equations to figure that out. I just figured it out like below (but for the sake of getting good marks, I also did it using 2 equations).

$$
0.70x + 0.30(500-x)=0.6(500) \\
0.70x + 150 - 0.30x = 300 \\
0.4x = 300 - 150 \\
\frac{0.4x}{0.4} = \frac{150}{0.4} \\\\
x = 375 \\
y = 500 - x \\
y = 500 - 375 \\
y = 125
$$
Answer: Hint: You need $0.7x+0.3y=300$.


All my blocks are gone. Even the block menu entry is gone

Question: Anyone know what I might have done? I found a few things about hook_block being implemented in template.php causing this, but I don't implement hook_block at all.
Answer: If you have a module and theme with the same name, this will happen (regardless if you do/don't have hook_block in either of theme).
Answer: The problem was the Context module. Once I disabled it my blocks came back.


Hyper-V vs KVM for running Ubuntu + Windows

Question: I am currently planning to set up a server for virtualisation. It will be running about half Windows 2012 servers and half Ubuntu. Would it be better to use hyper-v or KVM as the hypervisor as I am not sure which would give the best performance.
Comment: I think you be hard pressed to see a performance difference, so I'd go with what you are most familiar with.
Comment: Thanks, I just wanted another opinion before I did anything stupid.
Answer: I myself would go with Hyper-V (especially if 3.0) as long as MSFT verifies that your Ubuntu version will run as a VM...
See http://technet.microsoft.com/en-us/library/cc794868(v=ws.10).aspx for Hyper-V on W2008[R2] Linux guest compatability
(Cannot find the same sort of article for Hyper-V on 2012, but hopefully there will be one soon)
Comment: well Will I guess we won't know what he's using in this case!
Comment: reason for that being?