Rails loop through data in a form field

Question: I would like to loop through data in my database inside my form. What I would like to do with the data is put it in labels and textboxes. How could I do this in rails? Would I just use a .each block to loop through it inside the form? The reason I have it in my database is because my client would like to be able to add the form field data himself.

For example here is something I would like to do:
<%= form_for :order do |f| %>
  @fields.each do |field|
    <%= f.label field.name %>
    <%= f.text_field field.name %>
  <% end %>
  <%= f.submit %>
<% end %>

What the best way to accomplish something like this?
Please don't answer with a railscast :)
Thanks in advance
Comment: Railscast is a helpful resource which you can learn "how to catch fish". If you just ask questions on SO and someone "get you fish", you are not really learning anything, but just temporarily solving a problem. In return, this method will consume more amount of time than just learning the rails with railscasts or with books.
Comment: @Jake - it's generally considered good form to "accept' an answer if it solves your problem. You can do that by clicking the "tick" on the left of the answer. :)
Comment: +1 on not responding with a RailsCast.  They are a good resource, but they should only be used as adding additional resources to the end of an answer, not the answer itself.
Answer: Yes, that will work, though you missed an end script tag on line two:
<%= form_for :order do |f| %>
   <% @fields.each do |field| %>
       <%= f.label field.name %>
       <%= f.text_field field.name %>
   <% end %>
   <%= f.submit %>
<% end %>

If you need something more complex than just a label/text field pair - then you can use a partial-template and use the collection keyword:

<%= form_for :order do |f| %>

   <%= render :partial => 'field', :collection => @fields, :locals => {:f => f} %>
   <%= f.submit %>
<% end %>

and

<%= f.label field.name %>
<%= f.text_field field.name %>

more on partial rendering here: http://api.rubyonrails.org/classes/ActionView/Partials.html
Comment: instead of using a locals could I use an object?

Rails loop through data in a form field


Linear convolution using fft for system output

Question: Here is a mass-spring-damper system with an impulse response, h and an arbitrary forcing function, f (cos(t) in this case). I am trying to use Matlab's FFT function in order to perform convolution in the frequency domain. I am expecting for the output (ifft(conv)) to be the solution to the mass-spring-damper system with the specified forcing, however my plot looks completely wrong! So, i must be implementing something wrong. Please help me find my errors in my code below! Thanks
clear
%system parameters
m=4;
k=256;
c=1;

wn=sqrt(k/m);
z=c/2/sqrt(m*k);
wd=wn*sqrt(1-z^2);
w=sqrt(4*k*m-c^2)/(2*m);

x0=0;   %initial conditions
v0=0;
%%%%%%%%%%%%%%%%%%%%%%%%%
t=0:.01:2*pi  ;%time vector

f=[cos(t),zeros(1,length(t)-1)];   %force f
F=fft(f);

h=[1/m/wd*exp(-z*wn*t).*sin(wd*t),zeros(1,length(t)-1)];  %impulse response
H=fft(h);

conv=H.*F;   %convolution is multiplication in freq domain

plot(0:.01:4*pi,ifft(conv))

To see what is expected run this code. Enter in cos(t); 4; 1; 256 for the inputs. You can see that it reaches a steady state at an amplitude much different than the plot generated from the above FFT code.
%%%FOR UNDERDAMPED SYSTEMS

func=input('enter function of t--->   ','s');
m=input('mass    ');
c=input('c    ');
k=input('k    ');

z=c/2/sqrt(k*m);
wn=sqrt(k/m);
wd=wn*sqrt(1-z^2);

dt=.001;
tMax=20;

x0=0;
v0=0;
t0=0;

t=0:dt:tMax;

X(:,1)=[x0;v0;t0];

functionForce=inline(func);

tic
for i=1:length(t)-1
    a=([0, 1, 0; -wn^2, -2*z*wn, 0; 0,0,0]*[X(1,i);X(2,i);X(3,i)]+[0;functionForce(X(3,i));0]);
    Xtemp=X(:,i)+[0;0;dt/2] + a*dt/2;
    b=([0, 1, 0; -wn^2, -2*z*wn, 0; 0,0,0]*[Xtemp(1);Xtemp(2);Xtemp(3)]+[0;functionForce(X(3,i));0]);
    Xtemp=Xtemp+[0;0;dt/2] + b*dt/2;
    c=([0, 1, 0; -wn^2, -2*z*wn, 0; 0,0,0]*[Xtemp(1);Xtemp(2);Xtemp(3)]+[0;functionForce(X(3,i));0]);
    Xtemp=Xtemp + [0;0;dt] +c*dt;
    d=([0, 1, 0; -wn^2, -2*z*wn, 0; 0,0,0]*[Xtemp(1);Xtemp(2);Xtemp(3)]+[0;functionForce(X(3,i));0]);
    X(:,i+1)=X(:,i)+(a+2*b+2*c+d)*dt/6+[0;0;dt];

end
toc
figure(1)
axis([0 tMax min(X(1,:)) max(X(1,:))])
plot(t,X(1,:))

Comment: What sort of plot do you expect? I get a small-amplitude/high-frequency sinusoid offset by high-amplitude/low-frequency sinusoid, which doesn't seem unreasonable for the forcing function you provided. But it's also been a while since I've studied vibrations.
Comment: Can you show us what you expect the output to look like?  I also ran the code too and I seem to be getting something sensible like eigenchris.
Comment: I just added a program that will show what is expected ( i am unable to post pictures). This is a numerical solution of the system. Notice that it is WWAAAAAAAYYY too slow. The slow speed is why i am trying to use FFT method instead. Also, I'm not sure whether or not to expect to see the initial transient solution in the FFT method because of the assumption of periodicity of the input. @eigenchris
Comment: @rayryeng run the code i added.
Answer: The initial transient will appear in the FFT method, so you will need to increase the time span (eg t=0:0.01:15*pi) to ensure the result includes the steady state. Incidentally since you truncate h after the same duration, increasing the time span also makes your impulse response h a better approximation to the actual infinite length impulse response.
So, updating your code to:
T=15*pi;
N=floor(T/.01);
t=[0:N-1]*0.01;  ;%time vector

...

plot([0:2*N-2]*0.01, real(ifft(conv)));
axis([0 T]); % only show the duration where the driving force is active

would correspondingly show the following response:

which shows the initial transient, and eventually the steady state. You may notice that the plot is similar to your alternate implementation up to a scaling factor.
This difference in scaling comes from two factors. The first one is simply due to the fact that the convolution in your FFT based implementation computes a sum which isn't weight by the time step (as compare with the dt scaling used in your second implementation). The second one comes from the fact that the second implementation does not account for the mass m for the effect of the driving force.
After accounting for those two factors, you should get the following responses:

where the blue curve represents the FFT based implementation (same as the above curve but scaled down by dt=0.01), and the red curve represents your alternate implementation (with the functionForce divided by m).
Comment: ah YES! Thank you for pointing out that mistake!! I was wondering why my  amplitude seemed larger than expected in both cases. One last question: How would i alter the code if i was ONLY interested in the steady state response and did not want to see the transient part? Would i need to get rid of the zero padding?
Comment: No, you need the zero padding (otherwise you'd get a circular convolution). If you want the steady-state part, get rid of the initial samples of the convolution results (e.g. `convresult = real(ifft(conv)); result = convresult(delay+1:end);`, to get rid of the first `delay` samples).
Comment: That makes sense; however, i was hoping there is a way to not have to calcualte which part of the signal to throw out, but rather have that taken care of through the FFT calculations. Maybe there can be an advantage to using circular convolution in order to ignore the transient part? If there is a force with a defined period (cos(t) ; 2*pi ), and only the steady state is of interest, wouldn't circular convolution be preferred over linear?
Comment: Main problem with that is that the impulse response is not periodic, so circular convolution would't make sense in that case. I'd look at the possibility to reformulate the equations with periodic boundary conditions to avoid using the impulse response.
Comment: Ok, your responses are much appreciated! I will work on that. If i run into trouble I may post in another question.


React Native auto height WebView doesn't work on android

Question: I'm implementing a WebView with dynamic height. I found the solution that works like a charm on iOS and doesn't work on android. The solution uses JS inside the WV to set the title to the value of the content height. Here's the code:
...
this.state = {webViewHeight: 0};
...
<WebView
    source={{html: this.wrapWevViewHtml(this.state.content)}}
    style={{width: Dimensions.get('window').width - 20, height: this.state.webViewHeight}}
    scrollEnabled={false}
    javaScriptEnabled={true}
    injectedJavaScript="window.location.hash = 1;document.title = document.height;"
    onNavigationStateChange={this.onWebViewNavigationStateChange.bind(this)}
/>
...
onWebViewNavigationStateChange(navState) {
    // navState.title == height on iOS and html content on android
    if (navState.title) {
        this.setState({
            webViewHeight: Number(navState.title)
        });
    }
}
...

But on android the value of the title inside onWebViewNavigationStateChange is equal to page content.
What am I doing wrong?
Answer: I was baffled by this too. It actually works but it's hard to debug why it does not work because Chrome remote debugging is not enabled for the React Native WebViews on Android.
I had two issues with this:

The script I injected to the Webview contained some single line comments and on Android all the line breaks are removed (another bug?). It caused syntax errors in the WebView.
On the first call the title content indeed is the full content of the Webview. No idea why but on latter calls it's the height. So just handle that case.

Here's the code I'm using now which on works on React Native 0.22 on Android and iOS
import React, {WebView, View, Text} from "react-native";

const BODY_TAG_PATTERN = /\<\/ *body\>/;

// Do not add any comments to this! It will break line breaks will removed for
// some weird reason.
var script = `
;(function() {
var wrapper = document.createElement("div");
wrapper.id = "height-wrapper";
while (document.body.firstChild) {
    wrapper.appendChild(document.body.firstChild);
}

document.body.appendChild(wrapper);

var i = 0;
function updateHeight() {
    document.title = wrapper.clientHeight;
    window.location.hash = ++i;
}
updateHeight();

window.addEventListener("load", function() {
    updateHeight();
    setTimeout(updateHeight, 1000);
});

window.addEventListener("resize", updateHeight);
}());
`;

const style = `

`;

const codeInject = (html) => html.replace(BODY_TAG_PATTERN, style + "");

/**
 * Wrapped Webview which automatically sets the height according to the
 * content. Scrolling is always disabled. Required when the Webview is embedded
 * into a ScrollView with other components.
 *
 * Inspired by this SO answer http://stackoverflow.com/a/33012545
 * */
var WebViewAutoHeight = React.createClass({

    propTypes: {
        source: React.PropTypes.object.isRequired,
        injectedJavaScript: React.PropTypes.string,
        minHeight: React.PropTypes.number,
        onNavigationStateChange: React.PropTypes.func,
        style: WebView.propTypes.style,
    },

    getDefaultProps() {
        return {minHeight: 100};
    },

    getInitialState() {
        return {
            realContentHeight: this.props.minHeight,
        };
    },

    handleNavigationChange(navState) {
        if (navState.title) {
            const realContentHeight = parseInt(navState.title, 10) || 0; // turn NaN to 0
            this.setState({realContentHeight});
        }
        if (typeof this.props.onNavigationStateChange === "function") {
            this.props.onNavigationStateChange(navState);
        }
    },

    render() {
        const {source, style, minHeight, ...otherProps} = this.props;
        const html = source.html;

        if (!html) {
            throw new Error("WebViewAutoHeight supports only source.html");
        }

        if (!BODY_TAG_PATTERN.test(html)) {
            throw new Error("Cannot find  from: " + html);
        }

        return (
            <View>
                <WebView
                    {...otherProps}
                    source={{html: codeInject(html)}}
                    scrollEnabled={false}
                    style={[style, {height: Math.max(this.state.realContentHeight, minHeight)}]}
                    javaScriptEnabled
                    onNavigationStateChange={this.handleNavigationChange}
                />
                {process.env.NODE_ENV !== "production" &&
                <Text>Web content height: {this.state.realContentHeight}</Text>}
            </View>
        );
    },

});

export default WebViewAutoHeight;

As gist https://gist.github.com/epeli/10c77c1710dd137a1335
Comment: Anyone struggling with that, if you need to know why your code is not working on Android, I used this comment:
https://github.com/facebook/react-native/issues/14586#issuecomment-314172889
Answer: Loading a local HTML file on the device and injecting JS was the only method I found to correctly set the title / hash in Android.
/app/src/main/assets/blank.html
<!doctype html>

<title id="title">Go Web!</title>
<meta name="viewport" content="width=device-width, initial-scale=1">

And the component
class ResizingWebView extends Component {
  constructor(props) {
    super(props)

    this.state = {
      height: 0
    }
  }
  onNavigationStateChange(navState) {
    var event = navState.url.split('#')[1]
    var data = navState.title

    console.log(event, data)
    if (event == 'resize') {
      this.setState({ height: data })
    }
  }
  render() {
    var scripts = "setContent('
Yay!
');fireEvent('resize', '300')";
    return (
      <WebView
        source={{ uri: 'file:///android_asset/blank.html' }}
        injectedJavaScript={ scripts }
        scalesPageToFit={ false }
        style={{ height: this.state.height }}
        onNavigationStateChange={ this.onNavigationStateChange.bind(this) }
      />
    )
  }
}


Solve: $|z|^2+2zi+2\overline{z}i+3=0$

Question:
$$|z|^2+2zi+2\overline{z}i+3=0$$

$$z\overline{z}+3+i(2z+2\overline{z})=0+0i$$
$$1)\text{  }2(z+\overline{z})=0\iff 2Re(z)=0\iff Re(z)=0$$
$$2)\text{  }z\overline{z}+3\text{  }=0$$
due to $Re(z)$ we get:
$$2) \text{  }yi\cdot(-yi)+3\text{  }=0$$
$$2) \text{  }y^2=-3\iff y_{1,2}=\pm \sqrt{3}i$$
So we have $$z_{1,2}=\pm \sqrt{3}$$
but if we plug it back to the equation we get:
$$3\pm 4 \sqrt{3}+3=0$$ Which is obviously incorrect
Comment: $y$ is a real number.
Answer: You correctly found that $\Re(z)=0$. The equation reduces then to $|z|^2+3=0$, which has no solutions.
Answer: If $f(z)=0$, then also $\overline{f(z)}=0$, so you have
\begin{gather}
|z|^2+2zi+2\bar{z}i+3=0\\
|z|^2-2\bar{z}i-2zi+3=0
\end{gather}
and summing them up you get
$$
2(|z|^2+3)=0
$$

