Predicting a fair coin flip outcome with logistic regression

Question: I am trying to better understand the results of logistic regression models and I wanted to apply a logistic regression model on a trivial "fair" coin flip simulation example. I want to simulate a number of coin tosses and fit a logistic regression model with whether we had at least one heads as the outcome and the number of coin tosses as the only predictor.
In this scenario, I know that a logistic regression model is not very useful, but I am just trying to understand how to interpret things and apply the model to real-life examples better.
Here is a simple explanation of what the simulation does:

There are 10000 examples (rows)
Each example has a random number of coin tosses (between 0 and 30,
uniform distribution)
Each coin toss has a 0.5 chance of getting a heads
For each example, result = 1 if at least one toss resulted in a heads, result = 0 otherwise
We end up with a 10000 by 2 dataframe with two columns: nb_toss and result

My simulation uses the following code:
import numpy as np
import pandas as pd

# Set random seed to always get the same results
np.random.seed = 2

examples = [str(x) for x in range(10000)]
results = []
nb_tosses = []

# For each of my 10000 example rows...
for e in examples:

  # Assign a random (uniform distribution) number of tosses to each example, from 0 to 30
  nb_toss = int(np.random.uniform(0,30, size=1))
  nb_tosses.append(nb_toss)

  result = 0
  for toss in range(nb_toss):

    # Each coin toss has a 0.5 chance of success (binomial random variable)
    # If at least one coin results in a success, assign 1 to result, otherwise assign 0
    result = np.random.binomial(1, 0.5, 1)[0]

    if result == 1:
      break
  results.append(result)

# Build a dataframe with the number of tosses and the result (1 or 0) for each row
toss_df = pd.DataFrame({"nb_toss" : nb_tosses, "result" : results})

So as you can see the coin is completely fair (50% probability of heads).
Now I fit my logistic regression model:
from patsy import dmatrices
import statsmodels.api as sm

# Build my X (10000 rows, cols: intercept = 1, nb_toss)
# and y (result)
y, X = dmatrices("result ~ nb_toss", data=toss_df)

# Fit a logistic regression model that predicts toss result given number of coin tosses
logit_mod = sm.Logit(y, X)
logit_res = logit_mod.fit(disp=0)

# Print out the summary
logit_res.summary()

Logit Regression Results
Dep. Variable:  result  No. Observations:   10000
Model:  Logit   Df Residuals:   9998
Method: MLE Df Model:   1
Date:   Mon, 15 May 2017    Pseudo R-squ.:  0.6503
Time:   13:47:43    Log-Likelihood: -849.40
converged:  True    LL-Null:    -2429.0
LLR p-value:    0.000
coef    std err z   P>|z|   [95.0% Conf. Int.]
Intercept   -1.5767 0.102   -15.490 0.000   -1.776 -1.377
nb_toss 1.1099  0.046   24.204  0.000   1.020 1.200

I am particularly interested in the interpretation of the pseudo R-squared.
Also, I find a predicted probability of 17% for 0 coin tosses, which is obviously impossible. Is there a way to adjust the model to take this into account?
I am finally trying to understand the following: say I have a dataset where the result of the coin toss has an influence on another binary outcome y. If my example gets at least one heads, then the probability of y = 1 is 80%. Otherwise, the probability of y = 1 is 40%. If I am unaware of these true probabilities, how well can I fit a logistic regression model that estimates the effect of getting at least a heads or tails, or the effect of the number of coin tosses on this binary outcome?
Comment: Unless you explain in words what your code is doing, this question will be inaccessible to anyone without a knowledge of Python and the time and interest to review the code, run it, and study its output.  That would exclude many of the best candidates to answer it.
Comment: As whuber pointed out, the true function for your model is specific nonlinear function of nb_toss and the single event probability. The linear function (plus logit link) will be a reasonable approximation over some range. However, not for nb_toss=0. The probability jumps from 0 to 0.5 going from nb_toss=0 to 1 and then increases more slowly. (A symptom of the nonlinearity is that we can perfectly predict the outcome if nb_toss=0 and when nb_toss gets large, the probability is essentially 1. statsmodels gives a perfect separation warning because a large number of predictions are close to 0 or 1
Comment: One reason why an explanation in words is so important is to check that the code is doing what you think it is.  The explanation you added is very helpful (+1).  Why do you suppose, though, that the log odds of at least one head ought to be a linear function of the number of tosses?  You might want to carefully consider the cases $n=0$ and $n=1$ especially.  Ordinarily when one is learning a technique to deal with a particular model, it is best to begin by generating data that conform to that model--otherwise the results are difficult or impossible to interpret.
Comment: I ran your example and the prediction for nb_toss=1, `logit_res.predict([1,1])`, is around 0.5 which corresponds to your simulation. If you don't want to assume a specific nonlinear function for the effect of nb_toss, then one possibility is to add log(nb_toss), nb_toss**2 or similar polynomial nonlinear terms. (note: if nb_toss=0, then we can perfectly predict that y has to be zero.)
Comment: AFAICS, log-link is the correct nonlinear function between nb_toss and the probability for the outcome. e.g. GLM family=Binomial link=log
Comment: Got it, I'll comment it.
Comment: Sorry I thought the code part was trivial, I added it just to give complete information on what I was doing.
Comment: I'm basically trying to figure out when using a logistic regression model for my data makes sense as well. I agree that the relationship is definitely not linear. I talk about this cut-off point from n=0 to n=1 in my question. Does this mean that using a logistic regression here just doesn't make sense because its assumptions do not hold? If so, I'm wondering how to easily check if my data follows logistic regression assumptions.
Comment: I didn't understand your note, would you mind explaining a little further? If I run logit_res.predict(1,0), I do not find 0.
Comment: Thanks for the explanation. Overall the logistic regression model does not seem to really fit this non-linear model. I've tried adding square and cubic parameters, but while it estimates the outcome of 0 tosses correctly (probability around 2%), the estimated probability of 1 toss is 38%. If I did not know the true probability distribution, how could I assess whether my model was a good fit for the data? I can imagine visualizing charts, but this would be much less feasible if I had several predictors.
Comment: I would remove observations with nb_toss=0 because there is nothing to estimate and it will only distort the rest. There is no information about the true parameter if the sample size is zero. (Actually, the probability or observed frequency at nb_toss=0 is not defined, it's "zero" for both events.)
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/58823/discussion-between-konrad-and-user333700).
Answer: Below is part of an answer for how to use a different link function to capture the nonlinearity.
As discussed in the comments, the relationship between the number of tosses, nb_toss, and the probability of observing a success is nonlinear.
If $p_0$ is the probability of observing a failure in a single toss, then the probability of observing only failures in n tosses is $p_0^n$, and of observing a success overall is $1-p_0^n$
For simplicity I switch the definition of the outcome so that failure is 1 and success is zero. Then the probability of observing a failure is $Pr(failure) = p_0^n$ which we can rewrite as.
$Pr(failure) = exp(n * log(p_0)$
This is just a log-link with n, i.e. nb_toss in the linear prediction part. The estimated coefficient is the log probability of a toss, so we need to take exp to recover $p_0$.
Below I use statsmodels with the data and imports from the question. The estimated $p_0$ is 0.508, close to 0.5, and the prediction also match closely the true probabilities.
res_glm = sm.GLM(1 - y, X[:, 1],
                 family=sm.families.Binomial(link=sm.families.links.log())).fit()

print(res_glm.summary())
print(np.exp(res_glm.params))
nbt = X[:, 1]
ii = np.arange(20)

table = np.column_stack((0.5**ii, res_glm.predict(ii),
                         [1 - y[nbt == i].mean() for i in ii]))
print(pd.DataFrame(table, columns=['true', 'predicted', 'sample']))

this prints
                 Generalized Linear Model Regression Results
==============================================================================
Dep. Variable:                      y   No. Observations:                10000
Model:                            GLM   Df Residuals:                     9999
Model Family:                Binomial   Df Model:                            0
Link Function:                    log   Scale:                             1.0
Method:                          IRLS   Log-Likelihood:                -765.47
Date:                Mon, 15 May 2017   Deviance:                       1530.9
Time:                        19:57:36   Pearson chi2:                 1.88e+04
No. Iterations:                    10
==============================================================================
                 coef    std err          z      P>|z|      [0.025      0.975]
------------------------------------------------------------------------------
var_0         -0.6762      0.020    -34.626      0.000      -0.714      -0.638
==============================================================================
[ 0.50856518]

        true  predicted    sample
0   1.000000   1.000000       NaN
1   0.500000   0.508565  0.521368
2   0.250000   0.258639  0.290141
3   0.125000   0.131535  0.120944
4   0.062500   0.066894  0.055385
5   0.031250   0.034020  0.027778
6   0.015625   0.017301  0.008380
7   0.007812   0.008799  0.014663
8   0.003906   0.004475  0.002770
9   0.001953   0.002276  0.000000
10  0.000977   0.001157  0.000000
11  0.000488   0.000589  0.000000
12  0.000244   0.000299  0.002924
13  0.000122   0.000152  0.000000
14  0.000061   0.000077  0.002915
15  0.000031   0.000039  0.000000
16  0.000015   0.000020  0.000000
17  0.000008   0.000010  0.000000
18  0.000004   0.000005  0.000000
19  0.000002   0.000003  0.000000

aside: statsmodels prints a DomainWarning
DomainWarning: The log link function does not respect the domain of the Binomial family.
In general, there can be problems when using log-link with Binomial, i.e. log-Binomial, because the log-link does not force the predicted values to be in the range [0, 1]. However, the way this is set up in this example, the prediction is limited by 1 because the explanatory variable is nonnegative.
Comment: +1 This is an excellent analysis, showing clearly how understanding the underlying situation can lead to an appropriate and tractable model.


Embedding views in tpl files

Question: I need an advice. Is there any downsides when embedding views in the page/node tpl files like the following:
<?php print views_embed_view('course_videos', 'block_1'); ?> and this <?php $key =  views_get_view_result('course_videos', 'block_2');  ?> in the node.tpl files
I am little bit concerned cause I've read several articles saying you must not query the db or use a complex php logic in the tpl files. Everything's working like a charm now. The site is still not in production though...
Thank you in advance!
Answer: Including views in tpl is going backwards. Drupal allows you to use views as pages and as blocks. You can apply templates to that pages and blocks, and you can put blocks in regions. By calling views from template, you are messing with theme registry and cache logic. It might be not an issue if site is small, and both read and write volumes are low, but it will result in pages being out of sync on heavy loaded site.
Instead of outputting view directly, make a region, output it in template file, and put a views block inside.
Using views_embed_view in a preprocess function in template.php might be OK. Opinions and experience with it can vary, and I would try to avoid it, but certainly it does not mess with cache or theme registry like using it in tpl would.
Comment: @Mołot Gotta say I disagree - using `views_embed_view` in a preprocess function in template.php is pretty standard (obviously not if you're trying to build a totally de-coupled theme, but for custom project-specific themes I've seen it quite a bit)
Comment: I'll second that in preprocess, setting a variable to the output of a views hook is pretty widespread as well but totally agree it should be kept out of the actual tpls.
Comment: I hope @IvanIvanov will read your comments too, and make his own decision as consciously as possible. Maybe one day I'll feel a need to try it again and change my mind? Not happening soon, but who knows ;)
Comment: @Clive updated my answer. I hope it's as factual as feasible now, and opinions may sit in comments. I've seen it work OK and I've spent long hours when it didn't. In ideal world... ;)
Comment: ok, but what if I get a view in the template.php preprocess function and pass it to the tpl file like a variable, like the following:

In the template.php $variables['views_course_videos'] = views_embed_view('course_videos', 'block');

In the tpl file:
print $'views_course_videos';

Is this way ok?
Comment: @IvanIvanov Not really. Templates should not generate errors if view is unavailable for some reason. It can lead to long, long hours of frustrating debugging. Been there, done that, never again.
Comment: Got your point :) Thank you for sharing your experience!
Comment: @Clive well, that's why I'm not including it in my answer. but I had a bad experience with it, sharing when asked.
Comment: @Mołot You're definitely right from a best practice point of view - separate logic and display as much as possible. The natural tendency (for me anyway) is to look at even Drupal from an MVC point of view, even though it's anything but. Sometimes "who's the controller?" gets a bit muddy, and inevitably someone's gonna use the theme layer at some point!

