text:
Q: Calculus question with oblique asymptote involved This question is let $$f(x) = \frac{ax^2+bx-c}{x-4}.$$ Determine the values of $a,b,$ and $c$ so that $f(x)$ has an oblique asymptote of $y=3x+1$ and has local minimum at $x=-3$.
I know this requires two equations. The first one requires taking derivative of $f(x)$ and subbing local minimum. But how do I create second equation involving the oblique asymptote.

A: We have
$$\frac{ax^2+bx-c}{x-4}=\overbrace{ax+b+4a}^\text{oblique asymptote}+\overbrace{\frac{16a+4b-c}{x-4}}^{\text{remainder}}$$ and therefore have $a=3$ and $b=-11.$
To calculate $c$, you mentioned that you have to take the derivative and sub in local minimum.  Hopefully you can take it from here.

A: Be aware that, given a $f(x)$ :

*

*one thing is to find its "asymptotic behaviour" as $x \to \infty$, which means to find a $g(x)$  such that
$$
\mathop {\lim }\limits_{x \to \infty } {{f(x)} \over {g(x)}} = 1
$$
and we say that $f$ and $g$ are asymptotically equivalent;

*another thing is to find the function $g(x)$ which is asymptotically equal to $f(x)$, i.e. such that
$$
\mathop {\lim }\limits_{x \to \infty } \left( {f(x) - g(x)} \right) = 0
$$
Now,  when we talk to find a horizontal or oblique asymptote to a curve we mean to find a line
which is asyptotic to the curve in the second meaning, i.e. that the distance goes to $0$.
In the first way (J. Wang's answer) you can only determine the slope of the line, but not the intercept because
$$
\mathop {\lim }\limits_{x \to \infty } {{f(x)} \over {mx}}
 = 0\quad  \Rightarrow \quad \mathop {\lim }\limits_{x \to \infty } {{f(x)} \over {mx + q}} = 0
$$
Therefore in your case we have
$$
\eqalign{
  & f(x) = {{ax^2  + bx - c} \over {x - 4}} =   \cr
  &  = {{a\left( {x - 4} \right)^2  + b\left( {x - 4} \right) + 8ax - 16a + 4b - c} \over {x - 4}} =   \cr
  &  = {{a\left( {x - 4} \right)^2  + b\left( {x - 4} \right) + 8a\left( {x - 4} \right) + 16a + 4b - c}
 \over {x - 4}} =   \cr
  &  = a\left( {x - 4} \right) + b + 8a + {{16a + 4b - c} \over {x - 4}} \cr}
$$
So for the asymptote we shall have
$$
ax + b + 4a = 3x + 1\quad  \Rightarrow \quad a = 3,\quad b =  - 11
$$
as already indicated by A.Chin.
Then the function becomes
$$
f(x) = {{3x^2  - 11x - c} \over {x - 4}} = 3x + 1 - {{c - 4} \over {x - 4}}
$$
It is clear that the function has the required oblique asymptote, as well as a vertical asymptote at $x=4$, where we have:
$$
\mathop {\lim }\limits_{x \to 4 + } f(x) = - {\rm sgn}(c - 4) \cdot \infty \quad
 \mathop {\lim }\limits_{x \to 4 - } f(x) =  {\rm sgn}(c - 4) \cdot \infty
$$
This means that for $c < 4$ you will  have a minimum at $4 < x$ and a maximum at $x < 4$, while
for $4 < c$ you do not have any local extremum.
You can easily check this analytically.
Therefore a minimum at $x=-3$ is unattainable.


text:
Q: Created a python program to estimate travel time and having an error I have got everything working but for some reason when i put 500 for miles and 80 for mph it says invalid input.
Here is my code.
import time
import datetime

from datetime import datetime
from datetime import timedelta

ch='y'
print("Arrival Time Estimator\n\n")
while ch!='n':
    try:
        est_date_dept = input('Estimated date of departure (YYYY-MM-DD):')
        est_time_dept = input('Estimated time of departure (HH:MM AM/PM):')
        dist = int(input('Enter Miles:'))
        speed = int(input('Enter miles per hour:'))
        travel_time = int(dist)/speed
        t=timedelta(hours=travel_time)
        t=str(t)
        t=t.split(':')
        if t[2] > '00':
          t[1]=int(t[1])+1
          travel_time+=0.01
          time = datetime.strptime(est_time_dept, "%I:%M %p")
          est_time_dept = datetime.strftime(time, "%H:%M")
          est_date_dept = est_date_dept+" "+est_time_dept
          arr_date_time = datetime.strptime(est_date_dept, "%Y-%m-%d %H:%M")
          arr_date_time += timedelta(hours=travel_time)
          est_arr = arr_date_time.strftime("%Y-%m-%d %I:%M %p")
          est_arr=str(est_arr)
        est_arr=est_arr.split()
        print ('\n\nEstimated travel time')
        print ('Hours:',t[0],'\nMinutes:', t[1])
        print ('Estimated date of arrival:',est_arr[0])
        print ('Estimated time of arrival:', est_arr[1], est_arr[2])
        ch = input('\nContinue? (y/n):')
    except:
        print ("Invalid input")
        ch = input("\nContinue? (y/n):")

The output I get is
Output

A: Your problem is that you do a textual comparison on values, but seem to assume that the results will be based on their integer appearance.  As a result, you do not enter the if t[2] block, and est_arr isn't defined.  You need to handle this case and repair the logic that led you there.

A: If you want to know what's going wrong, don't use a bare except: that throws that information away.
Either remove the try:/except: (at least temporarily, for debugging), or change it to except Exception as e: and then print(f"Invalid input: {e!r}"), or something that includes the error message.

For your inputs, if the date or time is invalid, the actual exception is something like this:
ValueError("time data '19:23 AM' does not match format '%I:%M %p'")

In that case, the error message is correct—the input is invalid. It's not all that useful, because you're not giving the user any idea which of their four inputs is invalid, or why, but it is correct.
But if they're both valid, the error is this:
NameError("name 'est_arr' is not defined")

And in that case, calling the input invalid is wrong.

Why do you get this? Well, let's work it through:
travel_time = int(dist)/speed # int(500)/80 = 6.25
t=timedelta(hours=travel_time) # timedelta with 6:15:00
t=str(t) # the string '6:15:00'
t=t.split(':') # the list ['6', '15', '00']
if t[2] > '00': # not true, because '00' is not > '00'
# if body skipped
est_arr=est_arr.split() # oops, NameError

You never assign anything to est_arr if the time is an exact number of minutes (with no seconds left over).
So, when you try to use est_arr, you get a NameError telling you that you never assigned anything to that name.
How can you fix this? Well, I don't know what you were trying to do there. Why did you put that if there in the first place? What did you want to happen when it wasn't true? I can't think of any good reason for that, but presumably you had one in mind.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Prove $ \forall x >0, \quad \sqrt{x +2} - \sqrt{x +1} \neq \sqrt{x +1}-\sqrt{x}$
I would like to prove
  $$ \forall x >0,  \quad \sqrt{x +2} - \sqrt{x +1} \neq \sqrt{x +1}-\sqrt{x}$$

*

*I'm interested in more ways of proving it

My thoughts:
\begin{align}
\sqrt{x+2}-\sqrt{x+1}\neq \sqrt{x+1}-\sqrt{x}\\
\frac{x+2-x-1}{\sqrt{x+2}+\sqrt{x+1}}&\neq \frac{x+1-x}{\sqrt{x +1}+\sqrt{x}}\\
\frac{1}{\sqrt{x+2}+\sqrt{x+1}}&\neq \frac{1}{\sqrt{x +1}+\sqrt{x}}\\
\sqrt{x +1}+\sqrt{x} &\neq \sqrt{x+2}+\sqrt{x+1}\\
\sqrt{x} &\neq \sqrt{x+2}\\
\end{align}

*

*Is my proof correct?

*I'm interested in more ways of proving it.

A: Your proof is correct, but I feel that this could be proved by contradiction.
Assume for contradiction $\exists x>0$ such that the equation $\sqrt{x+2}-\sqrt{x+1}=\sqrt{x+1}-\sqrt{x}$ is true. Then,
\begin{align}
\sqrt{x+2}-\sqrt{x+1}&=\sqrt{x+1}-\sqrt{x}\\
\frac{x+2-x-1}{\sqrt{x+2}+\sqrt{x+1}}&=\frac{x+1-x}{\sqrt{x +1}+\sqrt{x}}\\
\frac{1}{\sqrt{x+2}+\sqrt{x+1}}&=\frac{1}{\sqrt{x +1}+\sqrt{x}}\\
\sqrt{x +1}+\sqrt{x} &=\sqrt{x+2}+\sqrt{x+1}\\
\sqrt{x} &=\sqrt{x+2}\\
x&=x+2
\end{align}
This is not true and we have reached a contradiction. Thus the equation does not hold.

A: Your proof is correct, because each inequality you write is equivalent to the previous one (it should be noted, probably).
Changing all $\ne$ into $=$ would make it a proof by contradiction, that's however unnecessary.
In a different way, you could just swap terms and square, again changing inequalities into equivalent ones:
\begin{gather}
\sqrt{x+2}+\sqrt{x}\ne 2\sqrt{x+1}\\[10px]
x+2+x+2\sqrt{x(x+2)}\ne 4x+4\\[10px]
\sqrt{x(x+2)}\ne x+1\\[10px]
x^2+2x\ne x^2+2x+1\\[10px]
0\ne1
\end{gather}

A: Hint #1:
Assume that $\sqrt{x + 2} - \sqrt{x + 1} = \sqrt{x + 1} - \sqrt{x}$ for some $x > 0$.
Hint #2:
Derive a contradiction.
Hint #3:
This proof (by contradiction) results to some changes in the notation you used in your proof.

A: By the MVT:
$$\sqrt {x+2} - \sqrt {x+1} = \frac{1}{2\sqrt {c_x}}\cdot 1, \ \ \ \ \sqrt {x+1} - \sqrt {x} = \frac{1}{2\sqrt {d_x}}\cdot 1.$$
Here $c_x\in (x+1,x+2), d_x\in (x,x+1).$ Because $1/\sqrt x$ strictly decreases, the left term minus the right term is negative.

Concavity: Slopes of successive chords on a strictly concave graph are strictly decreasing, and $\sqrt x$ is strictly concave. Therefore $\sqrt{x +2} - \sqrt{x +1} < \sqrt{x +1}-\sqrt{x}$  for all $x\ge 0.$

A: Assume the statement is true
\begin{align}
\sqrt{x + 2} - \sqrt{x + 1} &= \sqrt{x + 1} - \sqrt{x}\\
\sqrt{x + 2} + \sqrt{x} &= 2\sqrt{x + 1}\\
2x + 2 + (2\sqrt{x^2 + 2x}) &= 4x + 4\\
\sqrt{x^2 + 2x} &= x + 1\\
x^2 + 2x &= x^2 + 2x + 1\\
0 &= 1\\
\end{align}
Which is a contradiction. Now I am not sure if I'm allowed to manipulate the equation like this so the proof might be invalid. The reason I though I could was I had seen simillar logic in proving the irrationality of $\sqrt{2}$.

A: By the mean value theorem - MVT, for all $x >0$, it exists $\zeta_x \in (x, x+1)$ such that $$\frac{1}{2\sqrt{\zeta_x}}((x+1)-x)=\frac{1}{2\sqrt{\zeta_x}}=\sqrt{x+1}-\sqrt{x}$$ As $y \to \frac{1}{2\sqrt{y}}$ is stricly decreasing, you have $$\frac{1}{2\sqrt{\zeta_{x+1}}}=\sqrt{x+2} -\sqrt{x+1} < \sqrt {x+1}-\sqrt{x}=\frac{1}{2\sqrt{\zeta_x}}.$$

A: I will show that
if
$\sqrt{x+a}-\sqrt{x+b}
=\sqrt{x+b}-\sqrt{x+c}
$
for two different values of $x$,
then
$a=c$
and
$b = a+c
=2a
$.
If the equality
holds for one value of $x$,
then
$8x(a+c-2b)
=(a-4b+c)^2-4ac
$.
Since,
in the original problem,
$a=2, b=1, c=0$,
this can not hold for
two values of $x$.
If it holds for one $x$,
since
$a+c-2b = 0$
and
$(a-4b+c)^2-4ac
=2^2-0
=4
$,
this does not hold for
any $x$.
then
Suppose
$\sqrt{x+a}-\sqrt{x+b}
=\sqrt{x+b}-\sqrt{x+c}
$,
or
$\sqrt{x+a}+\sqrt{x+c}
=2\sqrt{x+b}
$.
Squaring,
$x+a+x+c+2\sqrt{(x+a)(x+c)}
=4(x+b)
$
or
$2x-a+4b-c
=2\sqrt{(x+a)(x+c)}
$.
Squaring again,
$4x^2-4x(a-4b+c)+(a-4b+c)^2
=4(x+a)(x+c)
=4(x^2+x(a+c)+ac)
=4x^2+4x(a+c)+4ac
$
or
$4x(a+c+a-4b+c)
=(a-4b+c)^2-4ac
$
or
$4x(2a+2c-4b)
=(a-4b+c)^2-4ac
$
or
$8x(a+c-2b)
=(a-4b+c)^2-4ac
$.
If this is true for
more than one $x$,
then
$a+c-2b = 0$
and
$(a-4b+c)^2-4ac
= 0
$.
From the first equation,
$2b = a+c$.
Substituting this
in the second equation,
$4ac
=(a-4b+c)^2
=(a+c-2(a+c))^2
=(a+c)^2
=a^2+2ac+c^2
$
or
$0
=a^2-2ac+c^2
=(a-c)^2
$,
so that
$a=c$.
Therefore,
if
$\sqrt{x+a}-\sqrt{x+b}
=\sqrt{x+b}-\sqrt{x+c}
$
for two different values of $x$,
then
$a=c$
and
$b = a+c
=2a
$.


text:
Q: Overload arrow operator as ref qualified If the arrow operator of my class returns a pointer to internal data, is it a good idea to always declare it as ref qualified and have it work solely for l-values?
template <class T>
class Dummy
{
  T _data; // data lives within the class

public:
  Dummy() { /* some ctor logic */ }

  T* operator->() & { return &_data; }
  //              ^ this is the question

  T const* operator->() const& { return &_data; }
  //                         ^ this is the question
};

The reasoning behind this, is that using the arrow operator on a temporary instance would create a dangling pointer by default, since the data lives in my class.
Also, is there a canonical resource on ref qualifiers and overloading member access operators?

Note that the provided class example is purely for demo reasons, to provide a minimum example.


text:
Q: Why the Jiffy package show the wrong week number I see a strange behavior with the Jiffy package (link). If I run the following code I get the following output (the first is correct, the second is wrong)

42

43

final refDate = new DateTime(2020, 10, 18); // 18 Oct 2020
int weekNumber(DateTime date) {
  int dayOfYear = int.parse(DateFormat("D").format(date));
  return ((dayOfYear - date.weekday + 10) / 7).floor();
}

print(weekNumber(refDate));
print(Jiffy(refDate).week.toString());

Can anyone explain when? I see the .week function call the same formula... (link)
Thanks!

A: This seems to be the intended behaviour of the package, ie weeks to start on Sunday and end on Saturday. Hopefully the developer will give an option to set when the week should start


text:
Q: Android geocoding asynctask crashes My android asynctask crashes when button is clicked. Here is the code below:
private class GetAddressTask extends AsyncTask<String, Void, LatLng>{
    Context mContext;

    public GetAddressTask(Context context) {
        super();
        mContext = context;
    }

    @Override
    protected LatLng doInBackground(String... params){

        Geocoder gc =  new Geocoder(mContext);
        List<Address> addresses = null;
        try {
            /*
            * Return 1 address.
            */
            String location = edit.getText().toString();
            addresses = gc.getFromLocationName(location, 1);
        } catch (IOException e1) {
            Log.e("LocationSampleActivity", "IO Exception in getFromLocation()");
            e1.printStackTrace();
        } catch (IllegalArgumentException e2) {
            e2.printStackTrace();
        }

        if (addresses != null && addresses.size() > 0) {

            Address address = addresses.get(0);

            double lat = address.getLatitude();
            double lng = address.getLongitude();

            LatLng mint = new LatLng(lat,lng);

            return mint;
        }

    else {
            return null;
        }
    }

    @Override
    protected void onPostExecute (LatLng mint) {
        CameraUpdate update = CameraUpdateFactory.newLatLngZoom(mint,14);
        map.moveCamera(update);
        progress.dismiss();
    }
}


text:
Q: What are some common issues with fitting functions to data? Mathematica has numerous functions designed to, or capable of, fitting known functions, and finding unknown functions to match data sets. What are some common issues that come with finding those fits?

A: First, let's enumerate some of the functions:

*

*Fit[] is the simplest of fitting functions. It has been introduced in v5, and hasn't been updated since v6 (as of v11).
It finds a least-squares fit as a linear combination of functions. As such it can only be used for simple functions. Fit[] can fit $c\sin{x}$ but not $\sin{c x}$, where c is an unknown parameter for Fit[] to find.

*FindFit[] has been introduced in v5, and hasn't been updated since v7 (as of v11). It provides a simple and clear way of finding parameters of a known function to a dataset. FindFit[] also finds a simple least-squares fit, but can be used for more complicated functions, including Trigonometric functions.

*LinearModelFit[] and NonlinearModelFit[] have been introduced in v7 and have been continuously updated since, which are related to Fit[] and FindFit[] respectively.
These functions construct a fit with a lot of additional information which can be extracted.
In the same vein as LinearModelFit[]there are some additional symbols such as LogitModelFit and ProbitModelFit which fit data to predefined models (as opposed to a linear model).

*

*FindGeneratingFunction[] is a symbol that attempts to generate a function to a dataset. The symbol will attempt to find a function that matches the data points exactly.

*FindFormula[] is a symbol which attempts to find a formula to non-exact data. FindFormula[] is currently unreliable.

*FindSequenceFunction[] is a symbol which tries to exactly match known series to a dataset.

*Interpolation[] generates a piecewise function which interpolates between the points it is fed. It doesn't return an analytical function.

*NMinimize[] minimizes a function with respect to a variable/ variables. This function can be used to create a fitting function.
Fitting: Poor or no results

*

*0. Insufficient or erroneous data points
Though this should be obvious, it is nonetheless a common problem.
As a general rule, in order to find n parameters, you need n data points. However, considering many of these functions are not exact, usually many more data points are required. In general, more data points is better.
Additionally data points should be fed in the form {{x1, y1}, {x2, y2}, {x2, y3}, ..., {xn, yn}}. If the data is in the form {y1, y2, y3, ..., yn} then the x-values will be taken to be Range[n].

*

*Initial Values
Often times the estimates that Mathematica produces are poor, especially when the real values are far from 1 or there are large order differences between the variables.
Consider:
    data = {{7, 17.93}, {14, 36.36}, {21, 67.76}, {28, 98.1}, {35,
        131}, {42, 169.5}, {49, 205.5}, {56, 228.3}, {63, 247.1}, {70,
        250.5}, {77, 253.8}, {84, 254.5}};
    model = c/(1 + ((c - n)/n)*E^(-r*t));
    fit = FindFit[data, model, {c, n, r}, t];

The result is quite poor:
    Show[Plot[model /. fit, {t, 7, 84}], ListPlot@data]

Initial estimates of the function can be used. The list of variables has to be augmented with the estimates: {{c, 256}, {n, 9}, r} instead of {c, n, r}. The result is significantly better:
    fit = FindFit[data, model, {{c, 256}, {n, 9}, r}, t]

*

*1.1
Supposing difficulties with finding the initial values, NonlinearModelFit[] can be used to programmatically find good values.
    data = Table[{i, 84.95 Sin[2 i] + 50}, {i, 1, 20}];
    model = {a Sin[b x + c] + d, -π <= c <= π};
    nlm = Quiet@Table[
       NonlinearModelFit[
        data, model, {a, {b, i}, c,
         d}, x, MaxIterations -> 1000], {i, 0, 4, 0.05}];

This will generate a list of fits, which can be tested.
    ListPlot[Norm[nlm[[#]]["FitResiduals"]] & /@ Range@81, Joined -> True]

As you can see, there are sharp spikes where the fit converges, finding the first and acquiring the fit:
    fit = Normal@nlm[[Position[
     min = Norm[nlm[[#]]["FitResiduals"]] & /@ Range@81, Min[min]][[1,
      1]]]]

50. + 84.95 Sin[3.52466*10^-17 + 2. x]

    Show[Plot[fit, {x, 1, 20}], ListPlot@data]

*

*1.2 Overflow in fit
Exponential data, and other data that has big differences in y-values of data can create overflow in the fit.
    data = {{0, 6.51}, {100, 0.77}, {200, 0.306}, {400, 0.0476}, {700, 0.004}};
    model = a Exp[-b x];
    nlm = FindFit[data, model, {a, b}, x]

General::ovfl: Overflow occurred in computation. >>

Using method "NMinimize" prevents overflow.
    FindFit[data, model, {a, b}, x, Method -> "NMinimize"]

{a -> 6.50674, b -> 0.0206953}

*

*1.3 Weighted data results in bad fit
Assuming the above data.
Using NonlinearModelFit[] you can add error data.
One might assume that in some physical models, the error scales linearly with the magnitude of the data.
Take into account that weights are rated quadratically.
With limited data, using square root scaled weights is usually the right rate.
    errors = data[[All, 2]];
    nlme = NonlinearModelFit[data, model, {a, b}, x, Method -> "NMinimize", Weights -> 1/errors^2];
    nlme2 = NonlinearModelFit[data, model, {a, b}, x, Method -> "NMinimize", Weights -> 1/errors2^2];
    nlm = NonlinearModelFit[data, model, {a, b}, x, Method -> "NMinimize"];
    Show[ListPlot[data, PlotStyle -> {PointSize[0.02], Darker@Red}],
     Plot[{nlm[x], nlme[x], nlme2[x]}, {x, 0, 700}, PlotRange -> Full],
     PlotRange -> All]

Where blue is unweighted, yellow is linearly weighted, and green inverse quadratically weighted.

*

*1.4 Exponential Data
Consider the following model:
    data = {{1032948957, 0.0710695}, {1033175985, 0.072761}, {1033794716,
      0.0773709}, {1035473824, 0.0898812}, {1036526395,
      0.0977235}, {1050599907, 0.310317}, {1058188482,
      0.572949}, {1064270054, 0.935439}, {978672841, 0.00081391}};
    model = a Exp[k t];
    fit = FindFit[data, model, {a, k}, t]

{a -> 0., k -> 1.}

The result is obviously wrong. The data is presented in a difficult way, the x-values are far higher than the y-values, and the data follows an exponential curve, so initial values might not do the trick.
One efficient way of solving this, is by taking the log of the y-data and the fit:
    logdata = {#[[1]], Log[#[[2]]]} & /@ data;
    fit = FindFit[logdata, c x + d, {c, d}, x];
    Show[Plot[c x + d /. fit, {x, 1.03*^9, 1.07*10^9}, PlotStyle -> {Red}],
     ListLogPlot[data, PlotStyle -> {Purple, PointSize[0.02]}]]

Note that this is a linear regression, and as such improperly weights the potential errors in the data points.
We can add weights based on the slope of an InterpolatingFunction constructed from the data.
    slopes = D[Interpolation[data][x], x] /. x -> data[[#, 1]] & /@
      Range@9;

And then fit with NonlinearModelfit[]:
    fitmod = NonlinearModelFit[logdata, c x + d, {c, d}, x,
      Weights -> 1/slopes^2]

The (log-)difference in the fits is small, but can be relevant.
    Plot[Normal@fitmod - (c x + d) /. fit, {x, 1.03*^9, 1.07*10^9}]

*Possibly complex functions
Consider the data set
    data = ToExpression@Import["http://pastebin.com/raw.php?i=eSXQuV62"];

Trying initial values:
    model = G/(2/3*x)*(1 - (4.13/G*(Log[k/(x*r)] + G/4.13))^(2/3));
    fit = FindFit[data, fun, {{k, 50}, {x, 0.2}, {G, 80}}, r];

Not only does the fitting result in a warning, but the functions cannot be plotted at all. This is because unless both x > 0 && k > 0, the model returns a complex result. As a result, functions with possible complex results need to be restrained.
    fit = Quiet@FindFit[
      data, {fun, k > 0, x > 0}, {{k, 0.5}, {x, 0.01}, {G, 80}}, r];
    Show[Plot[Re[model /. fit], {r, -10, 15000}], ListPlot@data]

This problem can most commonly occur with any models that have roots.
Suppose some function f[x] with unknown constant c, which is real at unknown intervals
    f[x_, c_]:= ...

The domain at which the function is real can be found by
dom = Reduce[And @@ Thread[f[#, b] & /@ data[[All, 1]] > 0], {b}, Reals];

where data[[All, 1]] is the dataset's x-values.

*Complex Data

*

*3.1 Complex variables
Suppose you need to fit data in the complex plane:
    data = {{5.0119`*^6, 4.3675` + 0.45799` I}, {3.9811`*^6,  4.3315` + 0.48469` I},
    {3.1623`*^6, 4.339` + 0.52722` I}, {2.5119`*^6,4.359` + 0.57605` I}, {1.9953`*^6, 4.409` + 0.63945` I},
    {1.5849`*^6,4.4774` + 0.70803` I}, {1.2589`*^6, 4.5612` + 0.78699` I}, {1.`*^6, 4.6626` + 0.87252` I}}
    model = a + b/(1 + I x c);

Then
    fit = FindFit[comp, model, {a, b, c}, x];

won't work, and will return the error that

 The function value ... is not a list of real numbers with dimensions

The particular issue is the c which is paired with the I.
One way of solving this is predefining c.
    model2[c_] := a + b/(1 + I x c);
    With[{c = 7*^-6}, FindFit[data, model2[c], {a, b}, x]]

{a -> 4.20685 + 0.378959 I, b -> -3.17118 + 3.49223 I}

A slight modification of subsection 1.1 can be used to find an optimal value for c.

*

*3.2 Real variables
Alternatively, a fit symbol can be constructed as follows:
    model[x_] = a + b/(1 + I x c)
    s = NMinimize[{Total[Norm[model[#[[1]]] - #[[2]]]^2 & /@ data],
       0 < a < 10 && 0 < b < 10 && -10 < c < 0}, {a, b, c},
      MaxIterations -> 10000]

{0.2686, {a -> 4.43805, b -> 9.44122, c -> -8.53354*10^-6}}

Again, with the limited sample data, initial domains as specified here are necessary for a good result.

*Implicit Functions
Suppose you have data which has to be fitted to the form
    modelimp = a y + b Log[y] == x;
    data = {{1, 1}, {2, 1.4}, {3, 1.8}, {4, 2.4}, {5, 2.9}};

The most straightforward way to solve this is to find the function in form of y =.
    model = y/.Quiet@Solve[modelimp, y][[1]];
    fit = FindFit[data, model, {a, b}, x]

{a -> 0.986636, b -> 1.96879}

Alternatively, if this isn't possible, FindRoot[] can be used to replace the model inside the fit symbol.
    fitfunc[a_?NumericQ, b_?NumericQ, x_?NumericQ] :=
      y /. FindRoot[a y + b Log[y] == x, {y, 1.}];
    fit = FindFit[data, fitfunc[a, b, x], {a, b}, x];
    Show[ListPlot[data], Plot[model /. fit, {x, 1, 5}]]

However, an implicit function requires a different calculation to minimize the residuals in both the x- and y- directions. To do this, you can use NArgMin to minimize the norm of the implicit function.
    {a, b} = NArgMin[
      Norm[Function[{x, y}, c[1] y + c[2] Log[y] - x] @@@ data], {c[1],
       c[2]}]

{0.990983, 1.95206}

As you can see, this gives slightly different results for a and b.

*FindGeneratingFunction[] finds the wrong result or no result.

FindGeneratingFunction[] looks for functions that match its dataspace exactly. However, if there are few datapoints, or the data points follow a logical pattern, there may be many results possible. This is especially true for infinitely repeating series.
At other times no solution is found at all.
Specifying , FunctionSpace -> will tell FindGeneratingFunction[] where to look. As any such series can be generated by an n-dimensional polynomial where n the length of the dataset. Polynomials of length n are often not given as a solution. Specifying , FunctionSpace -> "Polynomial" will force the simplest possible polynomial to be given as the answer, regardless of its order.

*Problems with prepending FindGeneratingFunction[]
Consider
    FindGeneratingFunction[{0, 0, 0, 0, 2, 2, 6, 6, 22, 22, 86, 86, 342,
      342, 1366, 1366, 5462, 5462}, t]

(2^(1 + t) t^4 (1 - 2 t^2))/(1 - t - 4 t^2 + 4 t^3)

The result should logically be the same as
    t^4 FindGeneratingFunction[data = {2, 2, 6, 6, 22, 22, 86, 86, 342, 342,
       1366, 1366, 5462, 5462}, t]

-((2 t^4 (-1 + 2 t^2))/(1 - t - 4 t^2 + 4 t^3))

However, the former is incorrect.
The latter is a proper workaround, programmatically this is
    t^(n = Length@Position[data, 0]) FindGeneratingFunction[Drop[data, n], t]

-((2 t^4 (-1 + 2 t^2))/(1 - t - 4 t^2 + 4 t^3))

A: @Feyre's answer is excellent.  I would add the following two items:
1. Overparameterizing a model.
When a model has parameters that are not estimable, errors and convergence problems arise.  For example a model with parameters $a$, $b$, and $c$ in the following form
$$y=a*b + c*x + error$$
does not allow one to estimate both $a$ and $b$.  The product $a*b$ can be estimated but not the individual parameters.  There are related issues when some of the parameter estimators are highly correlated.  Looking at the "CorrelationMatrix" option for some of the fitting techniques is helpful for seeing if overparameterization is an issue.
2. Not looking at the residuals.
Most of the model fitting techniques currently assume a constant variance across all of the predictor values.  Weighting is one way to address that issue but even with a well thought out weighting scheme, one needs to check on the residuals to look for lack of fit either in the prediction equation or the assumption of constant variance.  Plotting the histogram of residuals and the residuals vs. the predicted values should be a matter of course to check for undesirable patterns and deviations from assumptions.
Most models have a "fixed" portion and a "random" portion with both being essential to a justifiable fit.


text:
Q: Multiple jquery Datepicker with start end validation Hi I would appreciate any assistance with regards to my problem
I am able to make the jQuery Datepicker work with the start/end date validation if I only have 1 datepicker for both start and end.
However, I don't know how to have the same function if I have multiple datepickers in the same page. I can't classify them in a class cause then they aren't able to validate according to the correct start and end datepickers.
I've searched everywhere but still unable to find a solution. Hope someone can help me with this!
Thank you
This is my javascript:
$(document).ready(function () {
    $("#start1").datepicker({
    numberOfMonths: 2,
    onSelect: function(selected) {
      $("#end1").datepicker("option","minDate", selected)
    }
});
    $("#end1").datepicker({
    numberOfMonths: 2,
    onSelect: function(selected) {
       $("#start1").datepicker("option","maxDate", selected)
    }
});
});

This is my html for 1 datepicker each:
<input type="text" name="start1" placeholder="Start Date" id="start1" class="form-control" />'
<input type="text" name="end1"  placeholder="End Date" id="end1" class="form-control" />

If there are more than 1 datepicker the code is as such:
<input type="text" name="start" placeholder="Start Date" id="start<%=i%>" class="form-control" />
<input type="text" name="end"  placeholder="End Date" id="end<%=i%>" class="form-control" />

where i represents a number depending on the size of an array

A: I just used a class start and class end and called the datepicker function using those. for validation and manipulation, i left the ids the way they are and you can use those to validate/manipulate the fields.
UPDATE:::
After a few hours of my initial answer, I am now updating my answer to take into consideration of my understanding what OP wanted after a few communication between us through comments section. The code snippet and the fiddle links are also updated to the new answer.
Main thing I introduced is a new data attribute to the input tags "data-grp". So every start/end date pair gets to be part of a unique data-grp. In my code example, I have used 2 pairs of start/end date and with data attribure of data-grp="1" and data-grp="2". Now using that I have tweaked the datepicket call instantiation to uniquely identify the correct data groups and apply the min/max date feature/option to that particular group only.
Hope this is what you were looking for...
Jsfiddle link http://jsfiddle.net/2k72adyL/6/
Code snippet as follows....

$(document).ready(function() {

  $(".datePickStart").datepicker({
    minDate: 0,
    numberOfMonths: 2,
    onSelect: function(selected) {
      var datagrp = $(this).attr('data-grp');
      var end_currdatagrp = ".end[data-grp='" + datagrp + "']";
      var start_currdatagrp = ".start[data-grp='" + datagrp + "']";
      $(end_currdatagrp).datepicker("option", "minDate", selected);

    }
  });

  $(".datePickEnd").datepicker({
    minDate: 1,
    numberOfMonths: 2,
    onSelect: function(selected) {
      var datagrp = $(this).attr('data-grp');
      var start_currdatagrp = ".start[data-grp='" + datagrp + "']";
      $(start_currdatagrp).datepicker("option", "maxDate", selected);
    }
  });
});
Start1:
<input type="text" name="start1" placeholder="Start Date" id="start1" class="form-control start datePickStart" data-grp="1" />

End1:
<input type="text" name="end1" placeholder="End Date" id="end1" class="form-control end datePickEnd" data-grp="1" />

Start2:
<input type="text" name="start2" placeholder="Start Date" id="start2" class="form-control start datePickStart" data-grp="2" />

End2:
<input type="text" name="end2" placeholder="End Date" id="end2" class="form-control end datePickEnd" data-grp="2" />


text:
Q: Solr & Nutch - Indexing only certain urls I'm using nutch 1.6 for crawling, and solr 3.6.2 for indexing the urls crawled.
But, I want to keep only urls containing details.
What I have done is to add many (a lot of) filters to nutch/conf/regex-urlfilter.txt.
I want to know if there is a better solution even if I should crawl all data (urls), and then filter only the important once in Solr (in Solrindex command).

A: If you don't need the pages, it would be best to filter out from the indexing itself.
However, If you have a pattern that you can filter upon in Solr, you can use filter queries to do the filtering.


text:
Q: Is it possible to dynamically add Conversation Drivers using items in a list? I'd like to dynamically add some Conversation Drivers using items in a list, there may be 0 or more items up to 6.
A for-each loop is currently not allowed in the conversation-drivers block so I have resorted to using 'if' statements and selecting the corresponding item in the list.
conversation-drivers {
    if (size(this.options) > 0) {
      conversation-driver {
        template ("#{value(this.options[0].name)}")
      }
    }
    if (size(this.options) > 1) {
      conversation-driver {
        template ("#{value(this.options[1].name)}")
      }
    }
    if (size(this.options) > 2) {
      conversation-driver {
        template ("#{value(this.options[2].name)}")
      }
    }
}

This works but it's ugly, is there a better way?
Thanks

A: You are correct that there is no for-each child key inside conversation-drivers. Nice workaround with if and I'm afraid that's the way to go for now.
One note about conversation-drivers, it might not look pretty if more than 3 choices due to the mobile device screen size. You may want to check sample view with the 6 items first.
Have fun with Bixby!


text:
Q: Yii2 | Получение данных с модели День добрый. Начал изучать yii2.
Есть вопрос , не могу правильно получить данные с модели в контроллере.
код контроллера
public function actionChanelssetting(){
    if(isAdmin()){
        $model = app\models\ChanelsSetting::find()->count();// не получаются данные

        return $this->render('chanelssetting',[
         'model' => $model,
        ]);
    }
    else{
     return $this->redirect(['site/index']);
    }
}

код модели
namespace app\models;
use Yii;
use yii\db\ActiveRecord;
use yii\base\Model;

class ChanelsSetting extends ActiveRecord{

    public static function tableName(){
        return '{{%chanelssetting}}';
    }

    public function rules(){
        return [
            [['id', 'active'], 'integer'],
            [['daily_limit_today ', 'daily_limit_tomorrow'], 'required'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'name' => 'Название',
            'slug' => 'Сокращенное название',
            'daily_limit_today' => 'Дневной лимит на сегодня',
            'daily_limit_tomorrow' => 'Дневной лимит на завтра',
        ];
    }

}

На выходе получаю ошибку. Если удалить строку с получением данных в контроллере,то вьюха работает, но без данных.

An Error occurred while handling another error:
exception 'yii\web\HeadersAlreadySentException' with message 'Headers already sent in /home/i/infowe8i/msg.webcom.mobi/models/ChanelsSetting.php on line 42.' in /home/i/infowe8i/msg.webcom.mobi/vendor/yiisoft/yii2/web/Response.php:366
Stack trace:
#0 /home/i/infowe8i/msg.webcom.mobi/vendor/yiisoft/yii2/web/Response.php(339): yii\web\Response->sendHeaders()
#1 /home/i/infowe8i/msg.webcom.mobi/vendor/yiisoft/yii2/web/ErrorHandler.php(135): yii\web\Response->send()
#2 /home/i/infowe8i/msg.webcom.mobi/vendor/yiisoft/yii2/base/ErrorHandler.php(111): yii\web\ErrorHandler->renderException(Object(yii\web\HeadersAlreadySentException))
#3 [internal function]: yii\base\ErrorHandler->handleException(Object(yii\web\HeadersAlreadySentException))
#4 {main}
Previous exception:
exception 'yii\web\HeadersAlreadySentException' with message 'Headers already sent in /home/i/infowe8i/msg.webcom.mobi/models/ChanelsSetting.php on line 42.' in /home/i/infowe8i/msg.webcom.mobi/vendor/yiisoft/yii2/web/Response.php:366
Stack trace:
#0 /home/i/infowe8i/msg.webcom.mobi/vendor/yiisoft/yii2/web/Response.php(339): yii\web\Response->sendHeaders()
#1 /home/i/infowe8i/msg.webcom.mobi/vendor/yiisoft/yii2/base/Application.php(392): yii\web\Response->send()
#2 /home/i/infowe8i/msg.webcom.mobi/web/index.php(16): yii\base\Application->run()
#3 {main}

A: На вашем скриншоте с ошибкой сказано, что приложение не может найти класс app\conttrollers\app\models\ChanelsSetting.
Очевидно, что неверно указано FQCN (Fully Qualified Class Name) класса ChanelsSetting.
В вашем случае, вы забыли добавить знак \ в начало имени класса, и PHP искал его в текущем namespase.
Подробнее о том, что произошло:
Контроллер находится в пространстве имён app\controllers.
В коде вы используете класс app\models\ChanelsSetting. Так как в начале нет знака \, PHP считает, что указано относительное имя, а потому добавляет в начало текущее пространство имён
app\controllers + app\models\ChanelsSetting = app\controllers\app\models\ChanelsSetting

Если бы вы указали \ в начале (\app\models\ChanelsSetting) PHP посчитал бы имя абсолютным, и такого недоразумения не было бы.
Подробнее о том, как PHP работает с пространствами имён читайте тут:
https://www.php.net/manual/ru/language.namespaces.php


text:
Q: How to get data from MySql relation table in Prisma In datamodel.graphql
type Ride {
 rideId: String
 productId: String
 passenger: Passenger
 origin: Origin
 destination: Destination
 dateTime: DateTime
 feedback: String
}

type Passenger {
 id: ID! @unique
 firstName: String
 lastName: String
}

type Destination {
 # The unique ID of the destination.
 id: ID! @unique
 latitude: Float
 longitude: Float
 address: String
}

type Origin {
 id: ID! @unique
 latitude: Float
 longitude: Float
 address: String
}

type Report {

 productId: String
 passenger: Passenger
 description: String
}

I deployed this data model and generates a MySql Db, auto queries, mutations with this.
It creates a "Ride", "Passenger", "Report" and "Origin" table in MySql. But it didn't create any column for passenger, origin, destination in "Ride" table.
It separates creates a relation table for this like _PassengerToRide, _OriginToRide, and _DestinationToRide.
Lack of relation establishment in "Ride" table, I couldn't get the details from Passenger, Origin and Destination tables when I query "rides()". Is this the correct way to define the datamodel.graphql. (edited)

A: Based on your description, this query should "just work":
query {
  rides {
    feedback
    passenger {
      id
    }
    origin {
      id
    }
    destination {
      id
    }
  }
}

Prisma uses the relation table approach you mentioned to keep track if relations between two nodes, for example table _OriginToRide relates to relation @relation(name: "OriginToRide") from your datamodel.
You don't have to change anything on the SQL level to connect the relations afterwards.

Note: The above applies to Prisma database connectors with activated migrations. If your connector doesn't do migrations, different approaches to represent relations are supported. The respective datamodel to support this can be generated by introspecting your existing database schema.


text:
Q: Finding eigenvectors of a rank one projection matrix From the unit vector $$u=\left(\frac{1}{6},\frac{1}{6},\frac{3}6,\frac{5}6\right)$$ construct the rank one projection matrix
$$P=uu^t.$$

*

*a) Show that if $P=uu^t$ , then $u$ is an eigenvector with $\lambda=1$.

*b) If $v$ is perpendicular to $u$, show that $Pv=0$, then $\lambda=0$

*c) Find three independent eigenvectors of $P$ all with eigenvalue of $\lambda=0$.

A: *

*$Pu$ is an eigenvector means that $Pu = \lambda$. We have $Pu = uu^t u$, which equals what?

*$v$ perpendicular to $u$ means $u^t v = 0$. Now compute $Pv$.

*By using the above problem, finding three vectors $v_1, v_2, v_3$ such that $Pv_i = 0$ for each $i$ is the same as finding three vectors each perpendicular to $u$. See if you can set up an equation to solve for all vectors perpendicular to $u$.


text:
Q: File b'train.csv' does not exist even though file exist Code:
import pandas as pd
train_df = pd.read_csv("train.csv")

Error:
FileNotFoundError                   Traceback (most recent call last)
    <ipython-input-17-05c7c432b69f> in <module>()
      1 import pandas as pd
      2
    ----> 3 train_df = pd.read_csv("../input/train.csv")

    /anaconda3/lib/python3.6/site-packages/pandas/io/parsers.py in parser_f(filepath_or_buffer, sep, delimiter, header, names, index_col, usecols, squeeze, prefix, mangle_dupe_cols, dtype, engine, converters, true_values, false_values, skipinitialspace, skiprows, nrows, na_values, keep_default_na, na_filter, verbose, skip_blank_lines, parse_dates, infer_datetime_format, keep_date_col, date_parser, dayfirst, iterator, chunksize, compression, thousands, decimal, lineterminator, quotechar, quoting, escapechar, comment, encoding, dialect, tupleize_cols, error_bad_lines, warn_bad_lines, skipfooter, skip_footer, doublequote, delim_whitespace, as_recarray, compact_ints, use_unsigned, low_memory, buffer_lines, memory_map, float_precision)
    707                     skip_blank_lines=skip_blank_lines)
    708
    --> 709         return _read(filepath_or_buffer, kwds)
    710
    711     parser_f.__name__ = name

    /anaconda3/lib/python3.6/site-packages/pandas/io/parsers.py in _read(filepath_or_buffer, kwds)
    447
    448     # Create the parser.
    --> 449     parser = TextFileReader(filepath_or_buffer, **kwds)
    450
    451     if chunksize or iterator:

    /anaconda3/lib/python3.6/site-packages/pandas/io/parsers.py in __init__(self, f, engine, **kwds)
    816             self.options['has_index_names'] = kwds['has_index_names']
    817
    --> 818         self._make_engine(self.engine)
    819
    820     def close(self):

    /anaconda3/lib/python3.6/site-packages/pandas/io/parsers.py in _make_engine(self, engine)
    1047     def _make_engine(self, engine='c'):
    1048         if engine == 'c':
    -> 1049             self._engine = CParserWrapper(self.f, **self.options)
    1050         else:
    1051             if engine == 'python':

    /anaconda3/lib/python3.6/site-packages/pandas/io/parsers.py in __init__(self, src, **kwds)
    1693         kwds['allow_leading_cols'] = self.index_col is not False
    1694
    -> 1695         self._reader = parsers.TextReader(src, **kwds)
    1696
    1697         # XXX

    pandas/_libs/parsers.pyx in pandas._libs.parsers.TextReader.__cinit__()

    pandas/_libs/parsers.pyx in      pandas._libs.parsers.TextReader._setup_parser_source()

FileNotFoundError: File b'../input/train.csv' does not exist

Please help! I tried using pd.read_csv("../input/train.csv") but there is still an error. I am a Mac user using Jupyter notebook.

A: *

*Are you sure you have the correct path?

 train_df = pd.read_csv("./input/train.csv")
(if the csv file is in the input folder which is in the same folder as your jupyter notebook)
Easiest would be you have a folder which contains the juptyer notebook and the csv file. Then you would just need to do:
 train_df = pd.read_csv("./train.csv")  or
 train_df = pd.read_csv("train.csv")

*Try using
 train_df = pd.read_csv("train.csv",encoding='utf-8' )
to get rid of the 'b in front of b'../input/train.csv'

A: Try using an absolute path like this. The r at the beginning of the line helps to read the whole string as a raw string as it is, so when r is used, you don't have to worry about escaping slashes
import pandas

myFile = pandas.read_csv(r"C:\Users\samarnat\Documents\Personal Docs\Projects\train.csv",encoding='utf-8')

A: I faced exact problem yesterday, following points helped me to resolve the problem

*

*No combination filePath was working out for me.

*I manually added full path to file and it worked for me.

So now I have added single line of code to my code and it works all the time regardless of folder structure. Providing absolute path of file is the key.
csv_file_abs = os.path.abspath(csv_file)
print(f'ABS PATH: {csv_file_abs}')
df = pd.read_csv(csv_file_abs)

I hope this will help, please share your thoughts if this problem can be solved in other ways, this was quick-fix.

A: Possible Reasons:

*

*Path entered is incorrect or multiple folders of same name.

*The name of the file is incorrect.

*The file extension is not csv, it maybe xlsx (Rare chance)

Hope this helps.

A: Try to give an absolute path of the file rather than giving a relative one.

A: I found, if you are using a new version of Excel extension, you will face the problem.
First of all save the file eg.

*

*save as fileName = test

*below name section select

*

*CSV UTF-8 (Comma Delimited )(*.csv)

now use Jupyter
import pandas as pd
test = pd.read_csv("test.csv")

A: Check for empty spaces space characters at the beginning or end of your file string.

A: find out the directory you're working with using !pwd. Then upload the dataset in the same place. Then copy and paste the path of the directory in pd.read_csv command
    > df=pd.read_csv('/home/jovyan/demo/melb_data.csv')

what you're missing in the address is probably the jovyan term

A: if your text or csv file is in same folder where your jupyter notebook then instead of writing pd.read_csv('test.csv') write as pd.read_csv("test") bcz if your csv file explicitly shows .csv extension then only first way work or else second way.
for example if your file name looks like "test" then use pd.read_csv('test')
            or else filename is "test.csv" then use pd.read_csv('test.csv')
It depend on saving name of file.


text:
Q: Platform independent JavaScript: Check existence of DOM What is the best and safest (not shortest/fastest) solution for (cross-browser/-platform) checking the existence of the document object (and maybe the window object if necessary)?
(function(root, undefined) {

    var document = false;

    if(typeof root.document === "object" && root.document !== null)
        document = root.document;

    // ...

    if(document !== false)
        doMyFancyClientSideStuff();

})(this);

Is typeof window.document in browsers always "object"? Or is there maybe anything like a work-around needed to make sure that our received object is really the DOM type of object, like window.document instanceof window.Document, and not just a self made object or what else.

A: Your definition of "Cross-Browser" is pretty cruicial here. I'd actually recommend to check for the [[Class]] property like:
Object.prototype.toString.call( root.document );

That should return [object HTMLDocument] in modern'ish browsers (or [object Undefined]). To also include IE8+ on this list, we need to call
if( "" + this.document === '[object HTMLDocument]' ) { }

This would create a list of

*

*IE8+

*Chrome

*Firefox

*Safari

*Opera (I don't know, but think so)

IE<8 will always return [object] on the window.document [[Class]]. This is at least, the most accurate check I can think of. You can of course, also just check something like
if( 'document' in this ) { }

but that is no guarantee that we are talking about an actuall DOM object, just that there is a property called document in the global object.


text:
Q: Displaying vertex coordinates of polygon or line without creating new layer in QGIS I am wondering if there is a way to display coordinates for each vertex of a polygon by only using expressions, without creating a new layer. So this question is basically inspired by Displaying vertex coordinates of a polygon on a map in QGIS and enhancing it.
I thought about creating an array containing all vertices as geometry. So I have created this expression:
array_foreach( -- Go throuth every element of the following array
    string_to_array(geom_to_wkt(nodes_to_points($geometry)),','), -- Create the array of WKT information splitted by comma [ 'MultiPoint ((0.2974026 51.8987013)', '(0.00909091 51.50… ]
        make_point( -- Create a point geometry for every array content
            to_real(if(
                length(regexp_substr( -- Only create X coordinate if
                    regexp_substr(@element,'\\d.*\\d.[0-9]'),'([^ ]+)'))>0, -- everything between the Brackets of 'MultiPoint ((0.2974026 51.8987013)' before the whitespace '0.2974026' is not empty like ''
                    to_real(regexp_substr(regexp_substr(@element,'\\d.*\\d.[0-9]'),'([^ ]+)')), -- Extract the X coordinate of 'MultiPoint ((0.2974026 51.8987013)' --> 0.2974026
                    NULL -- If invalid coordinate use NULL, maybe replace with 0
            )),
            to_real(if(
                length(regexp_substr( -- Only create Y coordinate if
                    regexp_substr(@element,'\\d.*\\d.[0-9]'),'(?<=\\s).*'))>0, --  everything between the Brackets of 'MultiPoint ((0.2974026 51.8987013)' after the whitespace '51.8987013' is not empty like ''
                    to_real(regexp_substr(regexp_substr(@element,'\\d.*\\d.[0-9]'),'(?<=\\s).*')), -- Extract the Y coordinate of 'MultiPoint ((0.2974026 51.8987013)' --> 51.8987013
                    NULL -- If invalid coordinate use NULL, maybe replace with 0
            ))
        )
)

Which returns an array like [ <geometry: Point>, <geometry: Point>, <geometry: Point>, <geometry: Point>, ... ], which represents all the vertex of the polygon. One can easily extract X and Y coordinates out of it by adding x() or y() in front of make_point(), or by just adding another array_foreach() like array_foreach(*expression above*,x(@element)).
How could I use such an array to label every vertex with its coordinates? I thought of extracting them from the array, but cant iterate over it. Would this be possible? Or something similar? I am kind of stuck now...

A: There is still something to copy from OpenJUMP (and improve). In OpenJUMP vertex XY is available as a decoration. Unfortunately the font or the numbers is tiny and there is no user interface for changing it.

EDIT
I was reading the question too fast and used wrong decorations first.

A: There is a way to display the coordinates... though not as a label.
One can add style with geometry generator to extract the vertices, then add a font marker style that will be overridden to display the vertices coordinates..

*

*add the vertices

Add a style of type geometry generator, geometry type point computed with the expression nodes_to_points( $geometry)

*Style it as a Font Marker

*Instruct to display the coordinates

Scroll down and click the box to the right of character(s) to edit the data-defined override. Enter the following expression
round(x( geometry_n( $geometry, @geometry_part_num )),4) || ' - ' || round(y( geometry_n( $geometry, @geometry_part_num )),4)

Let's break it down a bit:
geometry_n( $geometry, @geometry_part_num )) --> get the nth geometry from the one being rendered. From step 1, the geometry being rendered is an array of point (each vertices). Because we use @geometry_part_num, it is applied on every part (= on every vertex).
x(..) and y(...) -> the x/y coordinates of the point
round(..) --> let's not display 18 decimals :-)
|| ' - ' || --> Concatenate the X and Y coordinates, separate them with a -


text:
Q: mapping automatically Box.com and Php I am trying to design an Application which can create folder and retrieve that folder from box.com using PHP, I have tried lots of APIs but fail.
Also I want to create the folder with automatic authentication.
I have tried https://developers.box.com/docs/ but can't do automatic authentication.
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://api.box.com/oauth2/token");
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_ENCODING,"Content-Type:application/x-www-form-urlencoded");
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
    curl_setopt($ch,    CURLOPT_CUSTOMREQUEST,"POST");
    curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded", 'Accept: application/json'));
    curl_setopt($ch, CURLOPT_POSTFIELDS,array('client_id=MY_CLIENT_ID&client_secret=MY_CLIENT_SECRET_KEY&grant_type=urn:box:oauth2:grant-type:provision&username=MY_EMAIL'));
    $result = curl_exec($ch);
    curl_close($ch);
    print_r($result);

*

*here i use my client id, secret key and my email id which are register in box.com

IT Gives Some Kind of error:

{"error":"invalid_client","error_description":"The client credentials
  are invalid"}

A: I would recommend using this BoxPHPAPI. I have used it on a big enterprise app. You have to make sure first that you have a app created at developers.box.com.
Once that is done you can pass all that info to the BoxPHPAPI Class and it should handle your login and authentication.
If you plan on doing many API calls at once or rapid succession I recommended you use curl pooling. It speeds it up quite a bit. From about 4 seconds to under 1 (for 5+ API calls). You can see an example of the pooling in this fork of the BoxPHPAPI.
I hope this helps!


text:
Q: Encode Decode using python I have this function in python
Str = "ü";
print Str

def correctText( str ):
  str = str.upper()
  correctedText = str.decode('UTF8').encode('Windows-1252')
  return correctedText;

corText = correctText(Str);
print corText

It works and converts characters like ü and é however it fails when i try � and ¶
Is there a way i can fix it?

A: According to UTF8, à and ¶ are not valid characters, meaning that don't have a number of bytes divisible by 4 (usually). What you need to do is either use some other kind of encoding or strip out errors in your str by using the unicode() function. I recommend using the ladder.

A: What you are trying to do is to compose valid UTF-8 codes by several consecutive Windows-1252 codes.
For example, for ü, the Windows-1252 code of à is C3 and for ¼ it's BC. Together the code C3BC happens to be the UTF-8 code of ü.
Now, for Ã?, the Windows-1252 code is C33F, which is not a valid UTF-8 code (because the second byte does not start with 10).
Are you sure this sequence occurs in your text? For example, for à, the Windows-1252 decoding of the UTF-8 code (C3A0) is à followed by a non-printable character (non-breaking space). So, if this second character is not printed, the ? might be a regular character of the text.
For ¶ the Windows-1252 encoding is C2B6. Shouldn't it be ö, for which the Windows-1252 encoding is C3B6, which equals the UTF-8 code of ö?


text:
Q: Update one table based on values in another table using case statement (MYSQL) I am trying to run the below query to update a table based on values in another table using case statement. And i get the following error.
Error Code: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'from tbl_a as a, tbl_b as b
  WHERE a.DIV_NO = b.' at line 12

Here is the query:
UPDATE a
  SET
    a.MIN_5 = b.Min_Five,
    a.IN_PR = b.Ad_Flag ,
    a.FRC = (
                    CASE
                       WHEN b.Prc_Fl = 'N' THEN 'Y'
                       WHEN b.Prc_Fl = 'Y' THEN 'N'
                       ELSE 'D'
                    END
            )
  FROM tbl_a AS a, tbl_b AS b
  WHERE a.DIV_NO = b.Div_num
    AND a.OFR_ID = b.Flg ;

A: Try this with JOIN
UPDATE
  tbl_a AS a
  JOIN
  tbl_b AS b ON (a.DIV_NO = b.Div_num AND  a.OFR_ID = b.Flg)
  SET
  a.MIN_5 = b.Min_Five,
  a.IN_PR = b.Ad_Flag,
  a.FRC =
    CASE
      WHEN b.Prc_Fl = 'N'
      THEN 'Y'
      WHEN b.Prc_Fl = 'Y'
      THEN 'N'
      ELSE 'D'
    END


text:
Q: Tell server to not run the code when there is an error I am looking for a way to tell the server to die when there is an error.
Examples: Let's say there are 2SQL queries. If one of them does an error, I want none of them to work, as if nothing has been clicked.
Example 2: When you miss a semicolon or similar on your code, but the other parts of your code still works and displays something that isn't supposed.
Something like
if (error) {
do nothing and go back to index page;
}

A: Exception handling is available in PHP since version 5.  It allows you to have a more fine-grained control over code when things go wrong ie, when exceptions occur.
Put your codes inside try block. if an error occur then the code inside your catch block will run. There is also one more bock. i.e finally (PHP 5.5) which will be called every time your code will run. You can hierarchically use these blocks.
Useful link: https://adayinthelifeof.nl/2013/02/12/php5-5-trycatchfinally/
try {

//Your codes

} catch (Exception $e) {
   //when above codes gives error
   do nothing and go back to index page;
}

A: You can always send a redirect and call die()/exit() to stop execution of the current script.
if (error) {
header("Location: http://example.com/index.php");
die();
}

Or surround your code with try/catch and send the redirect inside the catch block:
 try {
      //code where an error could occur

 } catch (Exception $e) {
     header("Location: http://example.com/index.php");
    die();
 }


text:
Q: Python wrapper to access Hg, Git and possibly Bazaar repositories? I'm looking for a Python library that can do basic manipulation of repositories, but is independent of the backend version control system.
By basic manipulation, I'm referring to: initialize a repo, add files, commit, pull, push, get current revision number.
Users of the library could do something this:
import dvcs_wrapper as dvcs
dvcs.set_backend('hg')  # could choose 'git', 'bzr'

repo = dvcs.init('/home/me/my_repo')
repo.add('/home/me/my_repo/*.py')
repo.commit('Initial commit')
repo.push('http://bitbucket.org/....')
print('At revision %d' % repo.revision_num)

Any pointers to something like the above? My Google searches turn up nothing...
Update: for what it's worth, I've started working on something like this: code is here with unit tests
for Hg repositories. I might get around to Git and Bazaar; contributions welcome.

A: There's also the VCS module, which advertises:

vcs is abstraction layer over various version control systems. It is
  designed as feature-rich Python library with clean API.

A: I think you are out of luck.
There are Python wrappers for git but according to this the quality is still less than optimal. Hg and bzr are Python projects but their infrastructure is quite different, so API level integration is not easy.  Also different SCMs have different design philosophies, which makes a unified wrapper less plausible.
That being said, if you do need a simple wrapper, you can use the subprocess module and wrap the command lines to get the result you want.


text:
Q: Chrome extension : Create new tab and attach a listener I would like to create an extension that when I click the extension icon opens a list of websites, then when I click of an item of the list a new tab is open with the selected website. I was able to create that scenario, but I would like to full fill some fields of the opened website in the new tab. Does it possible?
You will see in my code that I tried to open an alert on the new opened website, but nothing
Any help would be very much appreciated.
Best Regards,
Jerôme.
My script :
From manifest :
"browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html",
    "default_title": "Click here!"
  },

from popup.html

    <title></title>

        website1
        website2
        website3

from popup.js
$(function() {
    $('.link').click(function(){

        var href = $(this).attr('href');
        var websitename = $(this).attr('name');

        // Open a new tab with the selected website.
        chrome.tabs.create({url:href,active: true}, function(tab){

                alert("Alert on the opened website");

        });

    });
});


text:
Q: only fetch the diff when I run apt update on mobile phone with monthly data limit? I am running Ubuntu 20.04. I connect to internet via mobile phone with monthly data limit. When I run
apt update

it fetches about 60 MB data from repositories. Is there a way to only fetch the diff between previous running of apt update?
EDIT:
sudo apt update
Hit:1 http://archive.canonical.com/ubuntu focal InRelease
Hit:2 http://archive.ubuntu.com/ubuntu focal InRelease
Get:3 http://archive.ubuntu.com/ubuntu focal-updates InRelease [114 kB]
Get:4 http://archive.ubuntu.com/ubuntu focal-security InRelease [109 kB]
Get:5 http://archive.ubuntu.com/ubuntu focal-backports InRelease [101 kB]
Get:6 http://archive.ubuntu.com/ubuntu focal-updates/main Sources [364 kB]
Get:7 http://archive.ubuntu.com/ubuntu focal-updates/multiverse Sources [9,912 B]
Get:8 http://archive.ubuntu.com/ubuntu focal-updates/restricted Sources [10.1 kB]
Get:9 http://archive.ubuntu.com/ubuntu focal-updates/universe Sources [146 kB]
Get:10 http://archive.ubuntu.com/ubuntu focal-updates/main amd64 Packages [795 kB]
Get:11 http://archive.ubuntu.com/ubuntu focal-updates/main Translation-en [192 kB]
Get:12 http://archive.ubuntu.com/ubuntu focal-updates amd64 Contents (deb) [29.7 MB]
Get:13 http://archive.ubuntu.com/ubuntu focal-updates/restricted amd64 Packages [143 kB]
Get:14 http://archive.ubuntu.com/ubuntu focal-updates/restricted Translation-en [21.3 kB]
Get:15 http://archive.ubuntu.com/ubuntu focal-updates/universe amd64 Packages [736 kB]
Get:16 http://archive.ubuntu.com/ubuntu focal-updates/universe Translation-en [152 kB]
Get:17 http://archive.ubuntu.com/ubuntu focal-updates/multiverse amd64 Packages [16.9 kB]
Get:18 http://archive.ubuntu.com/ubuntu focal-updates/multiverse Translation-en [5,076 B]
Get:19 http://archive.ubuntu.com/ubuntu focal-security/universe Sources [42.9 kB]
Get:20 http://archive.ubuntu.com/ubuntu focal-security/main Sources [122 kB]
Get:21 http://archive.ubuntu.com/ubuntu focal-security/restricted Sources [8,960 B]
Get:22 http://archive.ubuntu.com/ubuntu focal-security/main amd64 Packages [480 kB]
Get:23 http://archive.ubuntu.com/ubuntu focal-security/main Translation-en [105 kB]
Get:24 http://archive.ubuntu.com/ubuntu focal-security amd64 Contents (deb) [23.6 MB]
Get:25 http://archive.ubuntu.com/ubuntu focal-security/restricted amd64 Packages [120 kB]
Get:26 http://archive.ubuntu.com/ubuntu focal-security/restricted Translation-en [17.6 kB]
Get:27 http://archive.ubuntu.com/ubuntu focal-security/universe amd64 Packages [532 kB]
Get:27 http://archive.ubuntu.com/ubuntu focal-security/universe amd64 Packages [532 kB]
Get:28 http://archive.ubuntu.com/ubuntu focal-security/universe Translation-en [74.5 kB]

Take a look at these :
Get:12 http://archive.ubuntu.com/ubuntu focal-updates amd64 Contents (deb) [29.7 MB]

Get:24 http://archive.ubuntu.com/ubuntu focal-security amd64 Contents (deb) [23.6 MB]

A: As @nobody has alluded to, these big files that you're downloading are coming from apt-file. Based on the docs, you can configure this by modifying the /etc/apt/apt.conf.d/50apt-file.conf file and running /usr/share/doc/apt-file/examples/apt-file-2-update.sh.
From there, you can set up a local cache for these .deb files with something like:
$ mkdir -p ~/.cache/apt-file ~/.config
$ touch ~/.cache/apt-file/dpkg-status
$ sed '/^Dir::State/ d; /^Dir::Cache/ d;' \
       /usr/share/doc/apt-file/examples/apt-file.conf \
       > ~/.config/apt-file.conf
$ cat <<EOF >> ~/.config/apt-file.conf
       Dir::State "$HOME/.cache/apt-file";
       Dir::Cache "$HOME/.cache/apt-file";
       Dir::State::status "$HOME/.cache/apt-file/dpkg-status";

From there you could update the apt-file cache independently from apt by calling:
$ apt-file -c ~/.config/apt-file.conf update

This was taken directly from the manpage, so some tweaking may be required.


text:
Q: Webscaping table data with drop down menu help in either Pandas, Beautiful Soup or Selenium I am trying to scrape data from this website:
https://www.shanghairanking.com/rankings/grsssd/2021
Initially pandas gets me out the gates and I can scrape the table but I am struggling with the drop down menus. I want to select the options next to the total score box which are PUB, CIT, etc. When I inspect the element it looks like maybe Javascript and the usual methods of interating over these options don't work. I have tried Beutifalsoup and most recently Selenium to select the drop downs by hand. This works for the default table data
'''
import time
import pandas as pd
from selenium import webdriver
from selenium.webdriver.support.ui import Select
driver = webdriver.Chrome('/Users/martinbell/Downloads/chromedriver')
driver.get('https://www.shanghairanking.com/rankings/grsssd/2021')
submit = driver.find_element_by_xpath("//input[@value='CIT']").click()

'''
Doesn't get me anywhere.

A: Your code would not work as you first have to click the dropdown open and then traverse through the options in the dropdown. Here is the refactored code.
Note that I have used time.sleep for instant purposes but for a robust code and good practice, use explicit wait such as WebdriverWait
driver.get('https://www.shanghairanking.com/rankings/grsssd/2021')
time.sleep(10)
driver.find_element(By.XPATH, "(//*[@class='inputWrapper'])[3]").click()
#The below commented code loops through all the dropdown options and performs actions.
# opt_ele = driver.find_elements(By.XPATH, "(//*[@class='rank-select'])[2]//*[@class='options']//li")
# for ele in opt_ele:
#     print(ele.text)
#     ele.click()
#     print('perform your actions here')
#     driver.find_element(By.XPATH, "(//*[@class='inputWrapper'])[3]").click()

# If you do not want to loop through but just want to select only CIT, here is the line:
driver.find_element(By.XPATH, "(//*[@class='rank-select'])[2]//*[@class='options']//li[text()='CIT']").click()


text:
Q: Problem with struct when I split the functions from main I have a struct in my main let's say:
struct node
{
    char name[N];
    int num;
    char **group;
    int groupsize;
    struct node * next;
};

and I have my functions to other .c and .h files call myfuncs.c.h
myfuncs.h
void create_node(struct node **, struct node **, int, int, char **, int);
void display(struct node *head);
void start_joseph(struct node **, int, int);

and myfuncs.c
void create_node(struct node **, struct node **, int, int, char **, int);
{
  do something;
}

void display(struct node *head);
{
  do something;
}

void start_joseph(struct node **, int, int);
{
  do something;
}

but I get this error
[Warning] 'struct node' declared inside parameter list
[Warning] its scope is only this definition or declaration, which is probably not what you want

Should I define the struct to the pre-processor or what?

A: Put the structure definition in the header before the function declarations that use it.
At minimum, you need a line:
struct node;

in the header before the function declarations.  Since you don't appear to be trying to create an opaque type (the details of which would be hidden from the code using it), then embedding the entire structure definition is reasonable.  Note that you then delete that definition from the code holding the main() function.
What the error message says is that if you write:
void create_node(struct node **, struct node **, int, int, char **, int);

and there is no previous mention of the type struct node, then the type name is created but only exists for that one function declaration.  The next function that refers to struct node creates a new type name struct node which is different from and incompatible with the previous one.  By declaring struct node; at file scope, you're saying "there is a type struct node".  Basically, you have to have something outside the scope of a prototype that says "there is a type struct node" which the function prototype can then use.
Suggested solution — myfuncs.h:
#ifndef MYFUNCS_H_INCLUDED
#define MYFUNCS_H_INCLUDED

struct node
{
    char name[N];
    int num;
    char **group;
    int groupsize;
    struct node * next;
};

extern void create_node(struct node **, struct node **, int, int, char **, int);
extern void display(struct node *head);
extern void start_joseph(struct node **, int, int);

#endif /* MYFUNCS_H_INCLUDED */

The header guards prevent problems if the file is included multiple times in a single translation unit (source file plus included headers).  I use extern on function declarations to match the extern needed on variables declared in the header; many people don't.  That choice is up to you and/or the coding guidelines you work with.  Removing the extern makes no difference to the result.

A: I think you should declare node struct at other header file, e.g global.h, and include the global.h in myfuncs.h.
  // in the global.h
 struct node
 {
      char name[N];
      int num;
      char **group;
      int groupsize;
      struct node * next;
  };
  ....    ....
 // in the myfuncs.h
 #include "global.h"

A: In these function declarations
void create_node(struct node **, struct node **, int, int, char **, int);
void display(struct node *head);
void start_joseph(struct node **, int, int);

the type struct node has the  function prototype scopes of each function declaration and is not visible outside the parameter declaration lists.
The same problem exist with the function definitions. And the warnings
[Warning] 'struct node' declared inside parameter list
[Warning] its scope is only this definition or declaration, which is probably not what you want

point to this.
The declaration of the structure in main has the function main block scope and is also invisible outside the function.
You need at least declare (or define) the structure before the function declarations and the structure shall be already defined before the function definitions.
So move the structure definition from main to a point before the function declarations.
For example
myfuncs.h
struct node
{
    char name[N];
    int num;
    char **group;
    int groupsize;
    struct node * next;
};

void create_node(struct node **, struct node **, int, int, char **, int);
void display(struct node *head);
void start_joseph(struct node **, int, int);


text:
Q: Disable Paste action using Javascript (without include Jquery) I have a text box for the login mobile number, I have to disable the paste action
Am working in ReactJs, The code that I used is Mention below.
<input
 type="text"
 name="userName"
 placeholder="Mobile number"
 onChange={e => this.onChangeNumber(e)}
 value={this.state.userName}
 maxLength="10"
 autoFocus
 autoComplete="off"
/>

I want to disable the paste action using the JS code without using jquery and any other packages. Anyone help me to complete this.
Thanks in Advance.

A: If you are using the reactjs, you can directly use the onPaste event in the input tag as given below. So it will restrict the paste action.
     <input
     type="text"
     name="userName"
     placeholder="Mobile number"
     onChange={e => this.onChangeNumber(e)}
     onPaste={e => {e.preventDefault()}}
     value={this.state.userName}
     maxLength="10"
     autoFocus
     autoComplete="off"
    />

If you want use the js, you can use the following code in your function. So that the paste action will get prevented.
    onChangeNumber =()=>{
       document.getElementByName('userName').onpaste=function(e){
         e.preventDefault();
       }
     }

A: One of the many ways to do this is like

  useEffect(()=>{
    document.getElementById('ipt').onpaste=function(e){
      e.preventDefault();
    }
  },[])

  return (
    <div className="App">

      <input
          type="text"
          name="userName"
          placeholder="Mobile number"
          id='ipt'
          autoFocus
          autoComplete="off"
        />
    </div>
  );
}

Why useEffect used ?
So, that the DOM element input has initialised and does not return NULL when we document.getElementById it.
NOTE: It is generally not advisable to restrict pasting to an input field. It is annoying and affects the User Experience.
PS: I am not exactly sure why refs dont work with onpaste. maybe that would be a better REACTish way of doing it.

A: <input
 type="text"
 name="userName"
 placeholder="Mobile number"
 onChange={e => this.onChangeNumber(e)}
 onPaste={e => {e.preventDefault()}}
 value={this.state.userName}
 maxLength="10"
 autoFocus
 autoComplete="off"
/>

Simply preventing default action onPaste would do needful.

A: <input type="text" class="word"> //html code
let box = document.querySelector(".word");// javacript method
//Disable Paste Event
box.onpaste = function () {
    return false;
}


text:
Q: Connecting Visual Studio 2010 to Oracle What is the easiest way to connect Visual Studio 2010 to an Oracle database not hosted on my local machine. Can anyone please link me to a tutorial that will help me do this as I have only ever connected using VB6 and ODBC. Or please provide me the steps involved in connecting Visual Studio 2010 to Oracle.

A: The easiest is probably to use ODP.net which is Oracle's official library to connect to Oracle databases (tutorials available on the linked web site)


text:
Q: Unable to create PermGen error This is homework, not going to lie. I need to write a program which will generate "java.lang.OutOfMemoryError: PermGen space" error.
Since I wasn't able to attend the lecture, I did hours of research yesterday and this is what I have so far.
At first I created a program and I got constantly this error:
java.lang.OutOfMemoryError: GC overhead limit exceeded

Okay, so I did some more research and understood that I didn't get PermGen error because, although that I created objects(String objects) I didn't use them again, so they were considered Garbage. So I changed my code and got constantly this:
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space

So this is the code I had at that point:
import java.util.ArrayList;
import java.util.List;

public class Test {

public static void main(String[] args) {
    List<String> test = new ArrayList<String>();
    test.add(new String(""));

    for (;;) {
        for (int i = 0; i<test.size(); i++){
            test.add(test.get(i));
        }
    }
}
}

Also under VM arguments I had "-XX:PermSize=2m" (I have tried different values).
I was told that my code is wrong because it uses the same String over and over. So I tried to change that but I was still unsuccessful.
Then I found this code: (Algorithms that lead to java.lang.OutOfMemoryError: PermGen space error)
Random rnd = new Random();
List<String> interned = new ArrayList<String>();
for (;;) {
    int length = rnd.nextInt(100);
    StringBuilder builder = new StringBuilder();
    String chars = "abcdefghijklmnopqrstuvwxyz";
    for ( int i = 0; i < length; i++ ) {
        builder.append(chars.charAt(rnd.nextInt(chars.length())));
    }
    interned.add(builder.toString().intern());
}

So if I understand correctly this should give me PermGen error? But I still get java heap error.
Also I found this:
http://javaeesupportpatterns.blogspot.com/2011/10/java-7-features-permgen-removal.html
Again if I understand correctly, then when using java7 maybe the java heap space error is the one I should be getting? That it's not possible to get PermGen error anymore? Okay, so I've tried to change the compiler and project version to java 6. But still got Java heap space error.
I know it's my fault that I didn't attend the lecture, but I could use some help to understand what am I doing wrong here or what am I missing?

A: First, simple one liner how you can reproduce perm gen error (just recursively call main):
public class PermGenError {
    public static void main(String[] args) {
        main(new String[] { (args[0] + args[0]).intern() });
    }
}

Should be launched with parameters:
whatever -XX:PermSize=8M -XX:MaxPermSize=8M

Second, why your example its not producing perm gen error? You usage of string intern is correct. However in latest JMV specification java virtual machine can move internalized strings out from permanent generation to another one. Real life scenario (happened on production :-) ) is that you could see perm gen 99% full, application extremely slow and jvm not throwing any erros because its constantly reshuffling objects between generations.
Third, the best paper which I've read and constantly referring to for any GC/Memory issue is Tuning Garbage Collection with the 5.0 Java[tm] Virtual Machine
EDIT:
Update to question is:

Example works fine, but still doesn't work when I'm specifying large perm
  size - getting 'Java heap space'

Update to answer is:
There are two aspets you need to be aware when specifying larger perm gen size:

*

*All objects first go to one of younger generations. Therefore if your perm gen size is bigger than size of first generation Java heap space will be thrown first. In this particular example I'm using one large string which exceeds perm gen size in order to reproduce error. If you want to reproduce 'PermGen space' then you need to specify heap size as well. For example:

*

*-Xms2048m -Xmx2048m -XX:PermSize=512M -XX:MaxPermSize=512M - will result in 'PermGen space' (large heap, small perm gen)

*-Xms512m -Xmx512m -XX:PermSize=2048M -XX:MaxPermSize=2048M - will result in 'Java heap space' (small heap, large perm gen)

*Second aspect is that the heap is divided into generations and memory in heap itself is fragmented. So when you specifying heap size of 512M you cant fit string of half a gigabyte long into memory (because string internally implemented as array and need to be stored as one sequential chunk in memory). The largest you could fit is probably around half that size(it depends on how badly memory is fragmented).

A: The PermGen Space is the memory area, where Java stores class definitions and internal data (which is not the data your application creates and uses). So basically you don't really need a big and/or clever application. This blog page documents briefly, how the Java memory is structured and what are the responsibilities of the different areas.
In theory you get the exception pretty quickly by defining a low perm gen space (as you already did with -XX:PermSize=2m). Then you add a couple of libraries to your applications classpath (Apache commons, maybe HTMLUnit or stuff like that). Download a couple of jars and you'll get this error as soon as the application starts and the classloader is trying to store the class definitions of your jars in the PermGen space.
If this doesn't work try using Tomcat, deploy some libraries and reload the application over and over via the web-app manager.
If you need an algorithm, which causes this problem, you can debug your running application with the JVM paramter -XX:+PrintGCDetails. This will show you the size of the PermGen space used every time the GC was used. This helps you to see whether you go into the right direction and which memory area you fill. The PermGen space stores arrays having references to methods as well, so this could solve your problem as well.

A:
So if I understand correctly this should give me PermGen error? But I still get java heap error.
java.lang.OutOfMemoryError: GC overhead limit exceeded

Yup.  What is going on is that you are hitting a JVM mechanism that is designed to stop the a program that is likely to run out of memory from spending too much time in the process.
See GC overhead limit exceeded
You can disable this using the -XX:-UseGCOverheadLimit switch.  I expect you will then get OOME's that say that you are out of permgen memory.

If you are now getting this:

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space

then the problem is that your regular heap is running out of space before you run out of permgen space:

*

*Increase the regular heap size.

*Make sure that your application keeps references to all of those intern'ed Strings.  (If they become unreachable. they will be garbage collected and you won't run out of permgen space.)


text:
Q: How to use the post_updated hook before and after arguments I want to check if the title of the post has changed and do some stuff if it did.
I thought of using the post_updated hook, the codex says "Use this hook whenever you need to compare values before and after the post update.", but i can't figure out how to use the before and after arguments.
function check_values($post_ID, $post_after, $post_before){
        echo 'Post ID:';
        var_dump($post_ID);

        echo '
Post Object AFTER update:';
            echo '
';
            print_r($post_after);
            echo '
';

        echo '
Post Object BEFORE update:';
            echo '
';
            print_r($post_before);
            echo '
';
    }

    add_action( 'post_updated', 'check_values', 10, 3 );

and i'm echoing it echo check_values($post->ID, get_post(),get_post()); inside a metabox.
Currently I'm getting the same values.
If i echo check_values(); I get missing argument error and on echo check_values($post_ID, $post_after, $post_before) i get NULL.
How can i get the values before and after the update?
Update
function check_values($post_ID, $post_after, $post_before){
    if ($post_before->post_title != $post_after->post_title) {
        // do stuff
    }
}
add_action( 'post_updated', 'check_values', 10, 3 );

A: First off you are using the function wrong. The function is tied to an action within wordpress whenever you use the add_action function. In this case you have added it to the post_updated action.
Basically your check_values function gets added to a queue which will then get called by the action when its time to do the action.
You can see where the action gets called here: https://core.trac.wordpress.org/browser/tags/4.4/src/wp-includes/post.php#L3359
See line 3359 of this file. There is a function called do_action and its going to call all the functions tied to the post_updated action. This would include your check_values function. This is where your function is getting called and as you can see it passes in the necessary parameters for your function to interact with.
Try updating or adding a post. You should see some output there because this is when wordpress is calling your function.
Then in order to check to see if there was a change compare the two titles from the two before and after post objects
<?php

function check_values($post_ID, $post_after, $post_before){
    if( $post_after->post_title !== $post_before->post_title ) {
        // do something
    }
}

add_action( 'post_updated', 'check_values', 10, 3 );
?>

A: When I used this action "post_updated" and update the post from latest updated gutenburg editor that time I get same post name in before post and after post details array.
It means suppose post name is "abc-test" and I changed this to a new post name as "abc-test-2" then I get "abc-test-2" name in both post after and before details.
Why its showing same data?
Thanks in advance.


text:
Q: No module named django-admin estoy empezando un curso de Django, en un momento del video, me dice que tengo que poner el siguiente codigo "python -m django-admin starproject Proyecto1", pero a mi me da el siguiente error al ejecutarlo en la cmd
"python.exe: No module named django-admin"
¿Alguien sabe como solucionarlo?.
Les dejo el link del video: https://www.youtube.com/watch?v=2DbWqyBR4Oo&ab_channel=pildorasinformaticas
Desde el minuto 7:50

A: Puedes resolver el problema si escribes el directorio completo en el que se ubica tu archivo django-admin.py
python C:\Python37\Scripts\django-admin.py startproject mysite


text:
Q: Combine geom_function and geom_ribbon in ggplot2 I would like to highlight the area between two function curves plotted with geom_function.
For example, I create two curves:
ggplot() + geom_function(fun = function(x){x^2}) + geom_function(fun = function(x){x^2 + 1})

How can I highlight the area between these curves? I think geom_ribbon might be the answer, but all the example code I saw for geom_ribbon used a dataset for mapping. How can I do that with geom_function, i.e. curves only based on a function and not on actual data?


text:
Q: Conventions for dealing with vectors of std::tr1::shared_ptr I've started using std::tr1::shared_ptr and so far I'm quite liking it. I understand some of the pitfalls (e.g. two classing containing smart pointer members to each other). But there are other cases which I'm unsure about whether to use smart pointer or not.
E.g.
class Scene;
typedef shared_ptr<Scene> ScenePtr;

Class SceneManager {
public:

   int size() { return _scenes.size(); }
   ScenePtr scene(int i) { return _scenes[i]; }

private:
   vector<ScenePtr> _scenes;
}

This is all good and working nicely. However, if I have an external controller, is there any disadvantage of doing:
for(int i=0; i<_sceneManager->size(); i++) {
   ScenePtr scene = _sceneManager->scene(i);
   scene->doSomething();
}

here 'scene' will obviously increase the reference count of each ScenePtr, but then decrease it again when it goes out of scope. But is there any performance (or any other) disadvantage?
Alternatively I could use a normal C pointer
for(int i=0; i<_sceneManager->size(); i++) {
   Scene* scene = _sceneManager->scene(i).get();
   scene->doSomething();
}

But is this actually any better? or is it identical? Does the reference count get increased? (on the function call), but then decreased as soon as it leaves the first line?
I often used to use a reference, would that have any complications?
for(int i=0; i<_sceneManager->size(); i++) {
   Scene& scene = *_sceneManager->scene(i);
   scene.doSomething();
}

And finally, is it even a good idea to return a ScenePtr at all, or should SceneManager::scene(i) return a (Scene*) or even (Scene&)?
Similarly, to do an ordered map I often used to use:
vector _scenesArray;
map _scenesMap;
So I can access the objects by name, or in order. Using std::tr1::shared_ptr should they both be ScenePtr? or just one of them ScenePtr and the other one Scene*?

A: It all depends on the use cases.
As you suspect using the pointer or reference will save on the reference counting overhead.
...but... often the overhead isn't significant enough to worry about and:
If the sceneManager is used in multiple threads or this function needs to be reenterent safe then the safety of accessing though the shared pointer might be preferred. As in if you're not using the shared_ptr you need somehow else to be sure the object won't be destroyed.
What to return depends on if the ownership of the object is to be passed on. You must not go from a pointer to shared_ptr if the object is already in a shared pointer somewhere else. You have to pass from shared_ptr to shared_ptr or each separate chain of shared_ptrs will try to delete the object. Multiple deletion => crash.
If ownership is staying with the SceneManager then returning a reference would give easy use of the object and express the ownership intension clearly.

Similarly, to do an ordered map I often used to use: vector
  _scenesArray; map _scenesMap;

For simplicity and flexibility I'd start with them both holding shared_ptrs. If later in the unlikely situation that turns out to be a bottle neck in the application you can swithc and add logic as a performance optimization.