Solve: $|z|^2+2zi+2\overline{z}i+3=0$


Finding distinct solutions for the equation

Question:
Consider the non negative integer solutions for the equation  $$ x_1 +
 x_2 + x_3 + x_4 + x_5 = 36. $$
(a) How many distinct solutions are there?
(b) How many distinct solutions are there if $x_1 \ge 12$ ?
(c) How many distinct solutions are there if $x_1 < 18$ ?
(d) How many distinct solutions are there if $x_1 < 18$ and $x_2 < 6$ ?

My working:
a) $\frac{5!}{1!} = 150 $
Not sure how to approach this question.
Answer: The first part is a classical Stars and Bars problem.
For the second part substitute $x_6 = x_1 + 12$ and apply the Stars and Bars reasoning for $x_2 + x_3 + x_4 + x_5 + x_6 = 24$
For the third part do same as for part two, but this time substitute $x_6 = x_1 + 18$ and then subtract the number you will get from the number of total solutions, which we obtained in part one.
The final part is similar to the part three, but now you will need a little help from the Inclusion-Exclusion Principle
Answer: So I would use the equation $\binom{n + k -1}{ k - 1}  =  \binom{ n + k -1}{n}$ for $n = 36, k = 5 $
Thus it would be: $\binom{40}{4}$
Comment: Aren't those meant to be binomial coefficients, not fractions?
Comment: @Jam: I suppose since it is a new member of the site, this member does not know about using MathJax for equations. Still, one could write (n+k-1)C(k-1) and 40C4 and so on.
Comment: @String Yeah that's what confused me. Even w/o MathJax, it'd be odd to write a binomial coefficient as n/k.
Answer: a) Using recursion:
Let $f(n+1, s)$ the number of non-negative integer solutions to
$$
x_1 + \dotsb + x_{n+1} = s \quad (*)
$$
then this is equivalent to the number of non-negative integer solutions to
$$
x_1 + \dotsb + x_n = s - x_{n+1}
$$
for $x_{n+1} \in \{ 0, \dotsc, s \}$, leading to
$$
f(n+1, s) = \sum_{i=0}^s f(n, i) \quad (**)
$$
We note $f(1, s) = 1$ from $(*)$. With this we could recursively evaluate $f$ via the first argument.
Further for the second argument we have
\begin{align}
f(n+1, s+1)
&= \sum_{i=0}^{s+1} f(n, i) \\
&= f(n, s+1) + \sum_{i=0}^{s} f(n, i) \\
&= f(n, s+1) + f(n+1, s)
\end{align}
and we note $f(n, 0) = 1$ from $(*)$.
So we got
<code>  4| 1
   |
  3| 1   4
   |
  2| 1   3   6
   |
  1| 1   2   3   4
   |
  0| 1   1   1   1   1
  s+------------------
   n 1   2   3   4   5
</code>
which is a variation of Pascal's triangle.
From the diagram we read
$$
f(n, s) = \binom{n-1+s}{s} \quad (***)
$$
and this gives the solution
$$
f(5, 36) = \binom{40}{36} = \frac{40!}{36! 4!} = \frac{40\cdot 39 \cdot 38 \cdot 37}{2\cdot 3\cdot 4} = 10 \cdot 13 \cdot 19 \cdot 37 = 91390
$$
b) We rewrite $(*)$ to
$$
x_2 + \dotsb + x_5 = 36 - x_1
$$
for $x_1 \in \{ 12, \dotsb, 36 \}$. So the number of solutions is
$$
\sum_{i=0}^{24} f(4, i) = f(5, 24) = \binom{28}{24} = 20475
$$
where we used $(**)$ and $(***)$.
c) Again we use
$$
x_2 + \dotsb + x_5 = 36 - x_1
$$
for $x_1 \in \{ 0, \dotsc, 17 \}$. Here the number of solutions is
$$
\sum_{i=19}^{36} f(4, i) = f(5, 36) - f(5, 18)
= \binom{40}{36} - \binom{22}{18} = 91390 - 7315 = 84075
$$
d) Now we rewrite to
$$
x_3 + \dotsb + x_5 = (36 - x_2) - x_1
$$
for $x_1 \in \{ 0, \dotsc, 17 \}$ and $x_2 \in \{ 0, \dotsc, 5 \}$. The number of solutions is
\begin{align}
\sum_{j=0}^5 \sum_{i=19-j}^{36-j} f(3, i)
&= \sum_{j=0}^5 f(4, 36-j) - f(4, 19-j) \\
&=
\left( \sum_{j=31}^{36} f(4, j) \right) -
\left( \sum_{j=14}^{19} f(4, j) \right)
\\
&=
(f(5, 36) - f(5,30)) -
(f(5, 19) - f(5,13))
\\
&=
\left( \binom{40}{36} - \binom{34}{30} \right) -
\left( \binom{23}{19} - \binom{17}{13} \right)
\\
&=
(91390 - 46376) -
(8855 - 2380) \\
&=38539
\end{align}


Drive Warning: /dev/hda3 (/usr) is 87% full

Question: As the title stated, I'm getting a drive warning via email from my server.  I was told to use the following command to determine where the disk space usage is coming from.  Is it possible for me to sort the results based on disk usage?  It returns a long list that is hard to sort through...
du -h --max-depth=2 /usr

Update:
What kind of data is stored here?
Answer: du --max-depth=2 /usr | sort -n | less

sorts the output and less allows to scroll up again
Comment: Also the `-b` option to du will give you bytes used.
Comment: Add the "-h" option to get human readable in MegaBytes
Comment: can `sort` handle the abbreviations?
Comment: No. If you're passing it into sort, then don't use -h. Use -b, -k or -m.
Comment: That just outputs blank lines...


A trough is 3 feet long and 1 foot high. The trough is full of water...

Question: A trough is 3 feet long and 1 foot high. The vertical cross-section of the trough parallel to an end is shaped like the graph of $x^2$ from -1 to 1 . The trough is full of water. Find the amount of work required to empty the trough by pumping the water over the top. Note: The weight of water is 62 pounds per cubic foot.
Comment: A trough in the shape of a parabolic prism?  Seems pretty far-fetched to me. I think your teacher is pulling your leg.
Comment: @MJD Calculus makes that not an issue.
Comment: I want to know what jerk-ass farmer is watering his livestock out of a parabolic trough. Everyone knows that cattle drink optimally from catenaries.
Answer: Consider a small amount of water in the trough at depth $h$ below the top edge. The water has a volume $dV$ and a mass of $\rho\;dV$ where $\rho$ is the density of water.  The small amount of work $dW$ to remove this small amount of water from the trough is $h\rho\; dV$. You need to calculate the total work, which is $$\iiint_{\text{trough}} dW$$
and this is equal to $$\iiint_{\text{trough}} h\rho \;dV.$$
$dV$, the volume of each small amount of water, is $dx\;dy\;dz$, and there is a simple relationship between $h$ and $z$.
Is this enough to get you started?
Comment: The $g$ is my mistake. I was thinking that the 62 pounds was pounds *mass*. But of course it isn't. I will correct. The triple integral just means you integrate over the three dimensions of the trough, but the two horizontal dimensions are trivial and just multiply by the horizontal measurements of the trough, leaving you with one interesting integral over the height, just as in your solution.
Comment: Look at my answer. This could be a way to do it, but in physics they teach you a different, easier way.
Comment: @mathguy It is exactly the same! Two of the three integrals in my expression turn out to be trivial multiplications.
Comment: oh is it? My bad. I just didn't know how to interpret the triple integrals yet and I wasn't sure how g would fit into this problem.
Answer: Basically, the hard part of this question would be finding the surface area of the trough at a certain depth of the water. So let's say the height of the water is $y$ from the bottom, while the depth of the water is $1-y$. Now at whatever height $y$ you are at, the length will always be $3$. The width, however varies between $0$ and $2$. Notice that the equation of the parabola is $y=x^2$. If you were to put a vertical axis in between the parabola, you would see that the width of the trough at that height is twice the distance from the vertical axis to either side of the parabola. The distance between the vertical axis to the parabola is $x=\sqrt{y}$, so the total width of the parabola at height $y$ is $2\sqrt{y}$. That means at height $y$, the top surface area is $2\sqrt{y}*3 = 6\sqrt{y}$.
Now all that is left is your integral. You need to do an integral from 0 to 1 of (the weight of water)(the depth of the water)(the area of the water at the given depth)(d-height of water) =
$\int_0^1 (62)(1-y)(6\sqrt{y})dy = 99.2$ foot-pounds.