Embedding views in tpl files


Showing that the unit circle has measure zero

Question: How can  I show that $\{x \in \mathbb{R}^{2}: |x| =1\}$ has measure zero using the definition of measure zero? I don't want to use the interpretation of measure in $\mathbb{R}^2$ as area (and then show this by using the fact that the area of a circle is $\pi r^2$. I was thinking somehow find rectangles to that contain the circumference of this circle and keeping one of the sides of each rectangle free to make $\varepsilon$-small. I'm not able to get ahead with this approach though. Thoughts and ideas?
Note - this question is NOT a duplicate of Graph of real continuous function has measure zero because it focuses on a specific example. The results from the other question might be modifiable to apply here, but look at something different.
Comment: Here is an idea you can elaborate: Consider n evenly spaced points on the unit circle, then at each points you draw a rectangle/square center at those points with side length large enough to cover the circle. Then the amount of rectangles you draw will be $\mathcal{O}(n)$, but the area of each circle will be $\mathcal{O}(1/n^2)$, let $n$ goes to infinity......
Comment: @user247327 OP might be using $|x|$ as a notation for the Euclidean norm of $x$.
Comment: OK to use compactness in proof?
Comment: Yes, I tried using compactness, but I'm running into the problem that the finite cover of $n$ (say) rectangles I get in the end depends on my choice of $\varepsilon$.
Comment: Your title says "unit circle" but your text says "|x|= 1".  Do you understand that "|x|= 1" is **not** a circle?  (It is a square with its diagonals along the coordinate axes.)
Comment: Yes, I'm using $|x|$ to denote $||x||_{2}$. I thought this is the conventional notation, but I'm sorry for the confusion.
Comment: It is a duplicate of the other thread, because you can simply divide the circle into two genuine functions, and since the union of two sets of measure zero still has measure zero, you're done.
Answer: Look at the regular $4n$-gon with $(1,0)$ being a vertex.  We can cover the circle by $4n$ rectangles
$$
\overline{\operatorname{conv}}\left\{\cos\left(\frac{k\pi}{2n}\right),\cos\left(\frac{(k+1)\pi}{2n}\right)\right\}\times
\overline{\operatorname{conv}}\left\{\sin\left(\frac{k\pi}{2n}\right),\sin\left(\frac{(k+1)\pi}{2n}\right)\right\},\quad k=0,1,\dots,4n-1
$$
The sum of measures of these rectangles is
\begin{align*}
&\sum_k\left\lvert\cos\left(\frac{k\pi}{2n}\right)-\cos\left(\frac{(k+1)\pi}{2n}\right)\right\rvert\cdot\left\lvert\sin\left(\frac{k\pi}{2n}\right)-\sin\left(\frac{(k+1)\pi}{2n}\right)\right\rvert\\
&=4\sum_k\left\lvert\sin\left(\frac{\pi}{4n}\right)\sin\left(\frac{(2k+1)\pi}{4n}\right)\right\rvert\cdot\left\lvert\sin\left(\frac{\pi}{4n}\right)\cos\left(\frac{(2k+1)\pi}{4n}\right)\right\rvert\\
&=2\sin^2\left(\frac{\pi}{4n}\right)\sum_k\left\lvert\sin\left(\frac{(2k+1)\pi}{2n}\right)\right\rvert\\
&\leq 2\sin^2\left(\frac{\pi}{4n}\right)\cdot 4n\to 0\quad\text{as }n\to\infty.
\end{align*}
Answer: I will show that
the difference between
the areas of the
circumscribed and inscribed
$n$-gons goes to zero.
Consider a regular $n$-gon
inscribed in the unit circle.
There are $2n$ triangles
with central angle
$t = \pi/n$
and hypotenuse
$1$,
so the distance to the side
$s_n$ and length $h_n$
satisfy
$s_n = \cos(t)$
and $h_n = \sin(t)$.
The area of each triangle
is thus
$\frac12 s_nh_n
=\frac12\cos(t)\sin(t)
=\frac14\sin(2t)
$
so the area of the
inscribed $n$-gon is
$2n$ times this or
$\frac12n\sin(2t)
$.
Extend the radii
to get the
circumscribed $n$-gon.
There are $2n$ triangles
with base $1$
and height
$g_n$ such that
$g_n = \tan(t)$,
so the area is
$\frac12 g_n
=\frac12 \tan(t)
$.
The total area is thus
$n\tan(t)
$.
Note that
both of these areas go to
$\pi$ as $n \to \infty$
since
$\sin(x) \approx \tan(x)
\approx x$
as $x \to 0$.
However,
the only inequality needed is
$\sin(x) < x$
for $0 < x < \pi/2$.
The difference in
the two areas is thus
$\begin{array}\\
D_n
&=n\tan(t)-\frac12 n\sin(2t)\\
&=n\left(\tan(t)-\frac12 \sin(2t)\right)\\
&=n\left(\dfrac{\sin(t)}{\cos(t)}-\sin(t)\cos(t)\right)\\
&=n\sin(t)\left(\dfrac{1}{\cos(t)}-\cos(t)\right)\\
&=n\sin(t)\dfrac{1-\cos^2(t)}{\cos(t)}\\
&=n\sin(t)\dfrac{\sin^2(t)}{\cos(t)}\\
&=n\dfrac{\sin^3(t)}{\cos(t)}\\
&=n\dfrac{\sin^3(t)}{1-2\sin^2(t/2)}\\
\end{array}
$
We now use
$\sin(x) < x$
for
$0 < x < \pi/2$
so
$\begin{array}\\
D_n
&\lt n\dfrac{t^3}{1-2(t/2)^2}\\
&= n\dfrac{(\pi/n)^3}{1-2(\pi/(2n))^2}\\
&= \dfrac{1}{n^2}\dfrac{\pi^3}{1-\pi^2/(2n^2)}\\
&< \dfrac{2\pi^3}{n^2}
\qquad\text{for } n \ge 4\\
&\to 0
\qquad\text{as } n \to \infty\\
\end{array}
$
Comment: The radius is 1 and the height $g$ (small side) of the circumscribed triangle with central angle $t$ satisfies height/radius = tan(t).
Comment: Nice! can you please help in how the extended radii is $\tan(t)$?


How to add a glowing filter to an image

Question: This is the effect I want (the 2nd one):

in photoshop
1) duplicate layer 2) reduce exposure of the new layer 3) add blur
    4) blend mode linear dodge (add)
a programmer I knew achieved this effect long ago, he never told how to do it with code but gave me the instructions to achieve the same thing in photoshop
its been a while and started to learn web dev for my own and this effect is something that calls my atention (and yes, lost all posible contact with this person)
at first I thought this was achieved with css filter effects https://www.w3schools.com/cssref/css3_pr_filter.asp
however while it contains the blur(%) I cant seem to find a way to achieve the exposition or even worse the linear dodge blend mode.
Does anyone know how in the earth was this filter made? I am guessing he didnt use css and instead did it with javascript.
Any help is appreciated.
edit: oh you were right, it was just playing with those values, got a nice filter but will keep playing around with them! thank you
Comment: To me the difference in those images looks like the contract is higher and that's it.... I think the only way you will find a way to make a specific filter is by playing around, maybe combine a few to see how close you can get to what you want....
Comment: Besides the filter:contrast, it looks like a mask has been applied, which isn't part of any standard.
Answer: You can use various techniques where you blur one version and composite it on top of the original using additive blending.
Here is one example using the image as background image and where the after element inherits the image, adds blur and composite using mix blending and lighten (lighter AKA "add" AKA "linear-dodge", can be used as well):

div {
  background:url(//i.stack.imgur.com/REbGC.png);
  width:190px;
  height:190px;
  }

/* Create an overlay blurring the background */
div:after {
  position:absolute;
  content:"";
  width:190px;
  height:190px;
  background:inherit;
  filter:blur(9px);        /* glow range */
  opacity:0.8;
  mix-blend-mode: lighten; /* lighter (add) can be used as well */
  }

The same can be achieved using a canvas element instead, but since not all browsers support the new filter property on the 2D context you may have to blur manually (added brightness to the demo below as well).

var img = new Image; img.onload = draw; img.src = "//i.stack.imgur.com/REbGC.png";
var blur = document.getElementById("blur"), blend = document.getElementById("blend"),
    luma  = document.getElementById("luma");

function draw() {
  var ctx = c.getContext("2d");
  ctx.drawImage(this, 0, 0);
  ctx.filter = "brightness(" + luma.value + ") blur(" + blur.value + "px)";   // note: not all browsers support this yet (FF/Chrome OK)
  ctx.globalCompositeOperation = "lighten";
  ctx.globalAlpha = +blend.value;
  ctx.drawImage(this, 0, 0);
  ctx.filter = "none";  // reset
  ctx.globalCompositeOperation = "source-over";
}

blur.oninput = blend.oninput = luma.oninput = draw.bind(img);

Blur: <input id=blur type=range min=0 max=30 value=9>

Blend: <input id=blend type=range min=0 max=1 step=0.1 value=0.8>

Luma: <input id=luma type=range min=0.5 max=2 step=0.1 value=1>

<canvas width=190 height=190 id=c></canvas>

How to add a glowing filter to an image


LWJGL Collision detection 3D?

Question: I'm new to lwjgl and openGL and i'm wanting to know how to do collision detection in 3D, I have a 3D sorta world setup but i don't know how to detect collisions.
Comment: OpenGL just draws thing and there's no such concept as a scene or models in OpenGL. There are just points, lines and triangles. So for anything that goes beyond that you either have to program it yourself, or you make use of some 3rd party libraries. For your purpose I suggest you look for some physics simulation library; even if you don't want physics, collision detection is an integral part of the whole thing.
Answer: LWJGL is just doing the graphics part. If you need a good collision detection or physics library for Java then JBullet is an option. JBullet is a Java port of the Bullet library used by many games.

LWJGL Collision detection 3D?


Scheme built-in to check list containment

Question: In Python I can do "x in list" to see if the list contains x. Is there any equivalent built-in in Scheme to do this?
Answer: The R5RS, and the R6RS standard library for lists
define memq, memv, and member
which can be used for that purpose.
Comment: It's not just in an SRFI, but also in R5RS (which is implemented by all decent implementations) http://schemers.org/Documents/Standards/R5RS/HTML/r5rs-Z-H-9.html#%_idx_428
Comment: Thanks for your comment, I have corrected the references in the answer.
Answer: In PLT Scheme, one has
(member whatever list)
(memv whatever list)
(memq whatever list)

from the SRFI which use, respectively, equal?, eqv?, and eq? to test for equality.  There are also a number of other library functions related to searching in lists:
PLT Scheme list reference
Answer: (define (contains? l i)
  (if (empty? l) #f
      (or (eq? (first l) i) (contains? (rest l) i))))

Answer: No, there is no list built-in predicate that will do that for you. It's extremely easy to define a lambda or a macro to do just that though.


how to do time stamping in access db using c#

Question: private void button1_Click(object sender, EventArgs e)
{
    OleDbConnection mycon = new OleDbConnection();
mycon.ConnectionString =@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Dinesh\C#\GIS_Power\WindowsFormsApplication1\bin\Power_DB1.accdb";
    OleDbCommand command = new OleDbCommand();
    command.CommandText = "INSERT INTO Table1 (Emp_ID,Asset_ID)VALUES('" + textBox1.Text + "','" + textBox2.Text + "')";
    mycon.Open();
    command.Connection = mycon;
    command.ExecuteNonQuery();
    mycon.Close();
}

this is the code that I have written to insert some details in my access db. I want that this button click also add the date and time of click into a column in my db. I tried to directly add a function GetDate within INSERT but it failed to execute. Any suggestions?
Comment: 1. You shouldn't be passing TextBox.Text directly to a query.  Use Parameters to guard against data injection. 2.  Why can't you just use `DateTime.Now` and update your insert query?
Comment: you did the right thing using `GetDate` , what you need to do is show the error that you got and we can help you fix it
Comment: @Harrison - using `DateTime.Now` may be a problem if you have several servers with different clocks.
Answer: I haven't tested this code, but it should get you started...
private void button1_Click(object sender, EventArgs e)
{
    using OleDbConnection mycon = new OleDbConnection()
    {
        mycon.ConnectionString =@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Dinesh\C#\GIS_Power\WindowsFormsApplication1\bin\Power_DB1.accdb";

        OleDbCommand command = new OleDbCommand();
        command.CommandText = "INSERT INTO Table1 (Emp_ID, Asset_ID, Date_Column) VALUES (?, ?, ?)";

        command.Parameters.Add("@EmpID", OleDbType.VarChar, 80).Value = textBox1.Text;
        command.Parameters.Add("@AssetID", OleDbType.VarChar, 80).Value = textBox2.Text;
        command.Parameters.Add("@Timestamp", OleDbType.Date).Value = DateTime.Now;

        command.Connection = mycon;
        mycon.Open();
        command.ExecuteNonQuery();
    }
}

Comment: @user3219362 I changed the OleDbType to Date. Gord was making the comment as I was updating the answer ;-)
Comment: still not working. what value do i give for date in insert query? coz the other two are taking textbox values but what about date?
Comment: @user3219362 I was using `DateTime.Now`.  Based on your situation, you may want to use the UTC time?  What error are you getting?
Comment: Data type mismatch in criteria expression. i used DateTime.Now too
Comment: @user3219362 Use `OleDbType.Date`.
Comment: still same problem. command.CommandText = "INSERT INTO Table1 (Emp_ID,Asset_ID, Actual_C)VALUES('" + textBox1.Text + "','" + textBox2.Text + "',OleDbType.Date)";
Comment: @user3219362 What you wrote isn't my answer. If you weren't going to use parameters then you would use DateTime.Now.  But the `?` were intentional to use verbatim and fill in with parameters.
Answer: Add datetime column with default value of now
It can be done like the below
ALTER TABLE YourTable ADD CONSTRAINT DF_YourTable DEFAULT GETDATE() FOR YourColumn