Haproxy Falling over under high volume

Question: I am having some issues with HAProxy configuration. I have been playing around with it to try and make it more resilient to high server loads and Denial of Service. However, I felt it was working fine until suddenly I was victim of a (D)DoS attack - Haproxy was reporting the backend as down even though I could still access it fine via the direct port.
Could somebody please check my HAProxy config and see if there is somewhere I am messing up or why I would be experiencing this.. I just can't seem to understand why this is happening.
Thanks in advance (and after of course) .
global
<code>    # Global Max Connections
        maxconn                                 20000
        # Various Other Settings
        pidfile                                 /var/run/haproxy.pid
        stats socket                            /var/run/haproxy.stat mode 600 level admin
        stats timeout                           5m
        chroot                                  /usr/share/haproxy
        daemon
        # User Settings
        user                                    haproxy
        group                                   haproxy

defaults
        # Default configuration settings for Haproxy
        retries                                 2
        maxconn                                 19500
        timeout server                          10s
        timeout client                          10s
        timeout queue                           10s
        timeout connect                         10s
        timeout http-request                    10s
        # Error files
        errorfile 503 /etc/phpconf/haErrors/503.http

frontend Connection_Handler
        default_backend Primary
        bind :80
        mode                                    http
        option                                  forwardfor
        option                                  http-server-close
        maxconn                                 20000
        # Check if cookie exists
        #acl cookie_set hdr_sub(cookie) authorized=1
        # If cookie doesn't exist try and set it
        #redirect prefix * set-cookie authorized=1 if !cookie_set

        # If the cookie is still not set, send it to blocked backend
        #use_backend Cookie_Block if !cookie_set

        ## (D)DoS Mitigation ##
        # Setup stick table
        stick-table type ip size 1m expire 10m store gpc0
        # Configure the DoS src
        acl src_DoS src_get_gpc0(Connection_Handler) gt 0
        # Use DoS tarpit if src_DoS
        use_backend DoS_Tarpit if src_DoS
        # If not blocked, track the connection
        tcp-request connection track-sc1 src if ! src_DoS

listen Statistics_Engine
        mode http
        bind                                    XX.XXX.XX.XX:9012
        stats                                   enable
        stats uri                               /admin?stats=true

        stats auth                              admin:Password
        stats hide-version
        stats refresh 2s
        #stats scope # Add this option to provide stats for a singular backend

backend Primary
        # Option Configs
        option                                  httpclose
        option                                  redispatch
        option                                  abortonclose

        ## (D)DoS Mitigation ##
        # The following table is recording the IP, connection rate and bytes out rate
        stick-table type ip size 200k expire 10s store conn_rate(5s)

        # Track request and enforce rules
        tcp-request content track-sc2 src
        # Mark as abuse if exceeding connection rate
        acl conn_rate_abuse sc2_conn_rate gt 80
        # Mark as abuse if over X bytes
        acl data_rate_abuse sc2_bytes_out_rate gt 200000

        # Set ACL rule to enforce on frontend
        acl mark_as_DoS sc1_inc_gpc0 gt 0
        # Block connections marked as DoS
        tcp-request content reject if conn_rate_abuse mark_as_DoS
        #tcp-request content reject if data_rate_abuse mark_as_DoS

        # Configure Server
        mode http
        option forwardfor
        server Primary_HTTP 0.0.0.0:1080 check addr 127.0.0.1 port 80 inter 3000 rise 2 fall 3 maxconn 20000
        #fullconn 1024

backend Conn_Tarpit
        # Tarpit for connections
        mode http
        timeout tarpit 20s
        reqitarpit .
        errorfile 503 /etc/phpconf/haErrors/tarpit_503.txt

backend Cookie_Block
        # Block connections that will not take on a cookie
        mode http
        reqdeny .
        errorfile 503 /etc/phpconf/haErrors/503_cookie.txt

backend DoS_Tarpit

        # Tarpit for suspected attacks
        log 127.0.0.1 local1 info
        timeout tarpit 10s # Tarpit for 10 seconds
        errorfile 500 /etc/phpconf/haErrors/500_DoS.txt
        mode http
        reqitarpit .
</code>
Answer: I see nothing obviously wrong in your config, you seem to have already taken care of correctly tuning your settings (especially maxconn). Is conntrack loaded on this machine ? The connection table might be full, preventing checks and connections from establishing to the server.
Also, have you checked how many concurrent connections were sent to the server ? It's possible that the server is alternatively going up and down due to the load.
Check the kernel log messages for any unexpected error.
Comment: Hi Willy. Thanks for that, I appreciate the reply. Due to regular denial of service I have had to modify conntrack and the table from memory is just about 10k. The attack was interesting as it was not exactly large but was requesting a large file primarily to consume bandwidth I guess. Current connections and load were all fine, I was monitoring the attack as it went and realised haproxy was causing problems. I stopped haproxy and put Litespeed back on port 80 and the attack was handled fine - That is what I cant get my head around. Seems haproxy is falsely reporting it as down.

Haproxy Falling over under high volume


AttributeError in cython wrapper for python error

Question: I have created a C++ wrapper in cython for python.
The C++ class has the method name makeBooleanValue, but in python I want the equivalent method to be make_boolean_value.
But I am getting the error:

Traceback (most recent call last):
    File "saxon_example.py", line 7, in
      xdmAtomicval = proc.make_boolean_value(False)
  AttributeError: 'saxonc.PySaxonProcessor' object has no attribute 'make_boolean_value'

It seems like I cannot use a different naming convention in cython.
In the pxd file I have the following:

XdmAtomicValue * makeBooleanValue(bool b)

In the pyx file I have the following:

def make_boolean_value(self, b):
    cdef bool c_b = b
    cdef PyXdmAtomicValue val = PyXdmAtomicValue()
    val.derivedaptr = val.derivedptr = val.thisvptr = self.thisptr.makeBooleanValue(c_b)
    return val

But in my python example script:
print(dir(library))

I get make makeBooleanValue
Any ideas what I am missing please?
Answer: It looks like the changes in the pyx file are not being picked up when I run a python  script. But it is being picked up when I run python from commandline


Is it possible to make a entity reference field translatable and keep content in existing translations?

Question: In our current project we use entity reference fields widely. There is quite a lot of content that already has translations.
Now we would like to enable translations of some of these entity reference fields.
When I did so I noticed that only the original language version of the nodes keep the contents of the fields - the translations show up with an empty entity reference field.
Did I just stumble into yet another Drupal gotcha? I looked through Drupal 8's issue queue but could not find anything related.
Answer: Normally you don't need to make the entity reference field translatable to translate the content. This is only necessary if you want to define for each language different target ids.
But this is a different issue. If you enable translation for a field the translated fields have not yet content. This is not specific to reference fields, it is the same for all field types. Only when you create new translations the field values are copied, so that the form is prefilled with the untranslated values. So if you change the field structure in this way and you want to start with all existing translations prefilled you may need an update script for the existing field data.
Comment: Thank you for your answer. You are right: We left these reference fields as not translatable on purpose so that it would be easier for the editors to wrap their heads around the system.

And now we see that they need to vary content by language.

Would you have any update scripts available somewhere for such a change?
Comment: Go through each entity of the content type, load the translations and fill the empty field with the untranslated values.


Initializing char*

Question: When I do this:
main(){
   char* output[255];
   output[0] = '\0';
}

I get a segfault at output[0] = '\0'.
What am I doing wrong?
Comment: Wow, 6 answers and not a single person has pointed out that this should not segfault.
Comment: I'll pass... I've got my "Legendary" badge already. So my rep-whoring days are over. :)
Comment: @Mysticial Be the first one :-)
Comment: @Mysticial And the one with the most upvotes uses a different language than the question!
Comment: I've already pointed this out
Comment: @peper0 Either I didn't see it, or you edited it in after I made my first comment. But I'll +1 anyway.
Comment: I edited it by adding "Maybe you try to print it somewhere?", but no-segfault note was mentioned earlier
Answer: The problem is probably somewhere else, this part of code shouldn't segfault. Maybe you try to print it somewhere?
However I'm not sure whether it does what you want. You declared array of char pointers:
char* output[255];

And write char there:
output[0] = '\0';

You probably wanted to declare array of chars:
char output[255];

Answer: You have created a char** type, not a char* type.
The correct syntax is char output[255];
Answer: A better way of doing this is:
#include <stdlib.h>
main()
{
    char* output = malloc(255); // Allocates the pointer
    output[0] = '\0';
}

Sesh's answer is C++.
Answer: You want to declare an array of characters, not POINTER to characters. It should be:
main(){
       char output[255];
       output[0] = '\0';
    }

Answer: Your variable output is an array of pointers, not an array of char. Remove the asterisk.
Answer: I complied the program that u have posted but apart from warning I was not getting any segfault. its gcc 4.1.2
Answer: You are basically declaring an array of pointers (pointers to char). And '\0' is not a valid value for a pointer. If you intend to allocate 256 char memory then rewrite:
char* output = new char[256];

Comment: Why '\0' is not a valid value for pointer? It just evaluates to NULL which is valid (at least if not dereferenced).
Comment: -1, nothing in this answer is correct. new doesn't exist in C and '\0' is a valid value for a pointer in C (although writing a null pointer with '\0' is very obscure syntax).
Comment: How exactly do you use `new` in C? This question isn't about C++.

Initializing char*


Finding PMF from CDF results in a 0 constant

Question: I have a CDF $\  F(x)= \frac {x+1}{k} $ for $\ -1 \leq x \leq 1 $
Asked to find the pdf results in $\ f(x) =  \frac {1}{k} $
Then asked to find the value of the constant k leads me to re-integrate:
$\int_{-1}^{1}\frac {1}{k} \text{ d}x $
$\int_{0}^{1}\frac {x}{k} \text{ d}x + \int_{-1}^{0}\frac {x}{k} \text{ d}x $
$\ [ \frac{1}{k}  + 0] + [0 + \frac{-1}{k}] = 1$
Which results in k =0. Naturally I am suspicious.
Can anyone verify these steps?
Comment: Your (wrong) result does not imply  that $k=0$. Since the integral would be always 1, k could be everything except 0.
Answer: You computed the integral incorrectly.
$$\int_{-1}^1 \frac{1}{k} \mathop{dx} = \frac{1}{k} \int_{-1}^1  1\mathop{ dx} = \frac{2}{k},$$
so $k=2$.
You could actually get the value of $k$ directly from the CDF, from the property that $F(x) \to 1$ as $x \to \infty$. (In particular, you need $F(1)=1$.)


Matching and multiple imputation (Lalonde revisited) - Correct method for pooling

Question: I´m trying to get up to speed with multiple imputation and matching. I´ve been struggling with finding the correct method of pooling the matched imputed data. In the end I ended up doing a new analysis of the Lalonde data (see below- copy paste, takes approx 60sec to run).
As far as I understand there are two general approaches and detailed by Mitra et al (also see this thread). In the analysis below I did these approaches, but also one where I clustered according to each individual and I obtain the exact same results as the averaging by Mitra (although easier to implement). They seem to fit reasonably well with the original dataset (could probably be improved by increasing the imputations, growing longer trees and increasing depth). Now the big question is which method I should report?
<code>data("lalonde")
lalonde$age[sample(1:614, 50)] <- NA
library(cobalt)
library(mice)
library(tidyverse)
library(twang)
s <- mice(lalonde, m = 3)
s_long <- mice::complete(s, "long")
s_list <- s_long %>% group_by(.imp) %>% nest()
s_list$twang <- map(
  s_list$data,
  ~ ps(
    treat ~ age + educ + black + hispan + married + nodegree + re74 + re75,
    data = as.data.frame(.),
    n.trees = 500,
    interaction.depth = 1,
    shrinkage = 0.01,
    perm.test.iters = 0,
    stop.method = c("es.mean", "ks.max"),
    estimand = "ATT",
    verbose = TRUE
  )
)
s_list$w <-
  map(s_list$twang,
      ~ get.weights(
        ps1 = .,
        stop.method = "es.mean",
        estimand = "ATT"
      ))

s_list$design <- map2(s_list$data,
                      s_list$w,
                      ~ svydesign(
                        ids =  ~ 1,
                        weights =  ~ .y,
                        data = .x
                      ))

s_list$glm2 <- map(s_list$design,  ~
                     svyglm(re78 ~ treat, design = .x))
library(broom)
map_df(s_list$glm2,  ~ tidy(.), .id = "N")
library(mitools)
summary(MIcombine(s_list$glm2))  #According to Rubins rule

s_long_data <- unnest(s_list, ... = data, w)
glm_id_design <- svydesign(ids =  ~ .id,
                           weights =  ~ w,
                           data = s_long_data)

glm_id <- svyglm(re78 ~ treat,
                 design = glm_id_design)

##According to Mitra
ave_w <- s_long_data %>% group_by(.id) %>% summarise(w2 = mean(w))

s_mitra <- s_long_data %>% filter(.imp == 1) %>% left_join(ave_w)

glm_mitra_design <- svydesign(ids =  ~ 1,
                              weights =  ~ w2,
                              data = s_mitra)
glm_mitra <- svyglm(re78 ~ treat,
                    design = glm_mitra_design)

##### All
(glm_all <-
    list(
      mitra = tidy(glm_mitra),
      svy_cluster = tidy(glm_id),
      robin = summary(MIcombine(s_list$glm2))
    ))

##### Compared to
data(lalonde)

all_lalonde <- ps(
  treat ~ age + educ + black + hispan + married + nodegree + re74 + re75,
  data = lalonde,
  n.trees = 500,
  interaction.depth = 1,
  shrinkage = 0.01,
  perm.test.iters = 0,
  stop.method = c("es.mean", "ks.max"),
  estimand = "ATT",
  verbose = TRUE
)

all_svy <- svydesign(
  ids =  ~ 1,
  weights = get.weights(all_lalonde, "es.mean", estimand = "ATT"),
  data = lalonde
)

svy_all <- svyglm(re78 ~ treat,
                  design = all_svy)

(glm_all <- list(
  mitra = tidy(glm_mitra),
  svy_cluster = tidy(glm_id),
  robin = summary(MIcombine(s_list$glm2)),
  all_lalonde = tidy(svy_all)
))
</code>
Answer: The following is my opinion, so feel free to look elsewhere. I think it's really good that you tried several methods and got the same result with each; that shows that your result does not depend on your methods choices, which gives some evidence for a robust effect. I would recommend reporting the method that is the most intuitive, the best-justified, or the most familiar to readers in your field. I think it would be a huge strength to let readers know that using other methods yielded the same result; this can go into an Appendix at most or a footnote at least, but I think a sentence or two in your write-up would be sufficient.
This approach is sometimes used when it isn't clear whether to endorse an assumption, so you try methods that either require or don't require the assumption. If the results agree, you can report either method, but often the simpler method allows readers to arrive at their conclusion the most efficiently. For example, if you didn't want to assume homoscedasticity in ANOVA, you could use Welch's ANOVA, but if you got the same results with the regular uncorrected ANOVA, you might report that instead, and also let readers know that the results didn't differ if you were to use the corrected ANOVA.


Triangulo vazado com css

Question: Estou precisando fazer este tipo de efeito com css será que tem como ?

Não teria importância utilizar css3 nem nenhum tecnologia, este tipo de css será usado em um aplicativo feito em ionic, não sei se isto importaria algo.
Preciso a reprodução identica a este, contendo um ícone e um texto dentro.
Tentei utilizar border-radius e rotate porem ele rodou todo conteúdo da div.
.triangle {
  height: 50px;
  width: 50px;
  background-color: red;
  border-radius: 5px;
  transform: rotate(50deg);
}

<ion-row>
  <ion-col col-4>

      <ion-icon name="md-book" class=""></ion-icon>
     Algum texto

  </ion-col>
</ion-row>

Comment: Já cogitou aplicar `border-radius` e `transform: rotate()` em uma `div`?
Comment: não, como ficaria ?
Comment: Até tentei aqui porém ele virou o conteúdo da div juntamente.
Comment: Dá para fazer com `rotate:(-50deg)` no `span` e com posicionamento `absoluto` no `span` e relativo no `.triangle`. E para ficar inclinado no angulo certo seriam `45deg`
Comment: @Isac poderia cria uma resposta para dar o exemplo ?
Answer: Uma forma de fazer o que pretende é aplicar a rotação inversa no elemento filho (o ), e colocar o seu posicionamento como absoluto, e o do pai como relativo.
Segue exemplo:

.triangle {
  margin:50px;
  height: 60px;
  width: 60px;
  border-radius: 5px;
  border:2px solid orange;
  transform: rotate(45deg); /*45 para ter a inclinação certa*/
  position:relative; /*<---*/
}

.triangle span {
  position:absolute; /*<---*/
  transform: rotate(-45deg); /*<---*/
}
<ion-row>
  <ion-col col-4>

      <ion-icon name="md-book" class=""></ion-icon>
      Algum texto

  </ion-col>
</ion-row>

Alterei ligeiramente outros estilos para ser mais fácil de ver e ficar também mais perto da figura que tem na pergunta.
Answer: Uma solução é criar um pseudo-elemento e fazer a rotação nele, assim o elemento em sí não irá girar também:

html, body{ background: #000; color: #fff; }

.triangle {
    position: relative;
    margin-top: 25px;
    margin-left: 25px;
    display: flex;
    width: 80px;
    height: 80px;
    justify-content:center;
    text-align:center;
    flex-direction:column;
}
.triangle::before{
    display:block;
    content: "";
    width:80px;
    height:80px;
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    border: 2px solid orange;
    border-radius: 10px; /* altere este valor para controlar a curvatura das pontas */
    -webkit-transform: rotate(45deg);
    -webkit-transition: border-color 0.3s;
}
<ion-row>
  <ion-col col-4>

      <ion-icon name="md-book" class=""></ion-icon>
         Algum texto

  </ion-col>
</ion-row>

Triangulo vazado com css


Should $\to$-elimination always have precedence over $\lnot$-elimination when transforming formulas to Prenex CNF?

Question: I'm currently learning the resolution method of proof and before it can be applied we need to transform a FOL formula into prenex, then skolemise it, then transform it to CNF, correct? I encountered a doubt when converting the following formula to CFN:
1) $\forall x \forall y ((H(x,y) \land C(y)) \to \lnot\exists z(H(x,z)\land Mouse(z)))$
Now, if I use $\to$-elimination before $\lnot$-elimination, I'll get the following transformation:
2) $\forall x \forall y (\lnot(H(x,y) \land C(y)) \lor \lnot\lnot\exists z(H(x,z)\land Mouse(z)))$
forcing me to convert $\lnot \lnot \exists z$ to $\exists z$
and get the following formula after $\lnot$-elimination:
3) $\forall x \forall y ((\lnot H(x,y) \lor \lnot C(y)) \lor \exists z(\lnot H(x,z)\lor \lnot Mouse(z)))$
And, after moving quantifiers to the front:
4) $\forall x \forall y \exists z ((\lnot H(x,y) \lor \lnot C(y)) \lor \lnot H(x,z)\lor \lnot Mouse(z)))$
Which will inevitably force me to skolemize the existential quantifier and finally arrive at:
5) $\forall x \forall y ((\lnot H(x,y) \lor \lnot C(y)) \lor \lnot H(x,f(x,y)))\lor \lnot Mouse(f(x,y))))$
Now, this is where my doubt comes into play. Had I used $\lnot$-elimination before $\to$-elimination -between 1) and 2)-, I'd have arrived at:
2*) $\forall x \forall y (\lnot(H(x,y) \land C(y)) \lor \forall z \lnot(H(x,z)\land Mouse(z)))$
By doing so, I wouldn't have to skolemize the existential quantifier away and would not have a skolem-function in my result. My question is: can I save myself the hassle of skolemising the existential quantifier in this way or will I run into trouble later on?
Thank you for your time.
Comment: Why the second $\lnot$ in $¬¬∃z$ ? Check again step 2.
Comment: Step 2) must be : $∀x∀y(¬(H(x,y)∧C(y))∨¬∃z(H(x,z)∧Mouse(z)))$.
Comment: Oh, now I feel dumb. Indeed there's no reason for that second negative. I guess that was such an obvious mistake that I overlooked it by assuming it was correct. Thank you for pointing it out.
Answer:
1) $\forall x \forall y ((H(x,y) \land C(y)) \to \lnot\exists z(H(x,z)\land Mouse(z)))$
Now, if I use $\to$-elimination before $\lnot$-elimination, I'll get the following transformation:
2) $\forall x \forall y (\lnot(H(x,y) \land C(y)) \lor \lnot\lnot\exists z(H(x,z)\land Mouse(z)))$

No, you don't. You get:
$\forall x \forall y (\lnot(H(x,y) \land C(y)) \lor \lnot\exists z(H(x,z)\land Mouse(z)))$
and thus:
$\forall x \forall y (\lnot(H(x,y) \land C(y)) \lor \forall z \neg (H(x,z)\land Mouse(z)))$
and thus you don't get an existential to skolemise that way either.
In general, when you put a statement in prenex, the nature of the quantifiers will be forced. That is, you will not be able to get a different quantifier depending on the order in which you perform the steps. So, the fact that you got $\forall x \forall y \exists z ...$ one way,  but $\forall x \forall y \forall z ...$ thew other way, immediately means that something went wrong.
However, what can happen, is that the order of the quantifiers can change. That is, doing steps in one order, you may get $\forall x \exists y...$, and doing it a different way, you might get $\exists y \forall x...$, and in that case doing it the second way avoids you having to introduce a function when skolemising.


ANDs within OrConditionGroups