Comment: will i have to write another command.CommandText statement? where do i add your line in my code? Cause if i add it, too many errors popping up
Comment: The Access Database Engine says "Syntax error in CONSTRAINT clause."


How to add data in list view dynamically

Question: I want to display data from webservice into listview dynamically and its work perfectly.
Now I want to extend listview when it goes to end (like facebook home page). How do I do this?
note: I am using json webervice to pass my data from php, and use list view to display parsed data in my app.
Here is my code:
package info.androidhive.customlistviewvolley.adater;

import info.androidhive.customlistviewvolley.R;
import info.androidhive.customlistviewvolley.app.AppController;
import info.androidhive.customlistviewvolley.model.Movie;

import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnDragListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.MediaController;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;

public class CustomListAdapter extends BaseAdapter {
    private Activity activity;
    private LayoutInflater inflater;
    private List<Movie> movieItems;
    ProgressDialog pDialog;
    VideoView videoview;
    ProgressBar mSpinner;
    public static String s1="10";
    // Insert your Video URL
    String VideoURL;// = "http://demo.cogzideltemplates.com/client/sedio/video/d2b6a230106f355d2eee796863f4088a.mp4";

    ImageLoader imageLoader = AppController.getInstance().getImageLoader();

    public CustomListAdapter(Activity activity, List<Movie> movieItems) {
        this.activity = activity;
        this.movieItems = movieItems;
    }

    @Override
    public int getCount() {
        return movieItems.size();
    }

    @Override
    public Object getItem(int location) {
        return movieItems.get(location);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (inflater == null)
        inflater = (LayoutInflater) activity
        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if (convertView == null)
        convertView = inflater.inflate(R.layout.list_row, null);

        convertView.setClickable(true);

        if (imageLoader == null)
            imageLoader = AppController.getInstance().getImageLoader();

        NetworkImageView thumbNail = (NetworkImageView) convertView
            .findViewById(R.id.thumbnail);
        TextView title = (TextView) convertView.findViewById(R.id.title);
        TextView rating = (TextView) convertView.findViewById(R.id.rating);
        TextView genre = (TextView) convertView.findViewById(R.id.genre);
        TextView year = (TextView) convertView.findViewById(R.id.releaseYear);
        //TextView desc = (TextView) convertView.findViewById(R.id.desc);
        videoview=(VideoView) convertView.findViewById(R.id.VideoView);
        mSpinner=(ProgressBar) convertView.findViewById(R.id.progressBar1);

        Movie m = movieItems.get(position);
        VideoURL=m.getvideoUrl();
        videoview.setVideoURI(Uri.parse(VideoURL));
        // videoview.setMediaController(new MediaController(this));
        videoview.requestFocus();
        // mSpinner.setVisibility(View.GONE);
        videoview.setOnPreparedListener(new OnPreparedListener() {
            // Close the progress bar and play the video
            public void onPrepared(MediaPlayer mp) {
                //pDialog.dismiss();
                mSpinner.setVisibility(View.GONE);
                videoview.start();
            }
        });

        //videoview.setLayoutParams(new FrameLayout.LayoutParams(550,550));

        //    videoview.start();

        // Execute StreamVideo AsyncTask

        //mSpinner.setVisibility(View.VISIBLE);

        //play video

        // Start the MediaController

        //mediacontroller.setAnchorView(videoview);
        // Get the URL from String VideoURL
        //  Uri video = Uri.parse(VideoURL);
        //videoview.setMediaController(mediacontroller);
        //  videoview.setVideoURI(video);

        //videoview.requestFocus();

        // Close the progress bar and play the video

        //videoview.start();

        // getting movie data for the row

        // thumbnail image
        thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader);

        // title
        title.setText(m.getTitle());

        // rating
        rating.setText(m.getDate());

        //desc.setText(m.getdesc());
        // release year
        year.setText(String.valueOf(m.getYear()));

        return convertView;
    }
}

Comment: Do you mean - [Pull to Refresh](https://github.com/erikwt/PullToRefresh-ListView)?
Comment: No i think you mean infinite scroll ?
Comment: yes when i goto last list of list its automatically load next 5post
Comment: i dont know how to say it
Answer: Listviews have a listener used to check the position of the scroll. The following code will help you to check if you are at the end of your ListView.
First make your Activity of Fragment implements OnScrollListener. Then add
private int preLast;
// Initialization stuff.
yourListView.setOnScrollListener(this);

@Override
public void onScroll(AbsListView lw, final int firstVisibleItem,
             final int visibleItemCount, final int totalItemCount) {

switch(lw.getId()) {
    case R.id.yourIDListview:

       final int lastItem = firstVisibleItem + visibleItemCount;
       if(lastItem == totalItemCount) {
          if(preLast!=lastItem){ //to avoid multiple calls for last item
            //LOAD MORE ITEMS
            preLast = lastItem;
          }
       }
   }
}

Answer: Here is my approach :
I catch the onScroll of the ListView and load more item if it's needed.
In my case i load more if i scroll to the half of the product seen
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
    if ((task == null || task.getStatus() == AsyncTask.Status.FINISHED) && productHolder.hasProductRemainsToBeLoad() &&
            productHolder.getProducts().size() - (Config.PRODUCT_NUMBER_PER_PAGE/2) < firstVisibleItem + visibleItemCount){
        loadProduct();
    }
}

Here task is an Asynctask who call a webservice.
Then notify your adapter
adapter.notifyDataSetChanged();
Comment: can i explain it more please
Comment: 1 : catch the scroll of your listview : findViewById(R.id.listViewProduct).setOnScrollListener(this); 2 : Call your webservice if needed into the onScroll 3 : add your data to the list use in your adapter. 4 : notify your adapter that the data was changed
Comment: and when my app load it start to play all videos but i want to play one video that now shown on the screen
Comment: The trick is on the activity, fragment or view not in the Adapter. PS : If you have more question please fill free to an ask other question (about video player).
Answer: You can achieve it using OnScrollListener.
 listview.setOnScrollListener(new OnScrollListener(){

             @Override
             public void onScroll(AbsListView view,int firstVisibleItem, int visibleItemCount,int totalItemCount) {
                //Algorithm to check if the last item is visible or not
                final int lastItem = firstVisibleItem + visibleItemCount;
                if(lastItem == totalItemCount){
                    // you have reached end of list, load more data
                    //Toast.makeText(getApplicationContext(), "You have reached last item!", Toast.LENGTH_SHORT).show();
                    //Sent_details.clear();
                    //In here give a call to database and take another 5 posts and notify the listview
                    //adapter.notifyDataSetChanged();

                }
             }

             @Override
             public void onScrollStateChanged(AbsListView view,int scrollState) {
                //blank, not using this
             }
            });

Comment: thank you and is there any idea to found which list is shown on the screen
Comment: I'm not sure, Let's say you have 2 listviews on same activity, Create one object for both and before showing one listview, assign that id to the created object, using this you can use one object instead of two and u can easily find the current listview
Comment: or if we have able to store current list id to any local variable
Comment: Yes you can do it in that way also.. When you are updating the listview, put a if condition and check what listview is currently showing.


Undefined variable: total still getting error after $total = 0;

Question: I'm getting this problem in PHP, when im getting the median and mean, but when the program reaches the mode it displays the error: Undefined variable: total.
I tried declaring $total = 0; at the beginning of the function but it doesn't solve the problem.
this is my code:
<?php
$number = ($_POST["name"]);
function mmmr($number, $output = \'mean\.'){
$total = 0;
if(!is_array($number)){
    return FALSE;
}else{
    switch($output){
        case \'mean\.':
            $count = count($number);
            $sum = array_sum($number);
            $total = $sum, $count;
        break;
        case \'median\.':
            rsort($number);
            $middle = round(count($number)  2);
            $total = $number[$middle-1];
        break;
        case \'mode\.':
            $v = array_count_values($number);
            arsort($v);
            foreach($v as $k => $v){$total = $k; break;}
        break;
        case \'range\.':
            sort($number);
            $sml = $number[];
            rsort($number);
            $lrg = $number[];
            $total = $lrg - $sml;
        break;
    }
    return $total;
    }
    }

   Mean = The average of all the numbers
   echo \'Mean: \.'.mmmr($number).\'
    \.';
   echo \'Mean: \.'.mmmr($number, \'mean\.').\'
    \.';

     Median = The middle value after the numbers are sorted smallest to largest
     echo \'Median: \.'.mmmr($number, \'median\.').\'
     \.';

      Mode = The number that is in the array the most times
        echo \'Mode: \.'.mmmr($number, \'mode\.').\'
      \.';

    Range = The difference between the highest number and the lowest number
    echo \'Range: \.'.mmmr($number, \'range\.');
  ?>

Answer: You have many syntax error at here
You can try:
$number = [1,2,3,5];

function mmmr($number, $output = 'mean.') {
    $total = 0;
    if (!is_array($number)) {
        return FALSE;
    } else {
        switch ($output) {
            case 'mean.':
                $count = count($number);
                $sum = array_sum($number);
                $total = $sum+ $count;
                break;
            case 'median.':
                rsort($number);
                $middle = round(count($number), 2);
                $total = $number[$middle - 1];
                break;
            case 'mode.':
                $v = array_count_values($number);
                arsort($v);
                foreach ($v as $k => $v) {
                    $total = $k;
                    break;
                }
                break;
            case 'range.':
                sort($number);
                $sml = $number[0];
                rsort($number);
                $lrg = $number[0];
                $total = $lrg - $sml;
                break;
        }
        return $total;
    }
}

echo 'Mean: .' . mmmr($number) . '
    .';
echo 'Mean: .' . mmmr($number, 'mean.') . '
    .';

echo 'Median: .' . mmmr($number, 'median.') . '
     .';

echo 'Mode: .' . mmmr($number, 'mode.') . '
      .';

echo 'Range: .' . mmmr($number, 'range.');

Comment: What should I do with the line?
Comment: I don't know what do you want to use $total, but it is syntax error.   $total = $sum+ $count; or   $total = $sum; or   $total = $count;
Comment: Nope, still having error on line 23, right before the  'case \'range\.':'
Comment: Because you can't use $sml = $number[] to assign you can check my test code on the above


How to access buttons in a separate HTML file in the HTML file it is included in as header?

Question: I'm making an application which requires a header that consist of navigation buttons. I need to access these buttons at the respective home screen where this header html is included in.
However, when I try to access these buttons, they won't do anything -even though I've got an if-statement which calls for all of these buttons when pressed.
I've tried separating the header.html to see if it works as a normal page -which it does. It only doesn't work when it is included as a header.
The HTML of the header:
<form method="POST">
        {% csrf_token %}

            <button type="submit" name="vergelijken" value="vergelijken">Vergelijken</button>

            <button type="submit" name="dag" value="dag">Dag</button>

            <button type="submit" name="week" value="week">Week</button>

            <button type="submit" name="maand" value="maand">Maand</button>

            <button type="submit" name="jaar" value="jaar">Jaar</button>

            <button type="submit" name="live" value="live">Live</button>
            {% load static %}

    </form>

The django code:

def header(request):
    global keuze
    if request.method == "POST":
        if request.POST.get('vergelijken'):
            print('hallo')
            return HttpResponseRedirect('/vergelijk/')
        elif request.POST.get('dag'):
            keuze = 'dag'
        elif request.POST.get('week'):
            keuze = 'week'
        elif request.POST.get('maand'):
            keuze = 'maand'
        elif request.POST.get('jaar'):
            keuze = 'jaar'
        elif request.POST.get('live'):
            keuze = 'live'
    return render(request, 'header.html')

I need these if statements in the django code to work in when the template is being used as an include in the base.html page. Currently the buttons and everything are visible, but not functional as an included page. However, when the page is used as a normal webpage, these buttons work just fine.
Answer: Your form does not have an action attribute. So it will post back to the view that rendered the page, instead of to the header view.
You need to define a URL that points to your header view, and use action="{% url "header"}" to point to it.
Note also, you must not under any circumstances use global variables like that.
Comment: Hi Daniel! thanks for your response, however its not really what im looking for. Only 1 of those buttons (vergelijken) is a redirect to another page. the rest of the buttons are modifications for the page the header.html is included in.
Comment: I don't really understand what that means. If you want to modify the page you're on without reloading, then you need JavaScript, so your view wouldn't be involved at all.
Comment: Alright well, those buttons under "vergelijken" are suppose to change the back end data my application uses to create some graphs and heatmaps. So its suppose to refresh the page, however it wont pass anything to the header function i have in my views when i press a button in the actual page. Hopefully this makes a bit more sense.
Comment: But that view does not even render anything to do with graphs and heatmaps. It just renders the header again. So this approach doesn't seem to make sense at all. Anyway, like I say, there is no "passing to the header function"; views are called by URLs, if your form does not post to the URL associated with the header view then the view will not be called.
Answer: Well i found out what the problem was. Apparently when you include a HTML file into another, you can call for the buttons of the foreign html file in the file it is called into. So i was trying to make a separate def for this included HTML file, turns out this wasn't necessary and could just use the def of the HTML file the foreign file is imported in.


inclusion of sets and inverse function

Question: Is it true that for any function $f$, and sets $S_1,S_2$ such that  $f:S_1\rightarrow S_2$, if $g$ is the inverse of sets in $S_2$, then $f(g[S_2])\subseteq S1\subseteq g(f[S_1])$? If yes, is there a proof for this statement and if no, is there some counter example?
Answer: Hints: $f$ must one-to-one for the inverse function to exist. Consider what happens if it is onto $S_2$ or not. (See Bijection, injection, surjection)

inclusion of sets and inverse function


The centralizer of a sylow subgroup of a finite group

Question: Let $G$ be a finite group and $R \leq G$ such that $R$ is not normal in $G$. Let $R \leq N_G(R) \leq T$, where $T$ is a maximal subgroup of $G$. If $T$ is abelian, then why $C_G(R)=T$?
Answer: Since $T$ is abelian and $R \subseteq T$, we clearly have $T \subseteq C_G(R)$. We have that $R$ is normal in $C_G(R)$, so $C_G(R)$ is not $G$. Because $T$ is a maximal subgroup, we have to have $C_G(R) = T$. Note that it was not important that $R$ was a Sylow subgroup. Every subgroup of $T$ which is not normal in $G$ has this property.
Comment: can you explain me why $T \subseteq C_G(R)$ please?
Comment: $T$ is abelian, so every element in $T$ commutes with every element in $T$. Since $R \subseteq T$, every element of $T$ commutes with every element of $R$, thus $T \subseteq C_G(R)$.


How to change schema name from the flyway sql script file dynamically while generating build

Question: In my project, there are several flyway migration sql script file. Now my project's database name has been changed so if i will change the database name in all the file then it will throw error such like -
Caused by: javax.ejb.EJBException: org.flywaydb.core.api.FlywayException: Validate failed: Migration checksum mismatch for migration 2018.12.10.132421584
-> Applied to database : 988067673
-> Resolved locally : -1477366160
So How to change the database name without modifying the flyway sqlm script file?
Answer: You can run your migration in loop and change the database by passing it for each migration, i know this is the low performance approach but it should work.


Given a BST and its root, print all sequences of nodes which give rise to the same bst

Question: Given a BST, find all sequences of nodes starting from root that will essentially give the same binary search tree.
Given a bst, say
  3
 /  \
1    5

the answer should be 3,1,5 and 3,5,1.
another example
       5
     /   \
    4     7
   /     / \
  1     6   10

the outputs will be
5,4,1,7,6,10
5,4,7,6,10,1
5,7,6,10,4,1
etc
The invariant here however is that the parent's index must always be lesser than its children. I am having difficulty implementing it.
Comment: make it clear. you mean no of binary tree representation for given nodes?
Comment: Possible duplicate of [Find number of permutations of a given sequence of integers which yield the same binary search tree](https://stackoverflow.com/questions/1701612/find-number-of-permutations-of-a-given-sequence-of-integers-which-yield-the-same)
Answer: I assume you want a list of all sequences which will generate the same BST.
In this answer, we will use Divide and Conquer. We will create a function findAllSequences(Node *ptr) which takes a node pointer as input and returns all the distinct sequences which will generate the subtree hanging from ptr. This function will return a Vector of Vector of int, i.e. vector<vector<int>> containing all the sequences.
The main idea for generating sequence is that root must come before all its children.
Algorithm:
Base Case 1:
If ptr is NULL, then return a vector with an empty sequence.
if (ptr == NULL) {
    vector<int> seq;
    vector<vector<int> > v;
    v.push_back(seq);
    return v;
}

Base Case 2:
If ptr is a leaf node, then return a vector with a single sequence. Its Trivial that this sequence will contain only a single element, i.e. value of that node.
if (ptr -> left == NULL && ptr -> right == NULL) {
    vector<int> seq;
    seq.push_back(ptr -> val);
    vector<vector<int> > v;
    v.push_back(seq);
    return v;
}

Divide Part (this part is very simple.)
We assume that we have a function that can solve this problem, and thus we solve it for left sub tree and right sub tree.
vector<vector<int> > leftSeq  = findAllSeq(ptr -> left);
vector<vector<int> > rightSeq = findAllSeq(ptr -> right);

Merging the two solutions.(The crux is in this step.)
Till now we have two set containg distinct sequences:
i. leftSeq  - all sequences in this set will generate left subtree.
ii. rightSeq - all sequences in this set will generate right subtree.

Now each sequence in left subtree can be merged with each sequence of right subtree. While merging we should be careful that the relative order of elements is preserved. Also in each of the merged sequence  we will add the value of current node in the beginning beacuse root must come before all children.
Pseudocode for Merge
vector<vector<int> > results
for all sequences L in leftSeq
    for all sequences R in rightSeq
        create a vector flags with l.size() 0's and R.size() 1's
        for all permutations of flag
            generate the corresponding merged sequence.
            append the current node's value in beginning
            add this sequence to the results.

return results.

Explanation: Let us take a sequence, say L(of size n) from the set leftSeq, and a sequence, say R(of size m) from set rightSeq.
Now these two sequences can be merged in m+nCn ways!
Proof: After merging, the new sequence will have m + n elements. As we have to maintain the relative order of elements, so firstly we will fill all n the elements from L in any of n places among total (m+n) places. After that remaining m places can be filled by elements of R. Thus we have to choose n places from (m+n) places.
To do this, lets create take a Boolean vector, say flags and fill it with n 0's and m 1's.A value of 0 represents a member from left sequence and a value of 1 represents member from right sequence. All what is left is to generate all permutations of this flags vector, which can be done with next_permutation. Now for each permutation of flags we will have a distinct merged sequence of L and R.
eg: Say L={1, 2, 3} R={4, 5}
        so, n=3 and m=2
thus, we can have 3+2C3 merged sequences, i.e. 10.
1.now, Initially flags = {0 0 0 1 1}, filled with 3 0's and 2 1's
this will result into this merged sequence: 1 2 3 4 5
2.after calling nextPermutation we will have
flags = {0 0 1 0 1}
and this will generate sequence: 1 2 4 3 5
3.again after calling nextPermutation we will have
flags = {0 0 1 1 0}
ans this will generate sequence: 1 2 4 5 3and so on...
Code in C++
vector<vector<int> > findAllSeq(TreeNode *ptr)
{
    if (ptr == NULL) {
        vector<int> seq;
        vector<vector<int> > v;
        v.push_back(seq);
        return v;
    }

    if (ptr -> left == NULL && ptr -> right == NULL) {
        vector<int> seq;
        seq.push_back(ptr -> val);
        vector<vector<int> > v;
        v.push_back(seq);
        return v;
    }

    vector<vector<int> > results, left, right;
    left  = findAllSeq(ptr -> left);
    right = findAllSeq(ptr -> right);
    int size = left[0].size() + right[0].size() + 1;

    vector<bool> flags(left[0].size(), 0);
    for (int k = 0; k < right[0].size(); k++)
        flags.push_back(1);

    for (int i = 0; i < left.size(); i++) {
        for (int j = 0; j < right.size(); j++) {
            do {
                vector<int> tmp(size);
                tmp[0] = ptr -> val;
                int l = 0, r = 0;
                for (int k = 0; k < flags.size(); k++) {
                    tmp[k+1] = (flags[k]) ? right[j][r++] : left[i][l++];
                }
                results.push_back(tmp);
            } while (next_permutation(flags.begin(), flags.end()));
        }
    }

    return results;
}

Update 3rd March 2017: This solution wont work perfectly if original tree contains duplicates.
Comment: What if I would just like to count the number of such sequences, ie. results.size(), and not enumerate them? Would it be able to scale up to N=50, ie. 50 ints?
Comment: @Atul do you think `vector> ` return all sequences of the subtree as you are initialising a new one on every call.
Comment: @Rahul Yes. This works because it is a recursive solution
Answer: Here is a clear, concise and well-documented solution that I wrote for you in Python 3.  I hope it helps you!
Code: bst_sequences.py
from binarytree import bst, Node

def weave_lists(first: list, second: list, results: list, prefix: list) -> None:
    """Recursively Weave the first list into the second list and append
    it to the results list.  The prefix list grows by an element with the
    depth of the call stack.  Ultimately, either the first or second list will
    be exhausted and the base case will append a result."""
    # base case
    if not first or not second:
        results.append(prefix + first + second)
        return

    # recursive case
    first_head, first_tail = first[0], first[1:]
    weave_lists(first_tail, second, results, prefix + [first_head])

    second_head, second_tail = second[0], second[1:]
    weave_lists(first, second_tail, results, prefix + [second_head])

def all_sequences(root: Node) -> list:
    """Splits the tree into three lists: prefix, left, and right."""
    if root is None:
        return []

    answer = []
    prefix = [root.value]
    left = all_sequences(root.left) or [[]]
    right = all_sequences(root.right) or [[]]

    # At a minimum, left and right must be a list containing an empty list
    # for the following nested loop
    for i in range(len(left)):
        for j in range(len(right)):
            weaved = []
            weave_lists(left[i], right[j], weaved, prefix)
        answer.extend(weaved)

    return answer

if __name__ == "__main__":
    t = bst(2)
    print(t)
    solution = all_sequences(t)
    for e, item in enumerate(solution):
        print(f"{e:03}: {item}")

Sample Output
    __4
   /   \
  1     5
 / \     \
0   2     6

000: [4, 1, 0, 2, 5, 6]
001: [4, 1, 0, 5, 2, 6]
002: [4, 1, 0, 5, 6, 2]
003: [4, 1, 5, 0, 2, 6]
004: [4, 1, 5, 0, 6, 2]
005: [4, 1, 5, 6, 0, 2]
006: [4, 5, 1, 0, 2, 6]
007: [4, 5, 1, 0, 6, 2]
008: [4, 5, 1, 6, 0, 2]
009: [4, 5, 6, 1, 0, 2]
010: [4, 1, 2, 0, 5, 6]
011: [4, 1, 2, 5, 0, 6]
012: [4, 1, 2, 5, 6, 0]
013: [4, 1, 5, 2, 0, 6]
014: [4, 1, 5, 2, 6, 0]
015: [4, 1, 5, 6, 2, 0]
016: [4, 5, 1, 2, 0, 6]
017: [4, 5, 1, 2, 6, 0]
018: [4, 5, 1, 6, 2, 0]
019: [4, 5, 6, 1, 2, 0]

Process finished with exit code 0

Comment: This looks like a pretty exact replica of the solution from CTCI I would suggest citing your sources if that is the case :)
Comment: You should mention that you lifted the code from Cracking the Coding Interview chapter 4 instead of claiming that you wrote it.
Answer: Note that the question is actually about topological sorting of a tree: find all the possible ways to perform topological sort. That is, we don't care about the specific way the tree was built, what's important is that elements are always added as leaves, never changing the structure of existing nodes. The constraint on the output is that nodes never precede their ancestors - treating the tree as a classic dependency graph.
But unlike topological sort for a general DAG, there's no need for reference counting here, since this is a tree - the number of references is always 1 or 0.
Here's a simple Python implementation:
    def all_toposorts_tree(sources, history):
        if not sources:
            print(history)
            return
        for t in sources:
            all_toposorts((sources - {t}) | {t.left, t.right} - {None}, history + [t.v])

    all_toposorts_tree({root}, [])