Question: I'm trying to use entityQuery in Drupal 8 to perform an "and" within an "or" group. A simplified version of what I'm trying to do is this: Query for all apples, oranges and bananas that are ripe. The code I'd like to be able to use would look like this code.
$oQuery = \Drupal::entityQuery('node');
$oOrGroup = $oQuery->orConditionGroup();
$oOrGroup->condition('type',['apple','orange'],'IN');
$oAndGroup = $oOrGroup->andConditionGroup();
$aAndGroup->condition('type','banana')
  ->condition('field_ripe',1);
$oOrGroup->condition($oAndGroup);
$oQuery->condition($oOrGroup);

This doesn't work because andConditionGroup() isn't a method of ConditionInterface.
Is there a way to do this with \Drupal::entityQuery(), or do I have to revert to using db_query()?
Comment: I see that the interface does expose this method, but when I use the above code, I get Fatal error: Call to undefined method Drupal\Core\Entity\Query\Sql\Condition::andConditionGroup() It looks like andConditionGroup() is not a method of the Drupal\Core\Entity\Query\Sql\Condition class, but it is of the \Drupal\Core\Database\Query\Condition class. So I think I'm confused about how to properly create an entityQuery in the first place perhaps.
Comment: Actually, there is a [`ConditionInterface::andConditionGroup()`](https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Database%21Query%21ConditionInterface.php/function/ConditionInterface%3A%3AandConditionGroup/8.2.x) method. Why do you think  `ConditionInterface` doesn't expose such method?
Answer: What you need to do is create both groups from the query, using the condition() method to plug the groups into the right places. Casting the query to a string will allow you to inspect the generated SQL to verify that it is what you would have created by hand (perhaps without some of the superfluous but harmless parentheses).
$storage = \Drupal::entityTypeManager()->getStorage('node');
$query = $storage->getQuery();
$bananas = $query->andConditionGroup()
  ->condition('type', 'banana')
  ->condition('field_ripe', 1);
$fruit = $query->orConditionGroup()
  ->condition('type', ['apple', 'orange'], 'IN')
  ->condition($bananas);
$query->condition($fruit);
echo (string) $query . "\n";

I've reformatted the output to make it a bit more legible, but otherwise it's exactly as the API created it.
   SELECT "base_table"."vid" AS "vid", "base_table"."nid" AS "nid"
     FROM "node" "base_table"
LEFT JOIN "node_field_data" "node_field_data"
       ON "node_field_data"."nid" = "base_table"."nid"
LEFT JOIN "node_field_data" "node_field_data_2"
       ON "node_field_data_2"."nid" = "base_table"."nid"
LEFT JOIN "node__field_ripe" "node__field_ripe"
       ON "node__field_ripe"."entity_id" = "base_table"."nid"
    WHERE (
            "node_field_data"."type" IN ('apple', 'orange')
          )
       OR (
            ("node_field_data_2"."type" = 'banana')
            AND
            ("node__field_ripe"."field_ripe_value" = '1')
          )

ANDs within OrConditionGroups


jQuery UI Accordion: start page without a selected section

Question: I have an Accordion style of navigation section on a website at work and I'm trying to figure out if there is a way to set it up so that there isn't a selected section when the page loads...basically you see all the headings but none of the content.
Also not sure that it's relevant, but the site is built on MVC3 using C#
Code...

        Employee Stock Ownership Plan Announcement

        @Html.Partial("_Esop")

        TAG Transport Purchase

        @Html.Partial("_TagPurchase")

        Wilcox Truck Line Purchase

        @Html.Partial("_WilcoxPurchase")

        JRI, Inc. Mentorship

        @Html.Partial("_JRIMentor")

Corrected code based on selected answer...

This did two things.

Made it so that when the page loaded there was no active content.
Removed the scroll bar from the panels
Answer:  $(".selector").accordion({ active: false });

Comment: The issue you describe in your comments can result from different things. This page provides a number of solutions: http://helpdesk.objects.com.au/javascript/how-to-avoid-scrollbars-when-using-jquery-accordion
Comment: Thanks this worked great.  A 'bug' that popped up with this now is that some of the windows have scroll bars when they didn't before.  Any thoughts on this?  The scroll bars aren't the end of the world, but I'd prefer not to have them.
Answer: $( "#accordion" ).accordion({ active : 'none' });

jsFiddle
Answer: Setting the collapsible option to true is part of the solution, you also need to set the active option to false


One vs. many domain user accounts in a server farm

Question: We are in a migration process of a group of related computers (Intranet servers, SQL, application servers of one application) to a new domain. In the past we used one domain user account for every computer (web1, web2, appserver1, appserver2, sql1, sqlbackup ...) to access central Windows resources like network shares. Every computer also has a local user account with the same name.
I am not sure if this is necessary, or if it would be easier to configure and maintain to use one domain user account.
Are there key advantages / disadvantages of having one single user account vs. dedicated accounts per computer for this group of background servers? If I am not wrong, one advantage besides easier administration of the user account could be that moving installed applications and services around between the computers does not require a check of the access rights anymore. (Except where IP addresses or ports are used)
Answer: I might be misreading what you're asking here, but if you have one domain, then your domain administrator account will have admin rights on all of the attached systems.
The only advantage to creating multiple, separate accounts is for partitioning of responsibilities and control. One separate admin account for each server might make sense if each server had its own administrator and you wanted to ensure they didn't overstep their responsibilities.
As for local users, it's wise to maintain separate accounts on each member server that you can use should your domain spontaneously explode, but I wouldn't say there's any need to use them for day-to-day administration.


iOS size of auto layout view

Question: Lets say if I have a parent UIView in which the sub views have dynamic height.
How can I get the size of the parent view (which has the same height as the sum of all sub views' height).
p.s. All the views are created by AUTO LAYOUT
or actually I have to add up the heights myself? I wonder if there is a simpler way to find the parent view's height
Answer: If view is your UIView, you can get the height of the parent view (also called superview) with
view.superview.frame.size.height

Comment: That depends on where you call it - it should work in viewWillAppear because then the views are laid out already.
Comment: oh... I dont even know frame is workable in auto layout... but what if I am not in a ViewController where I dont have viewDidAppear / viewWillAppear ? eg in UICollectionReusableView
Comment: maybe I should ask in this way: I want to get the height of the view and do something afterwards. When do I know the view is laid out? Where should I add my code?
Comment: The view is laid out during the call to [UIViewController layoutSubviews]. You can override this method (make sure to call [super]) and adjust the views afterwards.
Answer: self.parentView.superview.frame.size.height
Comment: @dondonhk You can call this in viewWillAppear(), how Glorfindel said, because at this moment all views know their sizes
Comment: It is not valid to say "auto layout views" or "views are created by AUTO LAYOUT".  Actually views use auto layout to layout their subviews, and I think this answer will work.

iOS size of auto layout view


Fairly simple problem: three integers, sums, and Pythagorean triples

Question: So, I randomly thought about this simple problem, and very sadly couldn't make much progress in answering this.

Does there exist three integers $a,b,c\neq0$ where $a^2+b^2$, $a^2+c^2$, and $b^2+c^2$ are all perfect squares?

Here's what I've worked out:

Let $a^2+b^2=C^2$,
$a^2+c^2=B^2$,
$b^2+c^2=A^2$.

For the smallest $a,b,c$ triplet that exists, exactly one of them must be odd.

It wouldn't be the smallest triplet if they're all even, and...
...there doesn't exist a Pythagorean triple $x^2+y^2=z^2$ where both $x$ and $y$ are odd (so $a,b,c$ can't have more than one odd number).

I've also found that $2(a^2+b^2+c^2)=A^2+B^2+C^2$, but this makes sense even when one of $a,b,c$ is odd.

I've even tried brute-forcing this with some code, but to no avail. So, I'm guessing there's no such $a,b,c$, but I haven't figured out how to prove that

So, it does seem that answering this would imply whether $a,b,c$ exists:

Can $b^2+c^2$ be a perfect square if $a^2+b^2$ and $a^2+c^2$ are?

...which I haven't figured out either.

Maybe some smart people have already thought about this many years ago – if so, I'd be happy to see their work! (Though, I've searched this up and found nothing.)
Also, feel free to add/fix the tags (I only added two here). Thanks in advance!
Comment: This has been discussed already at [art of problem solving](https://artofproblemsolving.com/community/c6h1964035p13594463). They have the name [Euler bricks](https://math.stackexchange.com/questions/1571383/are-euler-bricks-a-recursively-enumerable-set?noredirect=1).
Comment: I typed the three equations. But you are right, it took me while until "Euler bricks" came up. Anyway, I found it, so I hope  it is helpful for you.
Comment: Bruteforce from 1 to 250 is enough to say yes.
Comment: @DietrichBurde nice find! Also, I did search this up in the web (including here) and scroll down for quite a bit. Did you just search a related keyword (like Euler bricks) because you know it exists, or did you describe my problem (which is what I did)?
Comment: @IvanKaznacheyeu you're right. The IDE I used earlier stops executing after passing the time limit **(and doesn't show anything!)** so this made me realize that
Answer: Such a system of Diophantine equations arises from so-called
Euler bricks, which are well known. The smallest solution is given by
\begin{align*}
44^2+ 117^2 & = 125^2,\\
44^2+ 240^2 & = 244^2,\\
117^2+240^2 & = 267^2.
\end{align*}


How can I call an async method from an MVC4 control (an .ascx file)?

Question: My MVC4 application was re-factored to introduce some asynchronous code. However, there are several .ascx and .aspx files that are invocation asynchronous methods. For example,
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<SomeModel>" %>

    <%
        var authorizationContext = this.AuthorizationContext();
        if (await authorizationContext.ConfigurationAuthorization.CanUserUpdateConfig())
        {
     %>

The user can update configuration

      <% }
         else
         {
       %>

The user can NOT update configuration

       <%
         }
       %>

Not surprisingly I am getting an error saying that await can only be used inside of a method marked with 'async'. I really do not want to block the async call by using GetAwaiter().GetResult() or .Result or those other hacks. I have been reading a lot about best practices for async programming and the following two resources strongly suggest to never block an async call.
How to call asynchronous method from synchronous method in C#?
https://blog.stephencleary.com/2012/07/dont-block-on-async-code.html
How can I call the async method from my .ascx file?
Answer: Async is possible in ASP.NET Web Forms 4.5.
First, move your code to *.aspx(ascx).cs backend.
Second, register your async method like this:
public bool UserCanUpdate = false;

protected void Page_Load(object sender, EventArgs e)
{
    RegisterAsyncTask(new PageAsyncTask(UserCanUpdateAsync));
}

private async Task UserCanUpdateAsync()
{
    var authorizationContext = this.AuthorizationContext();
    UserCanUpdate = await authorizationContext.ConfigurationAuthorization.CanUserUpdateConfig();
}

Third, add Control attribute to your Page (Control) directive
<%@ Control Async="true" Language="C#" Inherits="System.Web.Mvc.ViewUserControl<SomeModel>" %>

Answer: The solution I went with was to not make any async calls in the .aspx or .ascx files. Instead load the data from the async method invocation into ViewData in the asynchronous controllers and you bypass the problem all together.


Const Variable in "Type"-Statement vba