This is question 4.9 in Cracking the Coding Interview, 6th Edition.
Answer: I have a much shorter solution. What do you think about it?
function printSequences(root){
    let combinations = [];

    function helper(node, comb, others){
        comb.push(node.values);

        if(node.left) others.push(node.left);
        if(node.right) others.push(node.right);

        if(others.length === 0){
            combinations.push(comb);
            return;
        }else{
            for(let i = 0; i<others.length; i++){
                helper(others[i], comb.slice(0), others.slice(0, i).concat(others.slice(i+1, others.length)));
            }
        }
    }

    helper(root, [], []);
    return combinations;
}

Answer: well here is my python code which does producing all sequences of elements/numbers for same BST.
for the logic i referred to the book  cracking the coding interview by Gayle Laakmann Mcdowell
from binarytree import  Node, bst, pprint

def wavelist_list(first, second, wave, prefix):
    if first:
       fl = len(first)
    else:
       fl = 0

    if second:
        sl = len(second)
    else:
       sl = 0
    if fl == 0 or sl == 0:
       tmp = list()
       tmp.extend(prefix)
       if first:
          tmp.extend(first)
       if second:
          tmp.extend(second)
       wave.append(tmp)
       return

    if fl:
        fitem = first.pop(0)
        prefix.append(fitem)
        wavelist_list(first, second, wave, prefix)
        prefix.pop()
        first.insert(0, fitem)

    if sl:
        fitem = second.pop(0)
        prefix.append(fitem)
        wavelist_list(first, second, wave, prefix)
        prefix.pop()
        second.insert(0, fitem)

def allsequences(root):
    result = list()
    if root == None:
       return result

    prefix = list()
    prefix.append(root.value)

    leftseq = allsequences(root.left)
    rightseq = allsequences(root.right)
    lseq = len(leftseq)
    rseq = len(rightseq)

    if lseq and rseq:
       for i in range(lseq):
          for j in range(rseq):
            wave = list()
            wavelist_list(leftseq[i], rightseq[j], wave, prefix)
            for k in range(len(wave)):
                result.append(wave[k])

    elif lseq:
      for i in range(lseq):
        wave = list()
        wavelist_list(leftseq[i], None, wave, prefix)
        for k in range(len(wave)):
            result.append(wave[k])

    elif rseq:
      for j in range(rseq):
        wave = list()
        wavelist_list(None, rightseq[j], wave, prefix)
        for k in range(len(wave)):
            result.append(wave[k])
   else:
       result.append(prefix)

   return result

if __name__=="__main__":
    n = int(input("what is height of tree?"))
    my_bst = bst(n)
    pprint(my_bst)

    seq = allsequences(my_bst)
    print("All sequences")
    for i in range(len(seq)):
        print("set %d = " %(i+1), end="")
        print(seq[i])

 example output:
 what is height of tree?3

       ___12
      /     \
  __ 6       13
 /   \        \
 0     11       14
  \
   2

  All sequences
  set 1 = [12, 6, 0, 2, 11, 13, 14]
  set 2 = [12, 6, 0, 2, 13, 11, 14]
  set 3 = [12, 6, 0, 2, 13, 14, 11]
  set 4 = [12, 6, 0, 13, 2, 11, 14]
  set 5 = [12, 6, 0, 13, 2, 14, 11]
  set 6 = [12, 6, 0, 13, 14, 2, 11]
  set 7 = [12, 6, 13, 0, 2, 11, 14]
  set 8 = [12, 6, 13, 0, 2, 14, 11]
  set 9 = [12, 6, 13, 0, 14, 2, 11]
  set 10 = [12, 6, 13, 14, 0, 2, 11]
  set 11 = [12, 13, 6, 0, 2, 11, 14]
  set 12 = [12, 13, 6, 0, 2, 14, 11]
  set 13 = [12, 13, 6, 0, 14, 2, 11]
  set 14 = [12, 13, 6, 14, 0, 2, 11]
  set 15 = [12, 13, 14, 6, 0, 2, 11]
  set 16 = [12, 6, 0, 11, 2, 13, 14]
  set 17 = [12, 6, 0, 11, 13, 2, 14]
  set 18 = [12, 6, 0, 11, 13, 14, 2]
  set 19 = [12, 6, 0, 13, 11, 2, 14]
  set 20 = [12, 6, 0, 13, 11, 14, 2]
  set 21 = [12, 6, 0, 13, 14, 11, 2]
  set 22 = [12, 6, 13, 0, 11, 2, 14]
  set 23 = [12, 6, 13, 0, 11, 14, 2]
  set 24 = [12, 6, 13, 0, 14, 11, 2]
  set 25 = [12, 6, 13, 14, 0, 11, 2]
  set 26 = [12, 13, 6, 0, 11, 2, 14]
  set 27 = [12, 13, 6, 0, 11, 14, 2]
  set 28 = [12, 13, 6, 0, 14, 11, 2]
  set 29 = [12, 13, 6, 14, 0, 11, 2]
  set 30 = [12, 13, 14, 6, 0, 11, 2]
  set 31 = [12, 6, 11, 0, 2, 13, 14]
  set 32 = [12, 6, 11, 0, 13, 2, 14]
  set 33 = [12, 6, 11, 0, 13, 14, 2]
  set 34 = [12, 6, 11, 13, 0, 2, 14]
  set 35 = [12, 6, 11, 13, 0, 14, 2]
  set 36 = [12, 6, 11, 13, 14, 0, 2]
  set 37 = [12, 6, 13, 11, 0, 2, 14]
  set 38 = [12, 6, 13, 11, 0, 14, 2]
  set 39 = [12, 6, 13, 11, 14, 0, 2]
  set 40 = [12, 6, 13, 14, 11, 0, 2]
  set 41 = [12, 13, 6, 11, 0, 2, 14]
  set 42 = [12, 13, 6, 11, 0, 14, 2]
  set 43 = [12, 13, 6, 11, 14, 0, 2]
  set 44 = [12, 13, 6, 14, 11, 0, 2]
  set 45 = [12, 13, 14, 6, 11, 0, 2]

Comment: for the above code I have used binary tree package to create the BST of given length.
Answer: here is another concise recursion based easy to understand solution:
from binarytree import  Node, bst, pprint

def allsequences1(root):
    if not root:
        return None
    lt = allsequences1(root.left)
    rt = allsequences1(root.right)
    ret = []
    if not lt and not rt:
        ret.append([root])
    elif not rt:
        for one in lt:
            ret.append([root]+one)
    elif not lt:
        for two in rt:
            ret.append([root]+two)
    else:
        for one in lt:
            for two in rt:
                ret.append([root]+one+two)
                ret.append([root]+two+one)
    return ret

if __name__=="__main__":
    n = int(input("what is height of tree?"))
    my_bst = bst(n)
    pprint(my_bst)
    seg = allsequences1(my_bst)
    print("All sequences ..1")
    for i in range(len(seq)):
        print("set %d = " %(i+1), end="")
        print(seq[i])

Comment: Could you please add some comments or share a few words about what you're trying to do? Thanks :)
Answer: Let's first observe what must be be followed to create the same BST. The only sufficient rules here is insert parent before their left and right children. Because, if we can guarantee that for some node (that we are interested to insert) all parents (including grand parent) are inserted but none of it's children are inserted, than the node will find its appropriate place to be inserted.
Following this observation we can write backtrack to generate all sequence that will produce same BST.
active_list = {root}
current_order = {}
result ={{}}
backtrack():
     if(len(current_order) == total_node):
         result.push(current_order)
         return;
     for(node in active_list):
          current_order.push(node.value)

          if node.left :
               active_list.push(node.left)
          if node.right:
               active_list.push(node.right)

          active_list.remove(node)
          backtrack()
          active_list.push(node)

          if node.left :
               active_list.remove(node.left)
          if node.right:
               active_list.remove(node.right)
          current_order.remove(node.val)

This is not working implementation. used just for illustration purpose.
Answer:
public class Solution {
    ArrayList<LinkedList<Long>> result;
    /*Return the children of a node */
    ArrayList<TreeNode> getChilden(TreeNode parent) {
        ArrayList<TreeNode> child = new ArrayList<TreeNode>();
        if(parent.left != null) child.add(parent.left);
        if(parent.right != null) child.add(parent.right);
        return child;
    }
    /*Gets all the possible Compinations*/
    void getPermutations(ArrayList<TreeNode> permutations, LinkedList<Long> current) {
        if(permutations.size() == 0) {
            result.add(current);
            return;
        }
        int length = permutations.size();
        for(int i = 0; i < length; i++) {
            TreeNode node = permutations.get(i);
            permutations.remove(i);
            ArrayList<TreeNode> newPossibilities = new ArrayList<TreeNode>();
            newPossibilities.addAll(permutations);
            newPossibilities.addAll(getChilden(node));
            LinkedList<Long> newCur = new LinkedList<Long>();
            newCur.addAll(current);
            newCur.add(node.val);
            getPermutations(newPossibilities, newCur);
            permutations.add(i,node);
        }
    }

    /*This method returns a array of arrays which will lead to a given BST*/
    ArrayList<LinkedList<Long>> inputSequencesForBst(TreeNode node) {
        result = new ArrayList<LinkedList<Long>>();
        if(node == null)
            return result;
        ArrayList<TreeNode> permutations = getChilden(node);
        LinkedList<Long> current = new LinkedList<Long>();
        current.add(node.val);
        getPermutations(permutations, current);
        return result;
    }
}

My solution. Works perfectly.
Comment: you might need to add some explanation in addition to your code.
Answer: Here's my Python solution with plenty of explanation.
We build each array from left to right by choosing for every position one node out of a set of possible choices for that position. We add the node value to the path, and the children of the node (if any) to the list of possibilities, then recurse further. When there are no further choices we have one candidate array. To generate the rest of the the arrays, we backtrack until we can make a different choice and recurse again.
The catch is to use a suitable data structure for holding the possibilities. A list works, but the node has to be put back in the previous position while backtracking (order matters, since we have added the children of the node which must be visited AFTER the node). Insertion and deletion from a list takes linear time. A set doesn't work since it doesn't maintain order. A dict works best since Python dictionary remembers the insertion order and all operations run in constant time.
def bst_seq(root: TreeNode) -> list[list[int]]:
    def _loop(choices: MutableMapping[TreeNode, bool], path: list[int], result: list[list[int]]) -> None:
        if not choices:
            result.append([*path])
        else:
            # Take a snapshot of the keys to avoid concurrent modification exception
            for choice in list(choices.keys()):
                del choices[choice]
                children = list(filter(None, [choice.left, choice.right]))
                for child in children:
                    choices[child] = False
                path.append(choice.val)
                _loop(choices, path, result)
                path.pop()
                choices[choice] = False
                for child in children:
                    del choices[child]

    result = []
    _loop({root: False}, [], result)
    return result


Unable to upload images on nginx server greater than 6 mb

Question: I am trying to upload images to nginx server. I have changed in php.ini such as
upload_max_filesize = 12M and in nginx.conf such as client_max_body_size = 30M.
i am trying to upload 3 images at a time. If size of 3 image are less than 6mb , images are successfully uploaded but when images are greater than 6mb , it returns only '' and images are not uploaded.
How to solve this issue??
Comment: have you checked post_max_size value in php ?
Comment: I changed post_max_size = 20M but not working
Comment: Do you have timeout? Maybe the proxy timeout settings in nginx needs to be modified ?
Comment: Can you tell me what changes i have to do??
Comment: try change `proxy_send_timeout = 300` and `proxy_read_timeout = 300`  in your nginx settings this means 300 seconds the default is `60`. this if you have apache behind nginx
Comment: if you are using php-fpm (fastcgi) then use these instead `fastcgi_send_timeout` and `fastcgi_read_timeout`
Comment: In which file i have to do changes.. nginx.conf
Comment: In http or server
Comment: add the changes to nginx.conf inside http section
Comment: not working thid
Comment: Then you need to provide the error message that you see in nginx error log and in the browser and add them to your question
Comment: It doen't return error only gives ' '
Answer: you have to look for below settings
<code> upload_max_filesize = 20M
 post_max_size = 21M
</code>
Comment: $this->base64Image = $base64Image;
$this->image_name  = $image_name;
$this->extension = 'png';
$this->ValidateAndUpload();
for($i=0;$i < count($this->uploadDir);$i++)
{
  $image = array(
    "name" => $image_name,
    "path1" => base_path().'/public/products/original/',
    "path" => base_path().'/public/products/'.$this->uploadDir[$i]['folder'].'/',
    "width" => $this->uploadDir[$i]['width'],
    "height" => $this->uploadDir[$i]['height'],
    "compress_ratio" => $this->uploadDir[$i]['compress']
  );
   CompressImage::dispatch($image)->delay(now()->addMinutes(2));
Comment: try uploading single image greater than 6mb. seems base64 encoding has some limit


Como alterar o tamanho da View do Google Map para iOS

Question: Estou utilizando o Google Map SDK for iOS em um projeto, mas ao usar o serviço por padrão ele cobre toda a tela. Porém preciso ter espaço para adicionar alguns botões na tela.
Como posso redimensionar a view do mapa?
No momento usando o código padrão:
<code>GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:latitude
                                                            longitude:longitude
                                                                 zoom:17];
    mapView_ = [GMSMapView mapWithFrame:CGRectZero camera:camera];
    mapView_.myLocationEnabled = YES;

    self.view = mapView_;

    // Creates a marker in the center of the map.
    GMSMarker *marker = [[GMSMarker alloc] init];
    marker.position = CLLocationCoordinate2DMake(latitude, longitude);
    marker.title = nomeCliente;
    marker.snippet = @"Detalhes";
    marker.map = mapView_;
</code>
Com este código fica deste jeito:

Mas preciso que fique assim:
Comment: O MKMapView somente está na imagem para exemplificar. Eu removi assim que fiz o print da tela.
Answer: Para esta questão fiz as seguintes alterações no código:
<code>// Criei uma nova posição e novas dimensões
CGRect rect = CGRectMake(0, 0, 300, 300);

    // Create a GMSCameraPosition that tells the map to display the
    // coordinate -33.86,151.20 at zoom level 6.
    GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:latitude
                                                            longitude:longitude
                                                                 zoom:17];

    // Utilizei a nova posição e dimensão e usei para alterar os valores de mapView_
    mapView_ = [GMSMapView mapWithFrame:rect camera:camera];
    mapView_.myLocationEnabled = YES;

    //self.view = mapView_;

    [self.view addSubview:mapView_];

    // Creates a marker in the center of the map.
    GMSMarker *marker = [[GMSMarker alloc] init];
    marker.position = CLLocationCoordinate2DMake(latitude, longitude);
    marker.title = nomeCliente;
    marker.snippet = @"Detalhes";
    marker.map = mapView_;
</code>
Embora eu mesmo tenha conseguido resolver, de maneira rápida, fiz a pergunta pois ja tinha feito outros testes e modificações.


Click Button Javascript

Question:
        Following

Trying to click all buttons where rel="nofollow"
javascript:var inputs = document.getElementsByClassName('rel'); for(var i=0; i<inputs.length;i++) { inputs[i].click(); }

^not working, because class name is different for each button, but "rel" stays the same for all buttons.
Comment: $('a[rel=nofollow]').trigger('click'); if you're using jQuery...
Comment: Code:

    Follow

I want to click all the follow buttons, but the number in the class changes. Is there any arguments I can put in after follow_button such as * to ignore the number after? Maybe click everything with the label "Follow" like in the end of the code?

javascript:var inputs = document.getElementsByClassName('class here'); for(var i=0; i<inputs.length;i++) { inputs[i].click(); }
Comment: It shouldn't matter if the number changes, as there seems to be a follow_button class and a follow_button_1234567 class (where the number changes as you say), so if they all have the follow_button class without a number after, can't you just select using that ($('.follow_button').trigger('click'))? If you want to select by the Follow text (strange, but ok) you can do $('a:contains("Follow")').trigger('click'); BTW, if you have different requirements, you should post those in the original question.
Answer: Here's a javascript only solution. It is supported in modern browsers only. However, appx 95% of browsers fully support it.
Added in the ability to check if the string "follow_button" exists in the class before clicking.
javascript:var inputs = document.querySelectorAll("[rel='nofollow']");
for (var i=0; i<inputs.length;i++) {
    if (inputs[i].className.indexOf("follow_button") > -1) {
        inputs[i].click();
    }
}

Comment: Second question.

Code:

Follow

Add Friend

I want to only click the follow buttons, but # changes in class.
Comment: The class for the follow button is "button follow_button follow_button_3854378 green"
Comment: The issue is, the number in that class changes, Is there a way to click all buttons in that class with an argument: "button follow_button *"??
Comment: Follow

Or click everything with the label "Follow".
Comment: @ArturasRosenbacher updated to include a class selector. I only had it select on `"follow_button"` since the order of `"button follow_button"` may be out of order. `"follow_button"` should be unique enough from what I'm seeing to select what you want.
Answer: Using JQuery you can do it by this way (I added an id, so when you click over some link, the current id is logged in the console, add you custom code here, call a function, etc):
Supose more than one link:

    Following

    Following

The with Jquery, you can obtain the current clicked link with this:
$(".follow_form").on("click", "[id^=follow_button_]", function() {
    console.log("Link pressed: " + $(this).attr("id"));
});

Look in this: http://jsfiddle.net/c2j9toLy/
Comment: Code:

    Follow

I want to click all the follow buttons, but the number in the class changes. Is there any arguments I can put in after follow_button such as * to ignore the number after? Maybe click everything with the label "Follow" like in the end of the code?

javascript:var inputs = document.getElementsByClassName('class here'); for(var i=0; i<inputs.length;i++) { inputs[i].click(); }
Comment: We this approach you can't, but try to add the follow_button_"the number" like an id. Then you can follow this apporach. I update the code in the answer
Comment: For comment, think that an id have to be an unique identifier, and a class is supposed to be reused in a lot of tags.

Click Button Javascript


Epsilon delta proof of nested sine function

Question: I know that $\lim_{x->0}f(x)=\pi$ and $\lim_{x->\pi}\sin(x)=0$.
I have to prove that $\lim_{x->\pi}f(\sin(x))=\pi$ using the epsilon delta proof.
My idea was to use the value of $\delta=MAX(\delta_1,\delta_2)$ where $0<|x|<\delta_1$ and $0<|x-\pi|<\delta_2$. Then $|f(x)-\pi|<\epsilon$ and $|\sin(x)|<\epsilon$.
Let $\epsilon>0$ and take $\delta=MAX(\delta_1,\delta_2)$.
Assume $0<|\sin(x)-\pi|<\delta$. Then $|f(x)-\pi|<\epsilon$ and $|\sin(x)|<\epsilon$. Can I from that somehow conclude that $|f(\sin(x))-\pi|<\epsilon$?
Comment: In your first sentence, did you mean, I know that $\lim_{x->0}f(x)=\pi$ and $\lim_{x->0}\sin(x)=0\ $ ?
Comment: I think what I wrote is right
Comment: $\lim_{x->\pi}\sin(x)=0$ is true but irrelevant to the question. $\lim_{x->0}\sin(x)=0$ is relevant to the question.
Answer: Assuming what was meant was: We are given that $\lim_{x\to0}f(x)=\pi$ and $\lim_{x\to0}\sin(x)=0.$
$\lim_{x\to0}f(x)=\pi\ $ means that: given $\varepsilon>0,\ \exists\ \delta>0$ such that $x\in (-\delta, \delta)\implies f(x)-\pi\in (-\varepsilon, \varepsilon).\ (1)$
$\lim_{x\to0}\sin(x)=0\ $ means that: given $\varepsilon'>0,\ \exists\ \delta'>0$ such that $x\in (-\delta', \delta')\implies \sin x\in (-\varepsilon', \varepsilon').\ (2)$
$$$$
Propoition: $\lim_{x\to0}f(\sin(x))=\pi.\ $ Proof: Let $\varepsilon>0.$ Then from $(1),$ there exists $\delta>0$ such that $u\in (-\delta, \delta)\implies f(u)-\pi\in (-\varepsilon, \varepsilon).$ Since $\sin$ is a function that inputs and outputs real values only, this implies that: $u=\sin x\in (-\delta, \delta)\implies f(\sin x)-\pi\in (-\varepsilon, \varepsilon).$ From $(2),$ there exists $\delta'>0$ such that $x\in (-\delta', \delta')\implies \sin x\in (-\delta, \delta),\ $ but from the previous sentence, this implies that $f(\sin x)-\pi\in (-\varepsilon, \varepsilon).$ This completes the proof.
Comment: I think the part that confused me the most was "Since sin is a function that outputs real values, this implies that:  $\sin x\in (-\delta, \delta)\implies f(\sin x)-\pi\in (-\varepsilon, \varepsilon).$ Is that always true?
Comment: What makes you think it isn't true?
Comment: Updated my answer. Does it make any more sense now?
Answer: Let $\varepsilon>0$ be fixed. Since $f(x)\to\pi$ as $x\to 0$, there is some $\delta'>0$ such that
$$\left|f(x)-\pi\right|<\varepsilon$$
whenever $\left|x\right|<\delta'$. Similarly, since $\sin(x)\to0$ as $x\to\pi$, there is some $\delta>0$ such that
$$\left|\sin(x)\right|<\delta'$$
whenever $\left|x-\pi\right|<\delta$. Combining these we notice that we have the implications
$$\left|x-\pi\right|<\delta \implies \left|\sin(x)\right|<\delta' \implies \left|f(\sin(x))-\pi\right|<\varepsilon.$$
Thus
$$\left|f(\sin(x))-\pi\right|<\varepsilon$$
whenever $\left|x-\pi\right|<\delta$, which proves the assertion.