Question: I want to sum up my Const Variables in a VBA Makro like this:
Private Type Company
   Public Const CompanyNameColumns As String = "14"
   Public Const CompanyNameStartRow As Integer = 5
Type End

I can't run this code.
I think the problem is, that there is no possibility of defining a Const within a Type Statement.
Has anybody a workaround for that?
Comment: Well.... I can definitely say that [the documentation for user defined types](http://msdn.microsoft.com/en-us/library/office/gg278633(v=office.15).aspx) is incredibly unhelpful....
Answer: So, it took me a second, but then it smacked me like a ton of bricks what's going on here.
TL;DR: You can't assign values during definition of a type, but there is a proper way to do what you're trying to do.
The reason you can't assign to it is because you're defining a type. I know that sounds cyclical and redundant, but that's exactly what is going on. You're trying to assign values in a place that is meant to define a data structure. That's all a UDT does. It defines a structure. It makes no sense to assign values to a structure.
As you've found, one solution is to create a new module and store your constants there.
Constants.bas
Public Const CompanyNameColumns As String = "14"
Public Const CompanyNameStartRow As Integer = 5

Which then gets called like this...
Constants.CompanyNameColumns
Constants.StartNameRow

And this is fine, but runs the risk of becoming a catch all. It would be much better to move these into a class module along with the logic they relate to. That way all of the related logic and data are in one place instead of scattered about multiple *.bas files in your project.
If you're going the class route, but the classes only hold this data structure, without any real state, you might want to consider making them global default instances. This is similar to what is known as "static" classes in other languages.
Comment: I needed two Constant "Structures" and now I just moved them into 2 Class Modules (to be honest I didn't know the difference between a Module and a Class Module because I normally code in vb.net)

Thank you for explaining why the hole thing didn't work
Comment: Oh. I'll make sure to let vba4all know that. But there are instructions for implementation in the CR link I posted.
Comment: @greece57 you can think of a VBA *Standard Module* (.bas) as a VB.NET *Shared Class*, if it's any help.
Comment: I added some extra information. You're very welcome.
Comment: I'm afraid, that the link to the implementation of static classes in VBA in the Post you linked doesn't work :/
Comment: It absolutely does work @greece57. I do it all the time for various reasons. If you're having trouble with it, I suggest creating a new question on that topic.
Comment: I mean [this link](http://vba4all.wordpress.com/category/vba-macros/making-vba-classes-static-and-calling-members-without-initialization/) @RubberDuck:
Answer: I worked around this Problem now by just defining a new Module. Named it Company and put the Consts in there!
Comment: I mostly code vb.net Code and when I tried to define a class it wasn't possible. Now i know why :D
Didn't know that you can add Class Moduls. Thanks!
Comment: Meehow, here's another one... please delete this comment as it's linking through to pharma scam.  Save the URL though and you can grab the legit copy in the Wayback Machine.  For now, readers are advised to avoid clicking.

Const Variable in "Type"-Statement vba


What hook should I use to attach a script to a content type?

Question: I have this function from a standalone php script that redirects the user based off the user agent. In the process of merging this into Drupal and the script only needs to execute for a specific content type. Not 100% sure what is the best hook to use: hook_node_presave(), hook_load() or hook_node_view()?
Or should I run this as a template pre-process since this script requires the JS window.location embed?
Part of the code attached:
$web_user_agent = $_SERVER['HTTP_USER_AGENT'];
$current_page = $_SERVER['REQUEST_URI'];

if (!$web_user_agent = '[User Agent Placeholder]') {

    die;

} else {

    echo('');
    die;
}

Comment: Why would you add a script from the backend to unconditionally redirect via javascript? Why would you not redirect from the backend?
Comment: What the client wants is okay - its the code needs adjusting.
Answer: It depends on how you want to approach it. Clive's question is still relevant, Javascript redirects are neither great or optimal. However, if it must redirect based on a User Agent, Javascript might be the only option.
I would advise you to do the agent detection on the client side, as the server value may not always be accurate. Your code above won't work.
To load a script based on content type, you can do:
function mytheme_preprocess_node(&$variables) {
  if ($variables['node']->type == 'mytype') {
    $variables['#attached']['js'][] = array(args);

    // or

    drupal_add_js('path/to/script.js');
  }
}

Your script itself also needs to be in a closure:
/**
 * @file
 */
(function () {

  "use strict";

  // All the JavaScript for this file.

})();

If jQuery or the Drupal scope is needed:
/**
 * @file
 */
(function ($, Drupal) {

  "use strict";

  // All the JavaScript for this file.

})(jQuery, Drupal);

See the docs page for more:

https://www.drupal.org/docs/7/api/javascript-api/managing-javascript-in-drupal-7
https://www.drupal.org/docs/develop/standards/javascript/javascript-coding-standards
Comment: The moment you turn on any sort of caching that code in the OP is not going to work for UA detection. Plus it has an error in it, the if condition will always be TRUE because you are setting the variable instead of comparing it.


How can I control substring length by ending it with a specific character?

Question: I have a string, "s", which I would like to obtain a substring of by starting a the begging (position 0), and end at a space- so that if someone were to, for instance, enter their full name, I could determine their first name.
I could have sworn their was a substring function that could 'search' until a certain character was found.  Thanks in advance!
Comment: Depending what's in there, you might just find it easier to put it in a stringstream and extract from that like you would with input.
Answer: Something like this would work:
<code>#include <string>
#include <iostream>

int main() {
    std::string str = "Person Name";
    size_t pos = str.find(" ");
    std::cout << str.substr(0,pos);
}
</code>
Comment: The nice thing is that you don't have to check against `npos` in this case, as that's what `substr`'s second parameter defaults to.
Comment: @chris yeah, I made the assumption that there is indeed a space between the names at all times.
Comment: But even if there isn't, it will print the whole string :)
Comment: Cool, thanks! Now, what if I wanted to start at a specific character then go to another specific character?
Comment: @Douko Do you mean looping through a string?
Comment: I don't think so- I mean say I want to capture a substring in the string '"I love you, and me- but mostly me."' I want to be able to designate a substring from say, the comma to the dash.
Comment: @Douko there are a couple ways of doing that, but `std::string::substr` doesn't accept indexes as its second parameter -- rather the second parameter is the count so it'd be a bit trickier.


Sensitivity of revenue to price

Question: This is a rather simple problem, but i can't for the life of me figure out the logic behind it.
The revenue $R $ from a software product depends on the price $p$ charged by the distributor according to the formula.
$$R = 4000p-10p^2$$
How sensitive is $R$ to $p$ when p is a) $100 $, b)$200$ c)$300 $?
Which begs for the differentiation: $\frac {dR}{dp}=4000-20p$
Now, finding the rate of change is easy. The rate of change is $2000$, $0$, $-2000$ for the respective values $100$, $200$, $300$.
If we were to maximize the revenue we would go for the $200$ option, because it is an absolute maximum value in the function $R = 4000p-10p^2$.
But practically, doesn't it mean that the revenue is $0$ dollars per dollar charged. And that a price at $200$ dollars would give us the revenue of $2000$ dollars per dollar charged?
Comment: Note:  I reformatted your post.  The version of Latex used by this site uses "$\$'s $" to indicate code intended for compiling, not as dollar signs.  You can insert dollar signs, as I did in this comment, but it's usually more trouble than it is worth.
Comment: That said, I don't understand your question.  The maximum revenue comes when the derivative vanishes (as there is clearly a global max and no global min).  Thus  at $p=200$, as you point out. But at $p=200$ we have $R(200)=4000\times 200 -10\times 200^2=400,000$  Where is the confusion?
Comment: The concept of rate of change is what set me up for confusion. I suppose it is synonymous with the slope at a given point. The slope at p = 100 is 2000. Doesn't this mean that for every dollar charged at this point, the income is 2000 dollars? Where as for p=200, where the slope is 0, there is 0 income for every dollar spent. Now I get that the maximum revenue is when the function reaches its peak. But how would we go about finding maximum revenue if there was no absolute maximum value at dR/dp=0? What if it would have been an inflection point?
Comment: Well, it's certainly true that this case is much simpler than the general case.  Calculus isn't even needed...just complete the squares to write $R(p)=-10(p-200)^2+400000$ to make the global max visible.  In general one does need to look at a second derivative, or nearby values, to test critical points.  Not necessary here.
Answer: Plot the revenue curve and see how revenue changes at random $dp$ intervals on the price axis. At the maxima it barely changes with small price shifts, right? Since growth rate of parabola is very small at the start. Now check some remote intervals

Sensitivity of revenue to price


Widget para introduzir data e hora

Question: Estou a utilizar o jQuery e o jQuery UI no front-end da minha aplicação web. Com o jQuery UI posso utilizar o widget datepicker (que só dá para introduzir data, segundo me parece...), e tenho-o utilizado noutras aplicações e até nesta.
No entanto, eu para uma nova função da minha app precisava de incluir um campo que desse para introduzir data e hora. Existe algum widget nestas livrarias para introduzir a data e a hora? É preciso uma nova livraria?
EDIT:
Estou a utilizar versões recentes do jQuery e do jQuery UI...
Comment: No site tem vários exemplos: https://pt.stackoverflow.com/questions/99138/jquery-mascara-formulario outra https://pt.stackoverflow.com/questions/128295/mascara-moeda-jquery outra https://pt.stackoverflow.com/questions/168967/problema-com-mascara-em-jquery
Comment: um input do tipo date? ou se quer mascara? pergunta fala esclarecimentos?
Comment: Sim um input tipo date. Seria do tipo "datetime",...
Comment: então já tem?...
Comment: `$("#datepicker").datepicker()` só dá para data! Vi https://api.jqueryui.com/category/widgets/ e não tinha qualquer coisa como datetimepicker... Se tem uma solução mostrava-me o código ou o link?
Comment: Por exemplo o `HTML` tem o `` que dá para isso. No entanto o aspecto, e mesmo a funcionalidade não é o mesmo de browser para browser. Por exemplo, no Firefox 81 a implementação não me parece aceitável... O que queria era uma livraria para isto, de modo a ser uniforme de browser para browser. Os utilizadores da minha app podem ter browsers antigos...
Comment: Mais: o `HTML` `` está a tornar-se obsoleto... Ver https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/datetime por exemplo
Comment: Você quer um exemplo input com máscara?
Comment: Parece-me que esse exemplo é introduzir a data como texto... O que eu queria era uma coisa mais user-friendly... que o utilizador gostasse... Mas se só tem esse, força...
Answer: Acabei por utilizar o jquery e o jQuery UI.
Assim criei controles no código HTML como o seguinte:
<input class="font-md" type="text" id="datepicker" name="ausData" value="" autocomplete="off" />

<input class="font-md" type="time" id="timepicker" name="ausDataT" value="" autocomplete="off" />

e incluí o seguinte script na página:
$(document).ready(function () {
    $("input#datepicker").datepicker();
});

O input#datepicker é um input que permite escolher a data num calendário, depois de activado com o script acima. O input#timepicker permite inserir a hora e a sua interface depende do browser onde está a ser utilizado. Por exemplo, no Firefox insere-se texto conforme uma certa máscara; no Edge abre-se um menu que permite escolher a hora.
Incluí o jQuery e jQuery UI com as seguintes tags:

    ...
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" integrity="sha256-rByPlHULObEjJ6XQxW/flG2r+22R5dKiAoef+aXWfik=" crossorigin="anonymous" />