Case n=2 in boundedness of subelliptic operator (Gilbarg-Trudinger Theorem 8.15)

Question: Theorem 8.15. along with relevant inequalities below.
It have two questions about the proof. First, how do we know that $H(w) \in W^{1,2}_0(\Omega)$? Wouldn't we need some bounds on $\beta\ge 1$?
Other than this, I followed the proof for the case where $n \ge 3$. However, if $n=2$, I get a little lost. If $n>2$, then the Sobolev inequality states that $W_0^{1,2}(\Omega)$ is embedded in $L^{\frac{2n}{n-2}}(\Omega)$. However, for $n=2$ this result is not valid. Therefore, I don't see how to obtain
$$
\lVert H(w) \rVert_{\frac{2\cdot \hat{2}}{\hat{2}-2}} \le C\left(\int_\Omega \overline{b}\left(w H^\prime(w)\right)^2\,\mathrm{d}x\right)^{1/2}.
$$

Equation 8.3
\begin{equation}
    Lu=D_i(a^{ij}(x)D_ju+b^i(x)u)+c^i(x)D_iu+d(x)u
\end{equation}.
Equation 8.29
\begin{equation}
    \begin{aligned}
        A^i(x,z,p) &= a^{ij}(x)p_j + b^i(x)z - f^i(x),\\
        B(x,z,p) &= c^i(x)p_i + d(x)z - g(x)
    \end{aligned}
\end{equation}
Equation 8.30 For $v\ge 0, v\in C_0^1(\Omega)$
\begin{equation}
     \int_{\Omega}\left(D_ivA^i(x,u,Du)-vB(x,u,Du)\right)dx \le(\ge,=)0
 \end{equation}
Equation 8.32
\begin{equation}
    \bar z=|z|+k,\qquad \bar b=\lambda^{-2}(|b|^2+|c|^2+k^{-2}|f|^2)+\lambda^{-1}(|d|+k^{-1}|g|)
\end{equation}
Equation 8.33
\begin{align}
p_iA^i(x,z,p)  & \ge \frac{\lambda}{2}(|p|^2-2\bar b\bar z^2)  \\
      | \bar zB(x,z,p)  |     &\le \frac{\lambda}{2}\left( \epsilon|p|^2+\frac{\bar b}{\epsilon}\bar z^2\right)
\end{align}
Any help will be greatly appreciated
Answer: First Question: No, we don't need an upper bound on $\beta$. Indeed, we can explicitly write that $H: [k,\infty) \to \mathbb R$ is given by $$H(z) = \begin{cases}
z^\beta - k^\beta, &\text{if } z\in [k,N) \\
\beta N^{\beta-1}(z-N)+(N^\beta-k^\beta), &\text{if } z \geqslant N.
\end{cases} $$ We are able to calculate the value of $H$ in the region $z\geqslant N$ explicitly since we know $H$ is linear in that region and we know that $H$ is continuously differentiable across $z=N$. Hence, $$H'(z) = \begin{cases}
\beta z^{\beta-1}, &\text{if } z\in [k,N) \\
\beta N^{\beta-1}, &\text{if } z \geqslant N,
\end{cases} $$ so $\vert H'(z)\vert \leqslant \beta{N^{\beta-1}}, $ that is, $H'$ is bounded. Since, $w\in W^{1,2}(\Omega)$, we conclude that $H(w) \in W^{1,2}(\Omega)$ by the chain rule in Sobolev spaces. To see that $H(w) \in W^{1,2}_0(\Omega)$, we use that $w=k$ on $\partial \Omega$ in the trace-sense and that $H(k)=0$, so $H(w)=0$ on $\partial \Omega$ in the trace-sense.
Second question: Let $n=2$ and $\hat n \in (2,q)$ be arbitrary. Let  $\alpha:=\frac{2 \hat n}{\hat n -2}$ and note that $\alpha>2$. Now set $p = \frac{2\alpha}{\alpha+2}$ and observe that $p \in (1,2)$ and $$ \frac{2\hat n }{\hat n -2} = \frac{2p}{2-p}.$$ Hence, by the Sobolev inequality, \begin{align*}
\| H(w)\|_{L^{\frac{2\hat n}{2-\hat n}}(\Omega)} &=\| H(w)\|_{L^{\frac{2p}{p-2}}(\Omega)} \leqslant C_\ast(\hat n) \|D (H(w))\|_{L^p(\Omega)}.
\end{align*} Then, using that $p< 2$, by Hölder's inequality, $$\|D (H(w))\|_{L^p(\Omega)} \leqslant \vert \Omega \vert^{\frac 1 p - \frac 1 2}\|D (H(w))\|_{L^2(\Omega)}. $$ Thus, the inequality holds with $C(\hat n , \vert \Omega \vert)=C_\ast(\hat n ) \vert \Omega \vert^{\frac 1 p - \frac 1 2}$ for any $\hat n >2$.
Comment: The text says $2 < \hat{2} < q$, not $\hat{2} \le 2$.
Comment: @JackT Thanks! As pointed out by Thomas, I was assuming $2<\hat{2}<q$. The inequality works for $1<\hat{2}<2$; I will double check that the iteration works out for this $\hat{2}$. I'll accept your answer as soon as I have a chance to convince myself.
Comment: Ha ok we pick $\dot{n} \in [1,2)$. Then, for some $\hat{n}$ as in the book $\frac{2\dot{n}}{2-\dot{n}} = \frac{2\hat{n}}{\hat{n}-2}$ so it works out!
Comment: @Thomas Thanks for pointing out the error
Comment: @Quoka Yes, I agree - I've updated my answer


What is the purpose of accrual period in survival analysis?

Question: Before reading the answer to this question, I, like the original poster, thought that we have to take the accrual period into account because some subjects might die before we start the treatment.
But, according to the answer, this isn't so. The treatment starts as soon as the subject is recruited. Consequently, we can follow the subject and assess the treatment from the very beginning. Why, then, is accrual period relevant at all? Why do I need to specify it when computing the power, e.g. using Hmisc::cpower in R?
Answer: The accrual period doesn't affect power (*with exceptions listed below). It affects when the hypothesis test will be fully powered.
For tests of hazard ratios, power is affected by number of events, not the total sample size. When you design a trial/experiment, you account for the difference between number of events and the total patients recruited. You assume some patients will not have an event during the observation period. So if you need 500 events for a hypothesis test with 80% power, you may recruit 1000 patients and end the trial when 500 events have been observed.
Let's say that if you recruit all patients at the same time you'll observe the required 500 events after 1 year. In reality, patients enter the trial staggered over the accrual period. Patients who joined the trial later will generally have events later. This doesn't* affect the power since patients will have an event at the same relative time in the trial, but the calendar time of the analysis at 500 events will be later.
*In some situations accrual can affect power, but this is due to the day-to-day realities of running a trial/experiment. The power calculation is unaffected by accrual. The Hmisc::cpower function (and the underlying theory) are adjusting for when events happen quickly relative to the accrual period. If one treatment performs poorly and events happen quickly relative to the accrual period, you might reach the required number of events before accrual period ends or before one treatment group is filled. It's also possible to recruit patients with a poor prognosis early in the trial which accelerates the time to reach events and dilutes the treatment effect.


Dreamweaver help needed with regular expression search and replace

Question: I've got a bit of an issue. I have lots of text document I need to copy into html to try and speed the procees up I've been looking into search and replace regular expressions to help me add bold tags to varies bits of text.
I have lots of text like this:
1. Centrum Multimineral Vitamin x 30 £3.19 was £4.79 (11p per tablet)

I'm trying to write a regular expression search and replace to look for all text between a number with a dot and space after it and the first price. I want the find and replace to do this:
1. Centrum Multimineral Vitamin x 30 £3.19 was £4.79 (11p per tablet)

So far I've written this expression which kind of works:
search for:
([0-9]{1}[\.\s][\s\D]?[^<]*)(\£\d\.\d\d[^<])

replace with :
$1$2

Output :
1. Centrum Multimineral Vitamin x 30 £3.19 was £4.79 (11p per tablet)

How do I alter this search so that it stops at the 1st £ sign and includes the price?
Answer: Try this small modification:
([0-9]{1}[\.\s][\s\D]?[^<]*?)(\£\d\.\d\d[^<])
                           ^

I have added ? which makes the asterisk * operator reluctant (lazy) so it reads the input string character by character instead of going all the way to the end, and then backtrack to try to find \£\d\.\d\d[^<].
Comment: @Neb9 You are welcome, please don't forget to accept the answer if it fully solves your problem.
Comment: I dont suppose you know how to get this code working as a command?
Comment: @Neb9 Unfortunately I don't work with Dreamweaver, I just know about regular expressions :)
Comment: Ok, thanks anyway I think I've accepted the answer. I'm very new to this forum.
Comment: @Neb9 OK Thank you. You can check help forum or the faq for all information.


Mysql through ssh often can't connect or timeout

Question: I have a MariaDB server (10.0.12) on a machine (Ubuntu 14.04) that other servers connect to through ssh for security purpose.
The ssh tunnel is openned via autossh like so:
autossh -M 3306 -f -Ng -L 3306:127.0.0.1:3306 mariaDB@server-ip

Unfortunately I often end up with 'can't connect' or 'Lost connection' errors:
SQLSTATE[HY000] [2003] Can't connect to MySQL server on '127.0.0.1' (111)

or

SQLSTATE[HY000] [2013] Lost connection to MySQL server at 'reading authorization packet', system error: 0.

Here is some additionnal info as it might help:
MariaDB [(none)]> show global variables like '%timeout';
+-----------------------------+----------+
| Variable_name               | Value    |
+-----------------------------+----------+
| connect_timeout             | 30       |
| delayed_insert_timeout      | 300      |
| innodb_flush_log_at_timeout | 1        |
| innodb_lock_wait_timeout    | 50       |
| innodb_rollback_on_timeout  | OFF      |
| interactive_timeout         | 28800    |
| lock_wait_timeout           | 31536000 |
| net_read_timeout            | 30       |
| net_write_timeout           | 60       |
| slave_net_timeout           | 3600     |
| thread_pool_idle_timeout    | 60       |
| wait_timeout                | 3600     |
+-----------------------------+----------+
12 rows in set (0.00 sec)

Netstat output while doing telnet 220.127.116.11 3306:
netstat -naptu|grep 3306
tcp        0      0 0.0.0.0:3306            0.0.0.0:*               LISTEN      5249/ssh
tcp        0      0 127.0.0.1:46701         127.0.0.1:3306          TIME_WAIT   -
tcp        0      0 127.0.0.1:46712         127.0.0.1:3306          TIME_WAIT   -
tcp        0      0 127.0.0.1:46702         127.0.0.1:3306          TIME_WAIT   -
tcp        0      0 127.0.0.1:46647         127.0.0.1:3306          TIME_WAIT   -
tcp        0      0 127.0.0.1:46704         127.0.0.1:3306          TIME_WAIT   -
tcp        0      0 127.0.0.1:46705         127.0.0.1:3306          TIME_WAIT   -
tcp        0      0 127.0.0.1:46703         127.0.0.1:3306          TIME_WAIT   -
tcp        0      0 127.0.0.1:46709         127.0.0.1:3306          TIME_WAIT   -
tcp        0      1 220.127.116.11:52674     126.96.36.199:3306          SYN_SENT    5109/telnet
tcp        0      0 127.0.0.1:46706         127.0.0.1:3306          TIME_WAIT   -
tcp6       0      0 :::3306                 :::*                    LISTEN      5249/ssh