...

Widget para introduzir data e hora


Under what conditions are HRs and RR consistent estimators of the same quantity?

Question: Assuming we have data for two groups from a time-to-event analysis with no censoring, there are two modeling approaches to comparing the group association with the risk of the event. Option one is a Cox proportional hazards model where a linear model is estimated having:
$$ \log \lambda (X|Z)= \log \lambda(X|Z=0) + \beta X$$
that is estimated by maximizing the partial likelihood
$$ \mathcal{L}(\beta; X, t) = \prod_{j=1}^K \frac{\lambda(X_j|Z_j)}{\sum_{\mathcal{l} \in\mathcal{R}_j\lambda(X_j|Z_\mathcal{l}) }} $$
More detail found here.
Alternately, one can consider the Poisson likelihood for an event and a log-linear model for a constant-in-time hazard function and an offset to designate the observation time, $t$ and each failure having the Poisson count variable equal to 1.
$$\log \lambda (X) = \alpha + \beta X - \log(t)$$
and $$ \mathcal{L}(\alpha, \beta, X) = \prod_{i=1}^n \lambda(X_i) \exp(-\lambda(X_i))$$
The question I have is under what conditions of the hazard function, or sample, is the $\beta$ that maximizes the Cox partial likelihood equal (or asymptotically equivalent to) to the $\beta$ that maximizes the Poisson likelihood? How do we prove this?
Answer: I'm not sure that there's a simple answer outside of the trivial case of a constant hazard.
As $\lambda$ is often used for the hazard function in a survival model, let's use $\mu_i = t_i\exp(\alpha)\exp(\beta X_i)$ to represent the Poisson mean for case $i$.  The log-likelihood for the Poisson model (with all outcome values identically 1) is then:
$$\sum_i \log \mu_i - \mu_i=\sum_i \alpha + \beta X_i  - t_i\exp(\alpha)\exp(\beta X_i)+ \log t_i.$$
The $\log t_i$ terms become 0 when differentiating with respect to the parameters to get the score function.
McCullagh and Nelder in Chapter 13 write the log-likelihood for a proportional hazards (PH) model with a specified baseline hazard in a way that parallels a Poisson model. With baseline hazard $h_0(t)$ and cumulative baseline hazard $H_0(t)$, then for case $i$ the cumulative hazard at its event time $t_i$ under PH is $\mu_i=H_0(t_i)\exp(\beta X_i)$. The log-likelihood without censored cases is:
$$ \sum_i \log \mu_i - \mu_i + \log \frac{h_0(t_i)}{H_0(t_i)}= \sum_i \log h_0(t_i) + \beta X_i - H_0(t_i)\exp(\beta X_i) . $$
For $h_0(t) = \exp(\alpha)$, this gives the same score function as the Poisson log-likelihood, as expected for an exponential survival model. The Cox partial likelihood approach can match the Poisson full-likelihood results for exponentially distributed data (Weibull with shape of 1) reasonably well.
> set.seed(101)
> expDF <- data.frame(time=c(rweibull(100,shape=1,scale=1),rweibull(100,shape=1,scale=2)),status=1,x=c(rep(0,100),rep(1,100)))
> expPois <- glm(status~x+offset(log(time)),data=expDF)

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)   1.6593     0.1406  11.801  < 2e-16
x            -0.6000     0.1988  -3.018  0.00288

> expCox <- coxph(Surv(time,status)~x,data=expDF)

     coef exp(coef) se(coef)      z Pr(>|z|)
x -0.6416    0.5264   0.1494 -4.295 1.74e-05

The ability to fit PH models with Poisson models having event-specific intercept terms has has been recognized for over 40 years: J Whitehead, "Fitting Cox's Regression Model to Survival Data using GLIM," Journal of the Royal Statistical Society. Series C (Applied Statistics) 29: 268-275 (1980).
Once you get beyond the exponential, however, you get into trouble. With a Weibull shape of 2 for simulated data (thus maintaining a PH interpretation amenable to Cox regression) instead of the exponential shape of 1:
> set.seed(101)
> weibDF <- data.frame(time=c(rweibull(100,shape=2,scale=1),rweibull(100,shape=2,scale=2)),status=1,x=c(rep(0,100),rep(1,100)))
> weibPois <- glm(status~x+offset(log(time)),data=weibDF)
Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)  1.32965    0.07030  18.914  < 2e-16
x           -0.64658    0.09942  -6.504 6.26e-10

> weibCox <- coxph(Surv(time,status)~x,data=weibDF)

     coef exp(coef) se(coef)      z Pr(>|z|)
x -1.2927    0.2745   0.1680 -7.696  1.4e-14

The issue is that the Cox PH analysis doesn't take actual time into account, only the ordering of events. Any stretch or compression of the time scale between events will give the same coefficient estimates, regardless of how the underlying baseline hazard over actual time is thus changed. In contrast, the Poisson coefficient estimates depend explicitly on event times. This failure of agreement in a fairly simple case with non-constant hazard suggests that there might not be much to pursue in general, even though I can't rule out some other specific combinations of hazards and data that could provide agreement absent constant hazards in time.
The Poisson estimate agrees much better with the (negative of) the accelerated failure time (AFT) coefficient of interest (Weibull is the default for survreg()):
> weibSR <- survreg(Surv(time,status)~x,data=weibDF)
              Value Std. Error      z      p
(Intercept) -0.0370     0.0556  -0.67   0.51
x            0.6914     0.0766   9.03 <2e-16
Log(scale)  -0.6136     0.0557 -11.02 <2e-16

which I guess isn't that surprising, as the Poisson and AFT models (with all cases having events) substantially differ only in terms of the assumed error distributions of $\log t_i$ about the predicted values.


How to reduce high number of categorical variables from your dataset while training ML algorithm

Question: I have a dataset that has a high number of categorical variables.
For example, currently, the dataset has 37 categorical variables, now if I perform one hot encoding or any other encoding it will explode the number of columns and overall column counts will increase by 100.
Hence is there an efficient way to first select the best 5 or 10 features among all the categorical variables present?
Answer: There is a huge number of solutions for your problem. I will give one really easy to implement and incredibly basic one and another one that is more decent. First one is to do simple linear regression using simple equation y = ax+b for each feature. After you fit linear regression function, you can check your "a" values for each feature and see how much they change the "y" value. This is something I suggest to get basics of feature selection (keep that in mind, negative "a" values have big importance too). Other one is Pearson correlation. There is many ways to check correlation but you can give these two a try.


BigQuery Error In where Clause with a String type column

Question: I have a column that contains strings like this '0 0PAA01 CF101 -S07'. I have some records in the database and when I tried to retrieve it using BigQuery the query is not returning records.
I am doing
select *
from table
where column='0 0PAA01 CF101 -S07'
Is a BigQuery Problem?
Answer: I'm 99% sure this is not a BigQuery problem - but that the strings are in fact different.
Look at this:
<code>SELECT MD5('my name is Felipe Hoffa') from_keyboard
  , MD5(str) from_db
  , str='my name is Felipe Hoffa' equal_are_they
FROM (
     SELECT 'my name is Felipe Hoffa' str
)
</code>

Why are they different? One has a tab instead of a space.


Adding and subtract complex numbers using OOP structure

Question: I have here a code that should print the sum and difference of two complex numbers. The instructions given are:
make the methods add, subtract, and print to be void and
test using the constructor's object.

public class Complex {

    /**
     * @param args
     */
    public double real;
    public double imag;
    public String output = "";

    public Complex(double real, double imag){
        this.real += real;
        this.imag += imag;
    }

    public Complex(){
        real = 0;
        imag = 0;
    }

    public double getReal(){
        return real;
    }

    public void setReal(double real){
        this.real = real;
    }

    public double getImag(){
        return imag;
    }

    public void setImag(double imag){
        this.imag = imag;
    }

    public void add(Complex num){
        this.real = real + num.real;
        this.imag = imag + num.imag;
    }

    public void subtract(Complex num){
        this.real = real - num.real;
        this.imag = imag - num.imag;
    }

    public void print(){
        //
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Complex c1 = new Complex(4.0, 8.5);
        Complex c2 = new Complex(8.0, 4.5);

        c1.add(c2);
        c1.subtract(c2);
        c1.print(); //expected answer 12.0 + 13.0i
                                    //-4.0 - 4.0i
    }

}

The expected answers are 12.0 + 13.0i and -4.0 - 4.0i. Please help me with the method print. Thank you.
Comment: What's the problem? Use `System.out.println()`, possibly with `String.format()`
Comment: off topic. why you adding values in constructor. why not simply assign them?
Comment: System.out.println(real + " " + imag +"i");
Comment: @AlekseiBulgak I tried that already but the only output is 4.0 + 8.5i.
Comment: It's the correct output: c1.add(c2) => 12+13i. then c1.subtract(c2)=> 12+13i-(8+4.5i)=4+8.5i... In fact, you are adding then subtracting the same value at c1, so in the end c1 is left unmodified
Comment: Is the problem really with your print() method? If you're getting the wrong output, it sounds like you need to fix your add and subtract and other methods instead.
Answer: Perhaps this is not what you're looking for, but to make the number be printed
isn't enough to make something like this in your print method?
System.out.print("The number is: " +real +"+i" +imag);
Comment: I tried that already but the only output is 4.0 + 8.5i. The expected answers are 12.0 + 13.0i and -4.0 - 4.0i.
Answer:    public void print(){
     if(this.imag <0){
      System.out.println(this.real+" "+this.imag+"i");
     }
     if(this.imag >0){
      System.out.println(this.real+"+"+this.imag+"i");
     }
    }

Answer: You incorrectly use print merhod. if you want to see correct result you need to rewrite add method like this:
public void add(Complex num, Complex num2){
    this.real = num.real + num2.real;
    this.imag = num.imag + num2.imag;
}

rewrite subtract method also.
public void subtract(Complex num){
    this.real = real - num.real;
    this.imag = imag - num.imag;
}

Now main method look like this:
public static void main(String[] args) {
        Complex c1 = new Complex(4.0, 8.5);
        Complex c2 = new Complex(8.0, 4.5);
        Complex result = new Complex(8.0, 4.5);
        result.add(c1,c2);

        result.print();

        result.subtract(c1,c2);
        result.print();

print method as I told previously look like:
public void print(){
    System.out.println(real + " " + imag +"i");
}

Explanation:
In your code you have error. You add c2 to c1 and then subtract c2 frim c1 and then print result. Mathematically this looks like : c1= c1+c2-c2;


search element in array using observable in angular 2

Question: I have search input for the book title and I need it to find books without reloading the page. My code works at the moment witht he reloading of the page, I type book name and push submit.
How can I rewrite this code in order to use observable, thus search for the books without reloading the page?
filterByName(){
    this.filteredItems = [];

    if(this.inputName != ""){
      this.books.forEach(element => {
        if(element.author.toUpperCase().indexOf(this.inputName.toUpperCase())>=0 ||
            element.title.toUpperCase().indexOf(this.inputName.toUpperCase())>=0){
          this.filteredItems.push(element);
        }
      });
    }else{
      this.filteredItems = this.books;
    }
    console.log(this.filteredItems);
    this.init();
  }

HTML:

    Filter
    <input  type="text"  id="inputName" [(ngModel)]="inputName"/>
    <input type="button" (click)="filterByName()" value="Apply"/>

Answer: You don't need to use observables for that, if you update your filteredItems variable in your component, it'll be updated in your view, such as:
filterByName() {
  if(this.inputName.length < 1) {
    return;
  }
  this.filteredItems = this.books.filter(book => {
    return book.author.toUpperCase().indexOf(this.inputName.toUpperCase()) >= 0 ||
      book.title.toUpperCase().indexOf(this.inputName.toUpperCase()) >= 0
  });
}

and in your view:

  Filter
  <input  type="text"  id="inputName" [(ngModel)]="inputName"/>
  <input type="button" (click)="filterByName()" value="Apply"/>

{{ book.title }} - {{ book.author }}

Comment: I need to update it without using submit button. I don't need to reload the page.
Comment: It should like with the ajax, you type text and right away you have result
Comment: Then you can attach an event to your input, such as: `` and remove your button, your function will now be `filterByName(input)` and you will use `input` variable instead of `this.input`
Comment: it doesn't work properly, if I type something it can find it but if I remove text and type something again it doesn;'t show me anything


Translating variables with context in Twig templates

Question: In Drupal 8, with English and German enabled, I am trying to translate a variable using a specific context.
When visiting a page in German:
{% trans with {'context': 'Long month name'} %}
    March
{% endtrans %}

This outputs März which is fine.

{% set month = 'March' %}

{% trans with {'context': 'Long month name'} %}
   {{ month }}
{% endtrans %}

This outputs March which is not fine.

Why? And how am I supposed to translate variables in a Twig template?
Here is the documentation I have read.

Edit: https://www.drupal.org/node/2357633
This mentions:

The t filter will run the variable through the Drupal t() function, which will return a translated string. This filter should be used for any interface strings manually placed in the template that will appear for users.

And also:

The following patterns are unsafe and should not be used because they pass a variable directly to translation. This not only inflates the list of strings for translation but is also a potential vulnerability, particularly if the output can be entered by a user.

{{ var1|t }}
{{ var1|placeholder }}
{% trans %}{{ var1 }}{% endtrans %}

Answer: In Drupal 8, you can translate a string in a Twig file with a specified context in two ways :
{{ "Text to translate"|t({}, {'context' : 'Context name'}) }}

and
{% trans with {'context': 'Context name'} %}
    Text to translate
{% endtrans %}

Answer: A variable is like a placeholder. It does not get translated. Context or not is not relevant. Your example basically translates to t('@month', ['@month' => 'March'], ['context' => 'Long month name']). It simply doesn't work like that.
if you need to translate march and then put it as a variable in a bigger text, you first need to translate March on its own using the context and then put it in the other text.
I'm not sure if you can do that within twig, but I suppose that's only a simplified example and you actually get month injected? Then you need to translate the month name at the source, where it is provided to the template. If that is not the case, then you need to explain your actual use case, because I suppose this is not it..
Comment: That all makes sense, thank you. Will edit my question in a minute with a bit of information I just found.


What is being returned by this swipe.js function?

Question: This code exists in the swipe.js library. I'm trying to customize it. The comment that precedes the return says 'exposes the Swipe API' but I'm not sure what that means.
function Swipe(container, options) {

...

//everything that makes the library work, including a setup() function

...

  //expose the Swipe API
  return {
    setup: function() {

      setup();

    },
    slide: function(to, speed) {

      // cancel slideshow
      stop();

      slide(to, speed);

    },
    prev: function() {

      // cancel slideshow
      stop();

      prev();

    },
    next: function() {

      // cancel slideshow
      stop();

      next();

    },...some more stuff
}

Is the returned value an array? Array list? Say for example I instantiate a new swipe object window['aNewSwipeObject'] = Swipe($theDOMElement); and I call the setup function like this window['aNewSwipeObject'].setup() what setup() gets called? The setup() above the return, or the setup() inside the anonymous function that is in the return of the Swipe() function?
Answer: It returns an object literal. Every key in the object is a function.
This is often used to create a namespace of functions, and by placing them in the function scope, the functions will share the local scope inherited from the namespace.
For example,
var Namespace = (function() {
    var helperFunction = function() { ... }
    var localData = // ...

    return {
       publicFunction1 : function() { ... },
       publicFunction2 : function() { ... },
       publicFunction3 : function() { ... }
    }

})();

Comment: So if I call setup() on the object, is it referencing the object literal or the setup() function defined above it?
Comment: To be precise, it returns an object. An *object literal* is just a syntactic construct to create an object.
Comment: If there are two setup() functions, and one is in the `return {...}` statement and the other above it is defined as `var setup = function() {...}`, then the *latter* function is a local function, and is not exposed in the Swipe API. So you would be calling the `setup` function in the `return {...}` statement.
Comment: This is one of the advantages of placing a set of functions in the function scope. They can then have their own (shared) local scope.
Answer: it returns the methods so the object can use them
Answer: It's returning an object where each property is a reference to an anonymous function.
This is a convenient way to encapsulate/hide data. Private functions exist within the Swipe function (you can nest functions in JavaScript), and the individual properties for the returned object-literal are merely references to anonymous functions that call these private functions.
This way, only the Swipe function has access to those private, internal functions.
When you call setup on the object, it calls the public function (referenced by the setup property of the object), which in turn, calls the internal setup() function which is only available within the Swipe function.
Here's something that makes it cleared:
function myAPI(options) {

    function privateFunction1() {
       ...
    }

    function privateFunction2() {
       ...
    }

    function privateFunction3() {
       ...
    }

    return {
        publicFunction1: privateFunction1,
        publicFunction2: function() {
            //some extra code
            privateFunction2();
        },
        publicFunction3: function() {
            ...
        }
    };
}

Now you can get individual instances by doing:
var myAPIObject = myAPI(options);

But another pattern that you will see is:
var myAPI = (function() {

    function privateFunction1() {
       ...
    }

    function privateFunction2() {
       ...
    }

    function privateFunction3() {
       ...
    }

    return {
        init: function(options) {
            //do something with options
        },
        publicFunction1: privateFunction1,
        publicFunction2: function() {
            //some extra code
            privateFunction2();
        },
        publicFunction3: function() {
            ...
        }
    };
})();

In this instance, you will do myAPI.init(options) to initialize the API, but in this pattern myAPI is effectively a singleton (which is usually what you want, unless you want to maintain state on a per-instance basis).
Comment: By singleton do you mean there will only be one instantiation of this object? Whereas in your first example we could instantiate several objects?
Comment: @jefffabiny Yes. In the first example you can have multiple instances, but in the second example you effectively have a singleton.


Is there a way to log changes to module settings for better long-term administration and debugging?

Question: We run quite a complicated Drupal 6 site with a lot of custom modules which was already migrated from D5. There are a few site administrators and we have had situations where a change in the settings of one module (usually something conflicting with Boost) has caused a problem with the site that is only detected later. We have no way to quickly tell which settings have been changed recently and what their previous values were.
Is there an additional module that hooks into to all variable_set() calls (for example) and logs the old and new values so that we can have an admin view listing all changes over time and which user made the change? It would be great to have an option to add a note to each item to explain why the change was made?
We try and share notes in our wiki on such changes but I think it would be much better if such data was available from inside Drupal itself.
Comment: Just to be clear, I'm not asking as a module developer. I'm looking for a tool/workflow as a site administrator to track changes and be able to undo setting changes if a bad side-effect is later detected.
Answer: Here is our workflow.
First of all you code base should use a versioning system as Git or Subversion, doesn't matter which you like or want use, but the main point its to use a versioning system.
Then you should give a look to Features module and all his modules relatives. This will allow you to create a set of module that include standard configuration and etc.
So, mostly popular modules are using either variables or ctools to manage their configuration, for those who sue CTools, Featues will help you export their configuration, for the others you've Strongarm.
I think just with this, you will covers at least 80% of your configuration, for the rest your should either move it to features or use hook_update_N with a module.
Here what is important its that all your configuration must be inside files and committed to the versioning system.
Like that, you will which configuration has been changed and see the historic through the versioning system.
I think the most important part its to move the already existing into Features and force people to use Features when they are doing changes in the configuration.
Comment: Thanks! Will check this out. Features covers both the config values AND the version of each module?
Comment: Features will help your for the config values. For the version of each module and historic, you will use versioning system.
Comment: It's worth mentioning that deploying updated features code isn't always sufficient to actually deploy the change (ie you may need to revert, which you can do in your `hook_update_N()`).
Answer: Blame module sounds like it might fit your needs:

The Blame module is an audit tool that allows the site administrator (or those with appropriate permissions) to see changes that have been made to any form on their Drupal website. The purpose of this module is to provide the ability to quickly identify which user made which changes to which form at a specific time. This includes node forms, contact forms, administrative settings, webforms, etc.

In the past when I've needed to find configuration changes I've grepped access logs for posts to specific forms.
Comment: That's exactly what I was thinking of! Shame is seems to be kinda dead - only 9 sites using it right now. I'll see if I can help with the rewrite...
Comment: I wouldn't worry about that, just try it out. Those stats are just fluff and shouldn't effect your decision on whether or not to use the module.


opening email with javascript on iphone

Question: I have a website that format the subject of the email that the user need to send. Then I open the client default email with mailto: function in javascript and they write their email and send it. It work everywhere I have tested it except with iPhone can someone tell me why, please.
This the code I use for opening the default email:
<code>    var email = 'firstname.lastname@example.com';
    var subject = 'the subject';
    var bodyemail = 'the body';

    var mailto_link = 'mailto:' + email + '?subject=' + subject + '&body=' + encodeURI(bodyemail);

    win = window.open(mailto_link, 'emailWindow');

    if (win && win.open && !win.closed) win.close();
</code>
Answer: Don't open the mailto link in a new window, just set the current window's href to the link.
<code>window.location.href = mailto_link;
</code>

opening email with javascript on iphone


auto.arima() not differencing while it should?

Question: I am using auto.arima from forecast package to create an ARIMAX model.
The dependent variable and the regressors are non-stationary. However, auto.arima() returns a model ARIMA(0,0,0).
Should I worry about this? Should I force auto.arima() to difference my time series, specifying d=1 ?
If I don't put any regressors in my model, it does detect non-stationarity, ending up with ARIMA(0,1,1).
I know the problem is similar to this topic, but my dataset is bigger (about 90 observations), thus the answer given is not satisfying.
Answer: auto.arima did nothing wrong. Note you have an additive model:
response = regression + time_series

When you include regressors / covariates, non-stationarity is captured by regressors / covariates, so time series component is simple. For your data, you end up with ARIMA(0,0,0), which is white noise.
When you don't have regressors / covariates, non-stationarity has to be modelled by time series, thus differencing is needed. For your data, you end up with ARIMA(0,1,1).
Of course, those two models are not the same, or even equivalent. If you really want some model selection, use the AIC values by both models. But remember, all models are wrong; some are useful. As long as a model can not be rejected at certain statistical significance, it is useful for prediction purpose.
Comment: if you post your data or email it to me .. I might be able to help you further.