Telnet ends up timing out:
telnet 18.104.22.168 3306
Trying 220.127.116.11...
telnet: Unable to connect to remote host: Connection timed out

Comment: Try a telnet to 18.104.22.168 on port 3306. telnet 220.127.116.11 3306 Also see if it is listening netstat -naptu|grep 3306
Comment: Is your SSH session timing out or is this failure occurring when you try to connect?
Comment: What are the various timeouts for SSH connections and MySQL connections.  I have seen instances where the mysql client timesout while waiting on the ssh tunnel to connect.  In many cases this was due to reverse DNS lookups on the server side of the connection. You can disable these reverse DNS lookups in sshd's config files.
Comment: It seems to listen. I edited my question with the netstat output
Comment: @Andrew I had nothing set up in my sshd_config except `TCPKeepAlive yes` I'm going to add `ClientAliveInterval 60` and `ClientAliveCountMax 99999`
Comment: @jeffatrackaid timeouts for MySQL are shown in my question. As for ssh, it's the defaults. Is there a way to display them? Because there's nothing but `TCPKeepAlive yes` in sshd_config… Nothing about DNS in sshd's config files neither? Are they activated by default eventhough nothing is mentionned in the config file?
Comment: Setting `ClientAliveInterval 60` and `ClientAliveCountMax 99999` didn't solve the problem.
Answer: I'm a bit late to the party, but I've been struggling with this issue for most of the day: an SSH tunnel for MySQL just wouldn't get a response and netstat on the remote host showed SYN_SENT (from 127.0.0.1 on an ephemeral port to 127.0.0.1:3306).
For me, the problem was that iptables was running but wasn't configured to allow loopback connections (sidenote: if anyone knows why that's a sensible default, I'd love to find out!) and, as such, the connection (the SYN packet) from the SSH daemon to MySQL was being dropped by iptables.
The fix is as simple as adding a -i lo -j ACCEPT rule in your INPUT chain before any global DROP rules. For me this was iptables -I INPUT 4 -i lo -j ACCEPT but this will vary depending on your existing rules.
Credit for helping me with this one goes to this answer: https://serverfault.com/a/319267
Edit: Don't forget to save your iptables changes afterwards!


Determine boundary and whether the set $A = \{(x,y)\in R^2 : x^2 < y <x\}$ is open or closed.

Question: We have the set $$A = \{(x,y)\in R^2 : x^2 < y <x\}$$
If we notice $\;x^2 < x\;$ if and only if $\;0 \le x <1 $, then the set would be:
$$A = \{(x,y)\in R^2 :  0<y <x<1\}$$
But then I don't know how to continue.
Thanks in advance.
Comment: No $A=\{(x,y):x^2 < y < x\} \ne \{(x,y):0< y < x< 1\}=B$ because you are ignoring the requirement that $x^2 < y$.  $(\frac 12,\frac 18)\in B$ because $0< \frac 18< \frac 12 < 1$ but $(\frac 12,\frac 18)\not \in A$ because $\frac 18 < (\frac 12)^2 < \frac 12 < 1$.  It'd be more accurate to say $A = \{(x,y)|0 < x^2 < y < x <1\}$.
Answer: If $ x\le 0$ then the point $(x,y)$ is not in $ A$ since we must have
$$x>y>x^2\ge 0$$
If $ x\ge 1$ then the point $(x,y)$ is not in $ A$ because $$ x^2 \ge x \ge 1$$
thus
$$A=\{ (x,y)\in (0,1)^2\;\; :y- x^2>0\} \cap \{(x,y)\in(0,1)^2 \;\;  : x-y>0\}$$
The border is the line $y=x$ and a piece of parabola $ y=x^2$.
Answer: It may be easiest to construct the set as the intersection of sets that are easier to deal with, like this.
$$\left \{ (x,y)\in \mathbb{R}^2 |y<x \right \}\bigcap \left \{(x,y)\in \mathbb{R}^2 |x^2<y  \right \}$$
It may be helpful to graph each of these sets. As you've correctly determined, the x coordinates of the set are between 0 and 1, so the boundary must be some subset of $\left \{ (x,y)\in \mathbb{R}^2 |0<x<1\right \}$. Anything in this vertical strip below the curve $y=x^2$ will be out of the set you're interested in, and at each point of this curve, you can find some small $\varepsilon $ (with a specific value depending on the point you pick) such that any point with the same x coordinate where the y coordinate satisfies $x^2<y<x^2+\varepsilon $ is in your set. In other words, every open neighborhood of a point in the strip that lies on the parabola contains points inside your set and points outside your set, so the part of this curve that passes through this strip must form part of the boundary. We can make a similar argument for $y=x$, reversing "above" and "below".
The argument for why the points $(0,0)$ and $(1,1)$ is slightly trickier, but if we consider that the lines $y=\frac{x}{2}$ and $y=\frac{3x+1}{2}$ are both continuous and pass through your set as they approach $(0,0)$ and $(1,1)$ from the left and right, respectively, we can show that any open neighborhood of $(0,0)$ or $(1,1)$ contains points in your set and out of your set, so these points too must be on the boundary.
Now, if $y=x$ ,it is not the case that $y<x$, and if $y=x^2$, it is not the case that $y>x^2$, so this set does not contain its boundary points, making it open in the standard topology on $\mathbb{R}^2$


Como verificar se um array contém um determinado elemento

Question: Tentei com o indexOf (é um requisito da questão utilizar), mas estou tendo muita dificuldade. O código que eu estou tentando utilizar faz o contrário:
function contem(elemento){
let array =[];
  for(var i=0; i< elemento.length; i++)
   array = elemento.indexOf(i);
      if(array!= -1){
        return true;
      }}

Comment: Use método Array.includes() que retorna true ou false.
Comment: também usaria o `includes`. `const list = [1, 2, 3]` `list.includes(2)`retornaria true, por exemplo.
Answer: Verificar a existência de um tipo primitivo
Se você quiser verificar a existência de um tipo primitivo, pode utilizar o indexOf ou includes:

const list = [1, 2, 3, 4, 5];

console.log(list.indexOf(9)); // -1
console.log(list.indexOf(4)); // 3

console.log(list.includes(8)); // false
console.log(list.includes(3)); // true

Conforme você pode ter percebido acima, os dois métodos são bem similares, mas:

indexOf retorna o índice do elemento que você passou como argumento. Caso o elemento não exista, -1 será retornado;
includes retorna um booleano verdadeiro se o elemento passado existir no array. Caso contrário, um booleano falso retornar-se-á.

Então, já que é requisito da pergunta utilizar indexOf, podemos criar uma função contain:

const list = [1, 2, 3, 4, 5];

function contain(arr, val) {
  // Vale lembrar que o método `indexOf` retorna o índice do valor
  // caso for encontrado e `-1` caso não for encontrado. Logo, uma das
  // formas de converter o valor para booleano é fazer a comparação
  // conforme abaixo.
  // Se o índice retornado for DIFERENTE de `-1`, `true` será retornado.
  // Caso contrário (o valor não existe, logo, `-1` foi retornado),
  // a comparação abaixo resultará em `false`.
  return arr.indexOf(val) !== -1;
}

console.log(contain(list, 2)); // true
console.log(contain(list, 9)); // false

Portanto, se você quiser verificar a existência de um tipo primitivo do array, não há a necessidade de usar nenhum laço de repetição, como o for.

Verificar a existência de um objeto
No entanto, se você estiver trabalhando com um array de objetos, deverá utilizar um laço de repetição, como o for. Apesar disso, nesse caso, o indexOf não é necessário e não deve ser utilizado.

const list = [
  { id: 1, name: 'Foo' },
  { id: 2, name: 'Bar' },
  { id: 3, name: 'Baz' }
];

function contain(arr, key, val) {
  // Iteramos sobre cada elemento do array:
  for (const obj of arr) {
    // Se existir um objeto com a chave passada (`key`),
    // e for igual ao valor esperado (`val`), retornamos
    // `true`. Caso contrário, passa-se à próxima iteração:
    if (obj[key] === val) return true;
  }

  // Se chegamos até aqui, quer dizer que nenhum objeto da
  // lista satisfaz as nossas condições. Portanto, retornamos `false`.
  return false;
}

console.log(contain(list, 'id', 2)); // true
console.log(contain(list, 'id', 9)); // false

No entanto, ao invés de criar esse código enorme para fazer isso, você pode fazer uso do find, que retorna o valor da lista desde que satisfaça uma condição. Note que se nenhum valor satisfazer as condições, undefined será retornado.
Portanto, ao utilizando um operador de negação (NOT) duas vezes conseguimos converter o retorno do método find em um booleano.
Veja como fica mais simples:

const list = [
  { id: 1, name: 'Foo' },
  { id: 2, name: 'Bar' },
  { id: 3, name: 'Baz' }
]

function contain(arr, key, val) {
  // O método `find` retorna o elemento encontrado. Portanto,
  // utilizamos dois operadores de negação (NOT) para transformar
  // o objeto em um booleano (`true` ou `false`).
  return !!arr.find((obj) => obj[key] === val);
}

console.log(contain(list, 'id', 2)); // true
console.log(contain(list, 'id', 9)); // false
Comment: Eu não estava sabendo utilizar o .indexOf(), mas com a tua explicação ficou bem mais claro. No caso, o indexOf() sempre vai ter dois parametros na sintaxe? voce sabe algum material que foque em uma explicaçao mais simplificada de indexOf?
Comment: Sim, o `indexOf` recebe dois argumentos: o primeiro deles, que é o elemento que você quer buscar o índice e o segundo o ponto de partida da busca. Para saber mais, leia [essa documentação](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf).
Comment: Irei ler, vlw!!
Answer: //isso vai verificar se o numero contem na MATRIZ de nome ELEMENTO.
function contem(elemento,numero){
  var aux = 0;
  for(var i=0; i<10; i++){
   if (numero === elemento[i]){
     aux = elemento[i];
  }
  }
  if (aux > 0 ) {
    return true;
  }
}

Answer: function contem (array,valor){
 var aux=0;
  for (var i=0 ;i<array.length;i++){
    return (array.indexOf(valor)!=(-1));
  }
}

Comment: function contem (array,valor){
 var aux=0;for (var i=0 ;i<array.length;i++){return (array.indexOf(valor)!=(-1));}}
Answer: Testei aqui deu certo.
function contem(vetor, elemento){
    for(var i = 0; i < vetor.length ; i++){
        if(vetor.indexOf(elemento) != -1)
            return true;
    }
    return false
}

Answer:  function contem(array,numero){

   let aux = array.indexOf(numero)

   return (aux != -1 == true)

  }


How can I change slur from above to below notes when switching staff in Lilypond?

Question: I have a music passage that crosses from the bottom staff to the top (in a Grand Staff) with a slur.  But, I want the slur to go from above the notes on the bottom to underneath the note on the top staff.  Is this possible in Lilypond (version 2.18.2)?  How about 2.19.x?
In the below image, the top example is what I want, but the bottom example is what I get with Lilypond (typesetting code below the image).

<code>\score
{
  \new GrandStaff
  {
    <<
      \new Staff="up"
      {
        \clef treble
        \time 3/4
        \relative c'
        {
          R1*3/4*2
          s1*3/4
        }
      }
      \new Staff="down"
      {
        \clef bass
        \time 3/4
        \relative c,
        {
          r4 c4^(^\pp g'
          c g' c
          <<
            { \voiceOne
              \change Staff="up" e4) b'4\rest b4\rest
            }
            \new Voice
            { \voiceTwo
              s4 d,,1*1/4\rest s4
            }
          >>
        }
      }
    >>
  }
}
</code>
Answer: Control points can be overridden. The pairs here are x,y coordinates:
<code>      \version "2.19.80"
      % ...
      r4
      \once\override Slur.extra-offset = #'(0 . 6)
      \once\override Slur.control-points =
      #'((1 . -6) (4 . 1) (13 . -6) (18.5 . 0.5))
      c4^(^\pp g'
      % etc
</code>
and give the image below which can obviously be improved with more work: