Error when passing an input through an object

Question: I created a method makesPerson() which takes input String[] and int[]. It is giving an error when i create an object and give the inputs as array of strings and int.It was working fine when the input were just String and int and not arrays.
public class Person {
    String name;
    int    height;
}

public class TestPerson {

    public void display(Person persons) {
        for (int i=0;i<persons.length;i++) {
            System.out.println(p.name[i]+":"+p.height[i]);
        }
    }

    public static void main(String args[]) {
        TestPerson p1=new TestPerson();

        //This is giving me error
        p1.makePerson({"joe" ,"jhon", "Alex"},{150,160,170});
    }

    public Person[] makePerson(String[] names, int[] hts) {
        Person [] persons = new Person(names.length);

        for(int i=0;i<names.length;i++) {
            Person p = new Person();

            p.name     = names[i];
            p.height   = hts[i];
            persons[i] = p;
        }

        String str = "";

        for(int i=0;i<persons.length;i++) {
            str += persons[i].height + ": :";
            System.out.println(str);
            display(persons);

            return persons;
        }
    }
}

Comment: `Person [] persons=new Person(names.length);` it makes no sense
Comment: So, what's the error?
Comment: why the question d/votes?
Answer: Change the method arguments to something like:
p1.makePerson(new String[]{"joe" ,"jhon", "Alex"}, new int[]{150,160,170});

instead of
p1.makePerson({"joe" ,"jhon", "Alex"},{150,160,170});// <- your sending String and ints not Arrays.

Also your display method is taking a array of persons not a person. so change it to:
public void display(Person[] persons) {

And in the makePerson method, you declaring array with a wrong way, it should be like:
Person[] persons = new Person[names.length];

Comment: @ Salah Yeah it pretty much solved the whole error problem.Do we always have to mention this when passing an array as input??
Comment: Yes, Or you could create an array in the normal way like to say `String[] names = new String[3];` then add values like `names[0] = "Joe";` and so on, then pass the `names` as argument like : `p1.makePerson(names, ints);`
Answer: Well, you've made several mistakes, so I've re-written your code:
public class TestPerson{

    public void display(Person[] persons)
    {
        for (int i=0;i<persons.length;i++)
        System.out.println(persons[i].name+":"+persons[i].height);
    }

    public static void main(String args[]){
        TestPerson p1=new TestPerson();
        String[] names = {"Joe" ,"John", "Alex"};
        int[] hts = {150,160,170};
        Person[] persons = p1.makePerson(names,hts);

    }

    public Person[] makePerson(String[] names,int[] hts){
        Person [] persons = new Person[names.length];

        for(int i=0;i<names.length;i++){
            Person p= new Person();
            p.name=names[i];
            p.height=hts[i];
            persons[i]=p;
        }

        display(persons);

        return persons;
    }
    public class Person{
        String name;
        int height;

    }
}

Now, I believe, it does what you've expected. Your initial error was related to a wrong array initialization during method call.
Output:
Joe:150
John:160
Alex:170

Answer: You should consider adding some safety checks to your loops. Like:
public Person[] makePerson(String[] names, int[] hts) {
    if (names.length != hts.length)
        throw new IllegalArguementException("different array sizes");

    final Person[] persons = new Person[names.length];

    for(int i = 0; i < names.length; i++) {
        Person p = new Person();

        p.name     = names[i];
        p.height   = hts[i];
        persons[i] = p;
    }

    for(int i = 0; i < persons.length; i++) {
        System.out.println(persons[i].height + ": :");
        display(persons);
    }

    return persons;
}


Getting an error with excel ole "Add method of Workbooks class failed"

Question: I am trying to open and refresh an excel 2003 spreadsheet via ole.  However I am getting the error "Add method of Workbooks class failed" with no further information.
The code works in unit tests, and works on 3 servers but fails with the error on our web server.  It is being run from a service app running under the Local System Account.
The same version of excel is installed on all servers (2003 sp3).  The file(s) in question all exist and are at the expected location.
There are no macros in the spreadsheets, but there are database queries.  The spreadsheets can all be opened.
The calling code is
if VarIsEmpty(XLApp) then
begin
  XLApp := CreateOleObject('Excel.Application');
  try
    XLApp.DisplayAlerts:=  wdAlertsNone;
  except
...
  end;
  XLApp.AutomationSecurity:= msoAutomationSecurityForceDisable;
end;

fullFileName:= ExpandReportFileName( partialFilename);
if not FileExists(fullFileName) then
  raise Exception.Create('File not found: ' + fullFileName);

XLAPP.Workbooks.Add(fullFileName);  << fail here

Any ideas on what else I can try?
Answer: I had been getting the same error for
xls.WorkBooks.Add(xlWBATWorksheet);

I changed that line to
xls.Application.Workbooks.Add;

Now it is working. You might try to get a Workbook first then try to call its methods.
Comment: thank you; that was the exact same problem i was having as well.  fixed.
Comment: It was working for years. We develop solutions to fix something that was already working. *Sigh*
Answer: Automating Office applications in a service is not supported.
While it is possible, it's very difficult, and you'll run into many problems, such as this one.  It'll also be very slow.
You should look for a Delphi component that manipulates Excel files.
Depending on what you're trying to do, you might be able to use OLE DB instead.
Answer: Workbooks.Open might be the method you're looking for
Add creates a new empty workbook. If you supply a filename, that file is used as a template for the new file - see here
Open just opens the file as you would expect - see here
Comment: Just tried that, it changes the error to "Open method of Workbooks class failed" :(
Answer: I ran into this error when I happened to have the Excel spreadsheet file selected in a Windows Explorer window, not open, just selected.  When I deselect the file, I do not get the error.
Comment: That's outrageous. I am dead inside


What is the easiest way to compare $\log_2 (72)$ with $2\pi$?

Question: I need to compare $\log_2 (72)$ with $2\pi$. What is the easiest way to do it?
Comment: Expanding on @FShrike's Hint: use $3^5<2^8,\,\pi>\frac{31}{10}$.
Comment: Compare $\log_2(3)$ with $\pi-3/2$
Comment: Sorry, I don't understand. So tough for my math skills. I just went insane and compared this logarithm with 6.25.
It turns out that 2*64^4 > 72^4, so 2$\pi$ >  $\log_2 (72)$
Answer: We first do this transformation:
$$\log_272\ \ \vee\ \ 2\pi\\
\dfrac12\cdot\log_272\ \ \vee\ \ \pi$$
The prime factorization of $72$ is $2^3\cdot3^2$. Thus by logarithmic properties we have $\log_272=\log_2(2^3\cdot3^2)=\log_22^3+\log_23^2=3\log_22+2\log_23=3+2\log_23$.
Hence $\dfrac12\cdot\log_272=\dfrac12\cdot\left(3+2\log_23\right)=\dfrac32+\log_23$.
So the inequality becomes the following:
$$\dfrac32+\log_23\ \ \vee\ \ \pi\\
\log_23\ \ \vee\ \ \pi-\dfrac32$$
Thus, we arrive at what was given by @FShrike.
Now, because $\pi\approx3.14$, and $3.14\gt3.1$, it's true that $\pi\gt3.1$, so $\pi\gt\dfrac{31}{10}$.
It's also true that $3^5\lt2^8$, so $\log_23\lt\dfrac85$ (if you wonder why, then it's because if we take logarithm base 2 of both sides of this inequality, we get $\log_23^5\lt\log_22^8\Rightarrow5\log_23\lt8\log_22\Rightarrow\log_23\lt\dfrac85$), thus $\log_23\lt\dfrac{16}{10}$.
Because $\log_23\lt\dfrac{16}{10}$, and it's true that $\dfrac{31}{10}\gt\dfrac{16}{10}$, we conclude that $\log_23\lt\dfrac{31}{10}$.
Because $\log_23\lt\dfrac{31}{10}$ and $\pi\gt\dfrac{31}{10}$, we conclude that $\log_23\lt\pi$.
Now, as $\pi\gt\dfrac{31}{10}$, by subtracting $\dfrac32$ from both sides of the inequality, we get $\pi-\dfrac32\gt\dfrac85$. But earlier we have found out that $\log_23\lt\dfrac85$, so it's true that $\log_23\lt\pi-\dfrac32$. By backtracking the initial inequality, $\log_272\lt2\pi$.
Answer: We have the series of inequalities:
$$ \frac{8192}{4096} \ = \ 2 \ > \ \left(\frac{9}{8} \right)^4 \ = \ \frac{6561}{4096} \ \ \Rightarrow \ \ 2^{1/4} \ = \ 4^{1/8} \ > \ \frac98     $$
and
$$  \pi \ - \ 3  \ > \ \frac18 \ \ \Rightarrow \ \ 4^{\pi  -  3} \ >  \ 4^{1/8} \  > \ \frac98 \ \ \Rightarrow \ \  4^{\pi} \ = \ 2^{2 \pi} \ > \ 4^3· \frac98 \ = \ 72 $$
$$ \Rightarrow \ \ 2·\pi \ \ > \ \ \log_2 (72) \ \ .  $$


Class object has no attribute tk?

Question: I am fairly new to python and with the help of tutorials I am trying to create a calculator but got stuck due to an error which I am unable to correct which occurs when I press a number button
from tkinter import *
root=Tk()
root.title("Yuvi's CAl")
global char

class cal():

    def __init__(self):
        self.string= StringVar()
        root=Tk()
        root.title("Yuvi's CAl")
        self.string=StringVar
        enter=Entry(root,textvariable=self.string)
        enter.grid(row=0,column=0,columnspan=6)
        values=["1","2","3","4","5","+","6","7","=","8","9","c"]
        row=1
        col=0
        i=0
        for txt in values:
            if i==3:
                row=3
                col=0
            if i==6:
                row=4
                col=0
            if i==9:
                row=5
                col=0

            if txt=="+":
                but=Button(root,text=txt)
                but.grid(row=row,column=col)
            elif txt=="=":
                but=Button(root,text=txt,command=lambda:self.equals)
                but.grid(row=row,column=col)
            elif txt=="c":
                but=Button(root,text=txt,command=lambda:self.clr)
                but.grid(row=row,column=col)
            else:
                but=Button(root,text=txt,command=lambda txt=txt:self.add(txt))
                but.grid(row=row,column=col)

            col+=1
            i+=1
    def add(self,char):
            meet=self.string.get(self)
            self.string.set((str(meet)) + (str(char)))

    def equals(self):
            result=eval(self.string.get())
            self.string.set(result)
    def clr(self):
            self.string.set("")

ent=cal()

root.mainloop()

and this being the error when I press a number button
Traceback (most recent call last):
  File "/usr/lib/python3.4/tkinter/__init__.py", line 1541, in __call__
    return self.func(*args)
  File "/home/yuvi/Documents/LiClipse Workspace/GUI/src/Misiio_calcuator.py", line 40, in <lambda>
    but=Button(root,text=txt,command=lambda txt=txt:self.add(txt))
  File "/home/yuvi/Documents/LiClipse Workspace/GUI/src/Misiio_calcuator.py", line 46, in add
    meet=self.string.get(self)
  File "/usr/lib/python3.4/tkinter/__init__.py", line 339, in get
    value = self._tk.globalgetvar(self._name)
AttributeError: 'cal' object has no attribute '_tk'

Do rectify if any mistakes
Thank you in advance
Answer: There are several issues with your code first you should remove hiding your global vars within your __init__ as it creates two windows and only running mainloop for one of them. In addition you overwrite self.string with the StringVar class object after first creating an instance of it. So your __init__ could look like so
...
def __init__(self):
    self.string=StringVar()
    enter=Entry(root,textvariable=self.string)
    enter.grid(row=0,column=0,columnspan=6)
    values=["1","2","3","4","5","+","6","7","=","8","9","c"]
    row=1
    col=0
    i=0
...

then in your add you don't have to pass self to self.string.get, that is it should look like
...
def add(self,char):
    meet=self.string.get()
    self.string.set((str(meet)) + (str(char)))
...

Those changes fixes your exception but I guess there are still other logical mistakes in the calculator, however that's not what the question is about and fixing them wouldn't help you learning python.

Class object has no attribute tk?


Riemann integration of a function

Question: I would like to ask if the function $f(x)=\begin{cases}0\text{ if } x\in \mathbb{\mathbb{[0,1]}\cap Q}\\ x^2\text{ if } x\in \mathbb{[0,1]\setminus Q} \end{cases}$ is Riemann Integrable in $[0,1]$?
My thought:
Let $S(f,P)$ and $s(f,P)$ be the upper and low sums of $f$ with respect to partition $P$ of interval $[0,1]$. Let $M_i=\sup\{f(x)| x \in I_i\}$ and $m_i=\inf\{f(x)| x \in I_i\}$, where $I_i$ is the $i$th interval of the partition $P$. Note that $M_i=1$ for all $i$, because every interval $I_i$ of the partition $P$ contains rational numbers. On the other hand, $m_i=0$ for all $i$ because every interval $I_i$ of the partition $P$ contains irrational numbers. By definition,
$$S(f,P)=\sum_{i=1}^nM_i\mu(I_i)=\sum_{i=1}^n1\mu(I_i)=\sum_{i=1}^n\mu(I_i)=1-0=1$$
$$s(f,P)=\sum_{i=1}^nm_i\mu(I_i)=\sum_{i=1}^n0\mu(I_i)=0$$
Thus, $f$ is not Riemann integrable because the upper and lower integrals are not equal. (The upper integral is the limit of the upper sums and the lower integral is the limit of the lower sums).
Comment: You're very close, but your calculation of $M_i$ is wrong. For instance if $I_1=[0,1/\sqrt{2}]$ then $M_1=1/2$, rather than (as you claim) $M_1=1$.
Answer: No, it is not Riemann-integrable, but your computations are not correct. You are right when you claim that $s(f,P)=0$, for each partition $P$ of $[0,1]$. However, it is not true that $S(f,P)=1$ for each partition $P$ of $[0,1]$. Actually, it is not true that "$M_i=1$ for all $i$, because every interval $I_i$ of the partition $P$ of $[0,1]$ contains rational numbers".  However, it is true that, for each partition $P$ of $[0,1]$, $S(f,P)\geqslant\frac13$, and this is enough to prove what you want.
Comment: I get confused, can you give a complete solution by the beginning please? It would be very helpful for me. Thank you
Comment: What is confusing you? You wrote that each $M_i$ is equal to $1$, which is just wrong. If $P=\left\{0,\frac12,1\right\}$, then you have two intervals: $I_1=\left[0,\frac12\right]$ and $I_2=\left[\frac12,1\right]$. In this case, $M_2$ is indeed $1$, but $M_1=\frac14$.
Comment: It would be helpful for me to have a complete solution, I am studying Riemann integration and I try to understand it. It would help me a lot
Comment: There is no way I will write anything else if you do not answer my question.
Comment: I can't see a question from you. I just ask for a help, if you have time just let me understand
Comment: Don't you see that two comments ago I asked "What is confusing you?"
Comment: I had a wrong thought. You wrote if we have two intervals etc, then $M_1=\frac{1}{4}.$ Then? If we have more intervals? I got confused
Comment: What I wrote was that **if** $P=\left\{0,\frac12,1\right\}$, then $I_1=\left[0,\frac12\right]$ and that, in **that** case,$$M_1=\sup\left\{f(x)\,\middle|\,x\in I_1\right\}=\frac14<1.$$

Riemann integration of a function


Irreducible polynomials and affine variety

Question: Let $k$ be any field, and let $f,g\in k[x,y]$ be two irreducible polynomials such
that $g$ is not divisible by $f$. Prove that $V(f,g)\subseteq A_k^2$ is finite.
Comment: Your question is phrased as an isolated problem, without any further information or context. This does not match many users' quality standards, so it may attract downvotes. To prevent that, please [edit] the question. This will help you recognise and resolve the issues. Concretely: please provide context, and include your work and thoughts on the problem. These changes can help in formulating more appropriate answers.
Answer: No need to consider $f,g$ irreducible polynomials, it's enough to assume $\gcd(f,g)=1$. Then $\gcd(f,g)=1$ in $K(X)[Y]$, and therefore there exist $u,v\in K(X)[Y]$ such that $1=uf+vg$. In order to clear the denominators we can find a polynomial $w\in K[X]$ such that $wu,wv\in K[X,Y]$. From $w=(wu)f+(wv)g$ it's obvious that $f(a,b)=g(a,b)=0$ implies $w(a)=0$ and since $w$ has only finitely many roots in $K$ we are done.
Comment: @jm.byrnes, you do the same thing with the variables interchanged, of course...
Comment: How did you prove that "$\gcd(f,g)=1$. Then $\gcd(f,g)=1$ in $K(X)[Y]$"?
Comment: @user26857 Hi. I can see why the $x$-coordinate has a finite number of roots in $(f,g)$ of $\mathbb{A}^2$, but how are you able to conclude that the $y$-coordinate is also finite?
Comment: Use Gauss' lemma (Theorem 2.1 from https://math.stanford.edu/~conrad/210APage/handouts/gausslemma.pdf). Basically, any positive-degree factor of f in K(X)[Y] leads to a positive-degree factor of f in K[X, Y].


Evaluate $\int_0^{\infty } \left(x^2+1\right)^{b-\frac{1}{2}} e^{-p x^2} \cos \left((2 b-1) \tan ^{-1}(x)+2 p x\right) \ dx$

Question: Gradshteyn&Ryzhik 3.976 states that $$\int_0^{\infty } \left(x^2+1\right)^{b-\frac{1}{2}} e^{-p x^2} \cos \left((2 b-1) \tan ^{-1}(x)+2 p x\right) \ dx=\frac{e^{-p} \sin (\pi  b) \Gamma (b)}{2 p^b}$$
For $b,p>0$. This seems to be related to Hermite formula i.e. formula $7$ here, but so far not success. Any help or suggestions will be appreciated.
Answer: Notice that the integral in question $I$ can be written as
$$I=\frac{1}{2}\Re(I_1)\\I_1=\int_{-\infty}^{\infty}dx(1+ix)^{2b-1}e^{-px^2}e^{2ipx}$$
which we can subsequently manipulate into a gamma function integral by completing the square :
$$I_1=\int_{-\infty}^{\infty}dx(1+ix)^{2b-1}e^{-px^2}e^{2ipx}\\=e^{-p}i^{2b-1}\int_{-\infty}^{\infty}dx(x+i)^{2b-1}e^{-p(x+i)^2}\\=e^{-p}i^{2b-1}\int_{-\infty+i}^{\infty+i}dx~x^{2b-1}e^{-px^2}$$
It is left to the reader to verify that since the integrand of the last expression has no poles in the complex plane, we can form a rectangular contour connecting the two lines of integration and prove that
$$\int_{-\infty+i}^{\infty+i}dx~x^{2b-1}e^{-px^2}=\int_{-\infty}^{\infty}dx~x^{2b-1}e^{-px^2}$$
Performing carefully a change of variables $y=x^2/p$ we find that
$$\int_{-\infty}^{\infty}dx~x^{2b-1}e^{-px^2}=\frac{1}{p^b}\int_{0}^{\infty}dx~y^{b-1}e^{-y}=\frac{\Gamma(b)}{p^b}$$
So we finally see that
$$I_1=-ie^{-p}e^{\pi ib}\frac{\Gamma(b)}{p^b}$$
and by extracting the real part and dividing by 2, we obtain the requested result:
$$I=e^{-p}\frac{\sin{(\pi b)}\Gamma(b)}{2p^b}$$


replace pandas DataFrame value pattern

Question: This is my current DataFrame using pandas, and it has some mixed type values in order_number column
       order_number             created_time  customer_id  driver_id
153280        40487  2017-02-01 12:39:25.887         1413       96.0
153281       118898  2017-02-01 10:52:38.822        51640     5382.0
153282      "36968"  2017-02-02 20:54:43.141        49072     6851.0
153283      "68383"   2017-02-02 19:01:08.52        28742     4479.0
153284      "56261"  2017-02-01 06:09:53.245        31656        NaN

and I want to remove the quote mark from the order number so that the DataFrame would be like this:
       order_number             created_time  customer_id  driver_id
153280        40487  2017-02-01 12:39:25.887         1413       96.0
153281       118898  2017-02-01 10:52:38.822        51640     5382.0
153282        36968  2017-02-02 20:54:43.141        49072     6851.0
153283        68383   2017-02-02 19:01:08.52        28742     4479.0
153284        56261  2017-02-01 06:09:53.245        31656        NaN

I already tried to use replace method like below but it didn't work.
df['order_number'].replace('""','')

Can anyone help?
Any suggestion would be appreciated :)
Answer: I think you need str.strip:
df['order_number'] = df['order_number'].str.strip('"').astype(float)

Or add parameter regex=True for replace substrings:
df['order_number'] = df['order_number'].replace('"','', regex=True).astype(float)

Last convert values to floats.

replace pandas DataFrame value pattern


Class Design - Image Upload - Resize (no cropping)

Question: Here is the edited class which inlcudes the answer:
EDIT: Included Answers
<?php

class Upload
{
    private $originalWidth,
            $originalHeight,
            $newWidth,
            $newHeight,
            $maxMedium = 50,
            $maxSmall = 20;

    private $src = NULL;

    private
            $fileType,
            $fileName,
            $sessionId,
            $path_medium,
            $path_small;

    function __construct($fileType, $fileName)
    {
        if(1)
        {
            Session::start();
            Session::activate(0, 1000, 'Test Account A', 'bookmarks');
        }

        /**
         *    Initialize the Object
         */

        $this->sessionId = Session::get('id');
        $this->path_medium = PICTURES . "/$this->sessionId.jpg";
        $this->path_small = PICTURES . "/$this->sessionId-1.jpg";
        $this->fileType = $fileType;
        $this->fileName = $fileName;

        /**
         *    Instantiate the Object
         */

        $this->instantiate();
    }

    private function instantiate()
    {
        $this->createImages();
        $this->updateSessionAndDb();
    }

    private function createImages()
    {
        if(move_uploaded_file($this->fileName, $this->path_medium))
        {
            if($this->get_image($this->path_medium))
            {
                list($this->originalWidth,$this->originalHeight)=getimagesize($this->path_medium);
                $this->newWidth = $this->originalWidth;
                $this->newHeight = $this->originalHeight;
                // these could each be another class instead of two functions..but no time to refactor further
                $this->resize_move($this->maxMedium,$this->path_medium);
                $this->resize_move($this->maxSmall,$this->path_small);
                imagedestroy($this->src);
            }
        }
    }
    private function updateSessionAndDb()
    {
        $db = new Database();
        $result = $db->_pdoQuery('none', 'update_picture', array($this->sessionId));
        Session::set('picture',1);
    }
    private function resize_move($max, $path)
    {
        $this->makeProportions($max);
        $image_true_color = imagecreatetruecolor($this->newWidth, $this->newHeight);
        imagecopyresampled($image_true_color, $this->src, 0, 0, 0, 0, $this->newWidth, $this->newHeight, $this->
        originalWidth, $this->originalHeight);
        imagejpeg($image_true_color, $path);
        imagedestroy($image_true_color);
    }
    private function makeProportions($max)
    {
        $this->newWidth=$this->originalWidth;
        $this->newHeight=$this->originalHeight;
        if(($this->originalWidth > $this->originalHeight) && ($this->originalWidth > $max))
        {
            $this->newWidth = $max;
            $this->newHeight = ($max / $this->originalWidth) * $this->originalHeight;
        }
        elseif($this->originalHeight > $this->originalWidth && $this->originalHeight > $max)
        {
            $this->newHeight = $max;
            $this->newWidth = ($max / $this->originalHeight) * $this->originalWidth;
        }
        elseif ($this->originalWidth > $max)
        {
            $this->newWidth = $this->newHeight = $max;
        }
    }
    private function get_image($path)
    {
        $type_creators = array(
            'image/gif' => 'imagecreatefromgif',
            'image/pjpeg' => 'imagecreatefromjpeg',
            'image/jpeg' => 'imagecreatefromjpeg',
            'image/png' => 'imagecreatefrompng');
        if(array_key_exists($this->fileType, $type_creators))
        {
            $this->src = $type_creators[$this->fileType]($path);
            return true;
        }
    return false;
    }
}

Comment: "public function get_image($path)" not "function get_image($path)". Although, as you can tell, mixing static and non-static functions can be done I try not to do it. As you can see you are passing a variable that is a class attribute and the static function can not access it.
Comment: Your **upload** class is actually **resizer** (or something similar)
Answer: A few things I noted:

Your method and variable name should be clearer.  Specifically, rmove should be renamed to something more descriptive, as well as every single one of your private member variables.  Shoot for clarity rather than brevity with function and variable names.
Remove references to $_FILES and $_SESSION from you class, and instead pass that information into the constructor.  There is no need to couple this class with the implemenation details of the surrounding client code.  You might want to reuse it in some other circumstance where the email wasn't in the session variable, or the file info was not in $_FILES.
You can rewrite your get_image() method as follows, to make it cleaner and shorter.  Note that using this method, adding support for new image types simply involves adding them to the array at the start of the method.  You could even move that array out of the method and provide it as a static member variable.
function get_image($path)
{
$type_creators = array(
    'image/gif' => 'imagecreatefromgif',
    'image/jpeg' => 'imagecreatefromjpeg',
    'image/png' => 'imagecreatefrompng',
);

$img_type = $_FILES['ufile']['type'];

if (array_key_exists($img_type, $type_creators)) {
    $this->src = $type_creators[$img_type]($path);
    return true;
}
return false;
}

Don't pass member variables as arguments into methods.  Remember, they are automatically available already.  So rather than $this->rmove($this->max1,$path3);, simply access $this->max1 from within rmove.
Consider breaking rmove down into smaller private functions whose names clearly describe what is going on in each case of the if statement.
Also, rmove is performing two distinct operations right now: 1) Recalculating the true width and height and 2) creating a new version of the image based on these dimensions.  I would break it down into two methods that perfrom each of these tasks separately.
Finally, a larger issue to consider: This class does not have any public API.  There is no reason any of its methods need to be public right now, as client code will never use them.  Right now, the class is just acting as container code to do a bunch of tasks that should be triggered after a file upload.  So you should consider rethinking how client code could use this class in other circumstances.
Comment: Please do :) just curious, how do you have a 329 reputation having never registered?
Comment: I guess it keeps tracks of my IP or simply a session var, I don't know for sure.
Comment: oh yes, functional programming is fun.  here's a simple proof of concept: http://codepad.viper-7.com/g8A9dq
Comment: I added in the new class to the question with all of your updates...if you see anything else let me know....thanks again


Middle humbucker as Bridge humbucker

Question: I have a cheap Strat, and I was just wondering to upgrade the bridge single coil to a bridge humbucker. Unfortunately, I bought a Tenayo Hot Rail Humbucker in Single Coil Form, which is - as it states - a "middle position" humbucker. Now, should I install it on the bridge position although it is a middle pickup, or not? What is the difference between bridge and middle pickups?
Answer: You'll probably want one made for the bridge in the bridge. Near the bridge the strings don't vibrate as widely so won't induce as much signal. To compensate bridge pickups are generally "hotter" than neck/middle pickups.
That means the bridge pickups generally have more windings around the magnets which means more current induced in the wire, which would also be the case with a larger magnet, but if the magnet is too big it affects the vibration of the string too much... lots of possibilities between magnet size, type of magnet, number of windings, and even the type of wire being wound (though I think it's almost always copper)... anyway, thus the enormous selection available of different pickup brands and models. (Thanks Wheat Williams for suggesting additional discussion).
Comment: Yes, and "hotter" means that the strength of the magnetic field of the bridge pickup is greater, by design. Sets of Stratocaster pickups usually come in two magnetic strengths, the "neck and middle" version (you'd use two of them, and they are interchangeable) and the "bridge" version, which is unique.

Middle humbucker as Bridge humbucker


Find the $\lim_{n\to \infty}\frac{1}{n^2}\cdot \sum_{k=1}^{n}k\cdot \ln\left(1+\frac{3k}{n}\right)$

Question:
$$\lim_{n\to \infty}\frac{1}{n^2}\cdot \sum_{k=1}^{n}k\cdot \ln\left(1+\frac{3k}{n}\right)$$

How should I approach this this? to find the limit? to find if the series converge?
Answer: By writing
$$
\frac{1}{n^2}\cdot \sum_{k=1}^{n}k\cdot \ln\left(1+\frac{3k}{n}\right)=\frac{1}{n}\cdot \sum_{k=1}^{n}\frac{k}{n}\cdot \ln\left(1+3\cdot\frac{k}{n}\right)
$$ one may recognize a Riemann sum, then as $n \to \infty$,
$$
\frac1n \sum_{k=1}^nf\left(\frac kn\right) \to \int_0^1f(x)dx.
$$

You are led to evaluate $\displaystyle \int_0^1 \!\!x \ln(1+3x)dx$, which one may obtain by integrating by parts:

$$
\begin{align}
\int_0^1x \ln(1+3x)\:dx&=\left[\frac{x^2}2\:\ln(1+3x)\right]_0^1-\frac32\int_0^1 \frac{x^2}{1+3x}\:dx
\\\\&=\ln 2-\frac12\int_0^1 \left(x-\frac13+\frac1{3(1+3x)} \right)dx
\\\\&=\ln 2-\frac12\left[\frac{x^2}2-\frac x3+\frac19\:\ln(1+3x)\right]_0^1
\\\\&=\frac89\ln 2-\frac1{12}.
\end{align}
$$
Comment: @newhere Exactely. You may use an integration by parts to get the result.
Comment: So the integral is $\int_{0}^{1} x*ln(1+3x)dx$?


Find the business days between two columns in a pandas dataframe, which contain NaTs

Question: I have 2 columns in my pandas data frame, and I want to calculate the business dates between them.
Data:
 ID     On hold     Off Hold
 101    09/15/2017  09/16/2017
 102    NA          NA
 103    09/22/2017  09/26/2017
 104    10/12/2017  10/30/2017
 105    NA          NA
 106    08/05/2017  08/06/2017
 107    08/08/2017  08/03/2017
 108    NA          NA

I tried the below code using busday_count from numpy:
 df1['On hold'] = pd.to_datetime(df1['On hold'])
 df1['Off Hold'] = pd.to_datetime(df1['Off Hold'])
 np.busday_count(df1['On hold'].values.astype('datetime64[D]'),df1['Off Hold'].values.astype('datetime64[D]'))

also,
 np.where(pd.notnull(df1['On hold']),np.busday_count(df1['On hold'].values.astype('datetime64[D]'),
                                                df1['Off Hold'].values.astype('datetime64[D]')),0)

The error was :
   Cannot compute a business day count with a NaT (not-a-time) date

Any help will be appreciated :)
Comment: How do you intend to treat the days with NaT values? To be ignored or imputed?
Comment: Ignored, I want to calculate only if it is not NaT
Comment: [This](https://stackoverflow.com/questions/37840812/pandas-subtracting-two-date-columns-and-the-result-being-an-integer) might have the answer
Comment: I was looking for business days between two dates.
Answer: Using the pd.bdate_range method:
pd.bdate_range(df['On Hold'], df['Off Hold'], freq = 'B')

Comment: Can you share the output you got when you ran this?
Answer: You can try the below:
f = df1.dropna()
f['days'] = np.busday_count(pd.to_datetime(f['On hold']).values.astype('datetime64[D]'), \
            pd.to_datetime(f['Off hold']).values.astype('datetime64[D]'))

df1.merge(f[['ID', 'days']],on='ID', how='left')

Answer: Try to drop NA first before you do bus day count. You can drop all the NA by using the following.
new_df = df.dropna()

Comment: This is just a snippet of the data, if I drop na, it will affect the other columns in the data frame.


Excepted conditional density and conditional expectation

Question: Apparently one can obtain a regression analysis as
$$g(x)=\frac{\int yf(y,x)dy}{f(x)}$$
where
$$f(x)=\int f(y,x)dy$$
is the marginal density of $X_i$. In effect, I believe, the above expression calculates the expected value of the conditional density $f(y|x)$.
I am confused, is the above expression a generalization of the conditional expectation $E[y|x]$, or are they the same?
Comment: Hmm you are right. Maybe to rephrase my question. What is the difference between g(x) and E[y|x]?
Comment: There isn't any difference - that's what Glen_b told you. In the RHS you wrote the exact expression for $E(Y\mid X=x)$. And if you write the LHS as $g(X)$ then the RHS is the exact expression of $E(Y\mid X)$.
Comment: In view of the edit to the question, I think Alecos' comment is now considerably more relevant than mine.
Comment: Majte, you may find the Wikipedia entry on [the marginal distribution](http://en.wikipedia.org/wiki/Marginal_distribution#Two-variable_case) helpful; as it says, a marginal probability can always be written as an expected value.
Comment: I got confused because I came across a few articles saying that the above formula should be used in lieu of E[y|x]. Maybe they referred to E[y|x] in the class of linear estimators.. I forgot the source now
Answer: Partially answered in comments:
Maybe to rephrase my question. What is the difference between g(x) and E[y|x]? – Majte
There isn't any difference - that's what Glen_b told you. In the RHS you wrote the exact expression for $E(Y\mid X=x)$. And if you write the LHS as $g(X)$ then the RHS is the exact expression of $E(Y\mid X)$. – Alecos Papadopoulos
See also https://en.wikipedia.org/wiki/Marginal_distribution#Two-variable_case


Maximum GCD of partitions of a number.

Question: I came across a interesting theorem that, if we have a number n and we want to divide it into k parts such that sum of all k parts is equal to n, then the highest possible GCD of those partitions is equal to n/sum, where sum is the sum of 1+2+...k. I need the proof of this theorem and intuition behind it.
Comment: Take e.g. $n = 12 = 6 + 6$, so $k = 2$ parts. Then $\gcd(6, 6) = 6$ but $12 / (1 + 2) = 4$?
Comment: for eg. let n=216 and we want to divide it in 3 partitions then we can calculate the maximum GCD possible by n/(1+2+3) = 216/6 = 36. The partitions are 36 , 72 and 108
Comment: Welcome to the site. Pl present your question in Mathjax and follow the instructions on the tourguide of the page.
Comment: I've edited the question for you this time. Also please note the source of your theorem
Comment: For starters, the gcd of the partition numbers must divide $n$ as well. Hence the gcd must be less than or equal to $n$
Comment: One more thing is that, this clearly shows that for the maximum number of partitions i.e: when we have $n$ pieces of $n$ the gcd drops down to one
Comment: Maybe you need each partition number to distinct? @prets
Comment: @KartikaySharma I give you a hint by the example you gave. If parts could be the equal, then $216$ could be split into 3 parts evenly, as $$216=72+72+72$$ but if you want the parts to be all different, then they must be of the form $$a_1 d + a_2d + a_3d=n$$ with $a_1 < a_2 < a_3$. You get the largest gcd minimizing the sum of $a_1+a_2+a_3$, simply picking $1,2,3$.
Comment: @Crostul Yeah! I got it. Thanks, for pointing this out.
Answer: Following Crostul's hint:
Suppose $d$ is the GCD of each element in the set $\{p_1,p_2..,p_k\}$ then, dividing each element by it, we get $\{a_1,a_2.,a_3..,a_k\}$. Allowing us to write:
$$ d(\sum_{i=1}^k a_i) = n$$
Or,
$$ d = \frac{n}{\sum_{i=1}^k a_i}$$
Of course since the elements are distinct, we can assume wlog that $a_i< a_{i+1}$, in the natural numbers (no 0), we can make the sum the least by replacing the elements by the least elements in the $\mathbb{N}$ while satisfying constraint.
From the above, we get the inequality:
$$ 1+2..+k \leq \sum_{i=1}^k a_i$$
Plugging this into the expression for $d$ isolated on LHS gives the result.
Answer: This theorem is not true.
As a counter-example, look at the case where $n = \alpha k$ (for $k > 1$).
Here, by setting the partitions all to equal size $\alpha$ we can get the GCD to be $\alpha = \frac{n}{k} > \frac{n}{1 + \cdots + k} $.
For the rest of this answer, I will assume that the theorem states that the partitions had to be distinct.
To prove this we start by naming $G(n, k)$ to be the largest such gcd you can find when splitting $n$ into $k$ distinct parts.
Now, we assume that $G(n,k) > \frac{n}{1+\cdots + k}$ (setting up a proof by contradiction).
Next then notice that the partitions are therefore of the form,
$$G(n, k) \alpha_1,G(n, k) \alpha_2, \ldots,G(n, k)\alpha_k$$
where $\alpha_i$ is a positive integer.
Now we since we know this is equal to $n$ we have
$$n = G(n,k) \left(\alpha_1 + \cdots + \alpha_k\right)$$
Now we pick the best possible case for our $\alpha_i$, clearly $gcd(\alpha_1, \ldots, \alpha_k) = 1$ otherwise, $G(n, k)$ would not be the largest possible. And finally, by selecting the smallest possible $\alpha_i = 1, 2, \ldots, k$.
We get that in the best case, $n = G(n, k)\left(1 + 2 + \cdots + k\right)$
$$\Rightarrow G(n,k) \not{>} \frac{n}{1 + 2 + \cdots + k}$$
$$\Rightarrow G(n,k) \leq \frac{n}{1 + 2 + \cdots + k}$$
Comment: The problem statement might have changed, but currently it states that the partitions have to be distinct :)

Maximum GCD of partitions of a number.


UIScrollView Vertical Scrolling when touching inside a subview

Question: I have implemented a scrollview, which holds multiple copies of a custom view.  The custom views contain a UIPanGestureRecoginixer that I use to swipe them to the left (to delete them). When I attempt to scroll vertically, scrolling doesn't occur if I'm touching inside of the CustomView.  However if I set up the subViews and the scrollviews content size so that it scrolls horizontally this issue doesn't occur.  How can I force the scrollview to scroll horizontally even if I'm touching inside of a subview?
Answer: Try to set the UIPanGestureRecoginzer's delegate and implement
<code>- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
</code>
It requires you to return a BOOL value. When you return YES, the otherGestureRecognizer will be recognized simultaneous.


Cauchy-Riemann conditions, how to obtain them from arbitrary directions

Question: If I have a function $f:\mathbb{C} \rightarrow \mathbb{C}$ which is differentiable in a neighbourhood of $z$, in a sense that
$$f'(z)=\lim_{\Delta z \rightarrow 0} \frac{\Delta f}{\Delta z} = \lim_{(\Delta x + i \Delta y) \rightarrow 0} \frac{\Delta u(x,y) + i\Delta v(x,y)}{\Delta x + i \Delta y} $$
exists independent of the direction in which $\Delta z $ approaches $0$, then I can derive the C-R conditions by using two particular paths, namely ones parallel to the axes. But surely it must be possible to obtain the same result in a more complicated way, namely by using two arbitrary paths (straight lines), where $\frac{\Delta y}{\Delta x} = m_1$ and $\frac{\Delta y}{\Delta x} = m_2$. But so far, doing this computation has led me nowhere.
Comment: +1. However, I suggest you give up. The problem is just that you are getting lost in computations, IMHO. Taking two arbitrary directions (but linearly independent, of course), you will end up with a system of PDE for the directional derivatives. After some amount of computations this will reduce to the CR system that you already know.
Answer: We should assume that $f$ is differentiable at $z$ in the real sense, that is,
$$f(z+h)=f(z)+Ah+o(|h|),\quad h\to 0 \tag1$$
where $A$ is a real $2\times 2$ matrix and complex number $h$ is interpreted as a real vector. (Without the differentiability assumption, directional derivatives may exist but be completely unrelated to partial derivatives.)
Every linear map $h\mapsto Ah$ in two dimensions can be written in terms of complex coefficients as $h\mapsto \alpha h+\beta \bar h$.  Hence, getting the same limit of $\Delta f/\Delta z$ in two independent directions amounts to $(\alpha h+\beta \bar h)/h$ being the same for two linearly independent vectors $h$. The latter is possible only when $\beta=0$, because the numbers $\bar h/h=1/h^2$ are different for the two vectors. Since $\beta=0$, the limit is the same for all directions, and we have the conclusion.


Best way to store embeddings

Question: I have a dataset which is a CSV file which I open and analyse as a Pandas dataframe.
I am now generating 'embeddings' based on some of this data, which I want to analyse as well.
The dataset is rather big (millions of rows), so I noticed that appending and storing the embeddings as part of the pandas dataframe makes me run out of RAM memory. Aside from that storing and saving numpy arrays in a dataframe is also a bit 'awkward'.
Since I want to analyze the whole dataset including embeddings storing them in so-called embedding stores doesn't make a lot of sense, since I always want to loop over the whole set anyways.
Are there any best practices or recommendations for how to work with this data?
Answer: I would recommend two things:

Be sure to use the correct datatypes for each column as it can significantly reduce the memory usage
Use parquet. It reduces significantly the usage.

There is a potential 3) if 1) and 2) are not enough. You could divide your big dataframe in chunks with multiple parquets file. I put this as a potential solution as I am not sure it fits your need based on your description.
Comment: How do you store an embedding vector in parquet? Embeddings are vectors, usually fairly large like maybe a thousand floats. A thousand float64 times millions of rows is a lot.
Answer: Generally, your question is too broad.
Need more info about the situation when you run out-of-memory.
Millions of rows is decent size for the pandas dataframe.
General approach:

Use downcast for each of your columns. I.e. you don't need float64 if you operate with nymbers like 0.98, 1.13, 50.3 ...
Use categorical columns if you have like such data. If you see data with type Object and it is not a text, try to convert to categorical type.
Use np.where / np.select to greatly speedup data manipulation
Be careful with any groupby. Operations of grouping with large datasets and incorrect params could lead to OOM your process

If you did all above and you are still don't fit memory:

Try to use duckDB as store for your dataset https://github.com/duckdb/duckdb
Try polars https://github.com/pola-rs/polars
Buy RAM via servers or via a hardware upgrade
Select the Statistical significance subset from your original Dataset and use it for your work (Pls don't ask me how)

Best way to store embeddings


Express-Session creating too many sessions in DynamoDB. (Using Google One Tap)

Question: I am using Google One Tap to log into a webpage and trying to use AWS' DynamoDB to manage the session info.  I previously tried Elasticache and couldnt view the clusters/connect to the DB, so I switched.  Now, I have the opposite problem where I'll get 20-100+ sessions saved to DyanmoDB in a 5-30 min span when I go to the login page 1-2x.  I thought the problem was having saveUninitialized set to true, but that has not changed anything.
Would really appreciate any suggestions on how to debug this/what's going on/alternatives for session management
const session = require('express-session')
const DynamoDBStore = require('connect-dynamodb')(session)

const options = {
    table: 'my-sessions',

    AWSConfigJSON: {
            accessKeyId: process.env.ACCESSKEYID,
            secretAccessKey: process.env.SECRETACCESSKEY,
            region: 'us-east'
    }
}

app.use(session({
    genid: (req) => {
        return uuidv4() // use UUIDs for session IDs
    },
        cookie: {
         secure: true
},
    store: new DynamoDBStore(options),
    secret: 'mysecretkey',
    resave: false,
    cookie: {
        maxAge: 5*60*1000, //set to 5 min
    },
    saveUninitialized: false,
    name: 'id',
    rolling: true
}));

Edit: Adding my Google Auth process just in case I modified it/managing sessions incorrectly
This function is on the client side and runs once the user selects the profile to log in with
function handleCredentialResponse(response) {
    var id_token = response.credential;
    var xhr = new XMLHttpRequest();
    xhr.open('POST', '/auth');  // have been getting a 404 error in the console, but I get logs in the terminal that indicate /auth was reached?  secondary, but would love any insight into this
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onload = function() {
    console.log('Signed in as: ' + xhr.responseText);
        };
    xhr.send('idtoken=' + id_token);
}

This is on the server side, and what a POST req to /auth hits:
const client = new OAuth2Client(process.env.GOOGLE_CLIENT_ID);

exports.authLogin = (req, res, next) => {

    async function verify() {

        // google API function that verifies the JWT signature, the aud claim, the exp claim, and the iss claim.
        const ticket = await client.verifyIdToken({
            idToken: req.body.idtoken, // passed from handleCredentialResponse function
            audience: process.env.GOOGLE_CLIENT_ID,
        });

        const payload = ticket.getPayload();
        const userid = payload['sub'];
        req.session.user = userid
        req.session.auth = true // logged in
        req.session.save()

    }
    verify().catch(console.error);

    next()

}

Answer: I'm not quite following everything you're asking here, but I do see an implementation mistake that could create problems.  In your exports.authLogin() function, you are calling next() before the asynchronous portion of your middleware has finished.  Instead, you should do this:
exports.authLogin = (req, res, next) => {

    async function verify() {

        // google API function that verifies the JWT signature, the aud claim, the exp claim, and the iss claim.
        const ticket = await client.verifyIdToken({
            idToken: req.body.idtoken, // passed from handleCredentialResponse function
            audience: process.env.GOOGLE_CLIENT_ID,
        });

        const payload = ticket.getPayload();
        const userid = payload['sub'];
        req.session.user = userid
        req.session.auth = true // logged in
        req.session.save()

    }
    verify().then(next).catch(err => {
         console.error(err);
         next(err);
    });
}

This moves the call to next() into a .then() handler so it does not advance to the next request handler in the chain until after verify() is done.  In addition, if verify() fails, it also calls next(err) rather than just doing nothing but logging and leaving the current request stranded.
I also note that you aren't waiting for req.session.save() to complete before proceeding so you need to figure out if that is also something you need to do.
Comment: thanks for catching that.  I made the change and it's still doing it.  I added a console.log to here below and noticed it's printing like 20 times.  Not sure what to google/how to go about debugging, any ideas?
app.use(session({
    genid: (req) => {
       console.log('gen id');
        return uuidv4() // use UUIDs for session IDs
    },...
Comment: @user3768258 - At the start of your `authLogin()` function, add this:  `console.log("authLogin(): path=", req.path)` so you can at least see what requests are causing it to get called so many times.
Comment: @user3768258 - You can also add this as the first middleware: `app.use((req, res, next) => {console.log("start: path=", req.path); next();});`
Comment: When I added these logs, most of the time, nothing extra came up.  But sometimes (I think it's when my laptop falls asleep), I get this multiple times:
start: path= /apple-touch-icon-precomposed.png
start: path= /apple-touch-icon.png
start: path= /favicon.ico
Confused bc I'm on a laptop...I can only guess it's some weird new M1 mac thing??  any ideas?
Comment: @user3768258 - These are extra things an apple browser may ask for from a website.   You could make explicit routes for them and put those before your middleware and then they wouldn't get to your middleware.


K fold cross validation sample mean question

Question: When doing k fold cross validation, the data is randomly separated. Does it make sense to throw out a data set if it is very uncharacteristic of the general data?
If I don't have a very large data set, any random sample from that data set might have a very different mean and standard deviation from the complete data set.
Should I verify that the standard deviation and mean from random samples taken for K fold cross validation match that of the intended real world data?
Edit:
To clairfy, if you have 100 samples with standard deviation $\sigma_0$ and mean $\mu_0$, and you do $K10$ fold cross validation, then you will have $10$ randomly generated test sets, each with their own $\sigma_i$ and $\mu_i$.
If $\sigma_i$ and $\mu_i$ are radically different from $\sigma_0$ and mean $\mu_0$, then does it make sense to throw out that particular test set?
Answer: Let me make this even more general. The core of your question seems to be if there are any problems (or benefits) with removing "atypical" cases from the validation set. From what I understood, you judge the cases to be "atypical" if they differ from the whole dataset that you have.
If you removed the cases, then this would obviously improve your validation scores, but only because you were cheating and not testing on the hard cases! There is no reason whatsoever why you shouldn't test your model on valid data. The whole idea about cross-validation is to use the validation set to check performance of your model on dataset that differs from the one that you used for training. Even more, we often deliberately choose the validation set to differ from training set (e.g. with time-series data, we split it to use the "past" for training and "future" for testing). The reason for cross-validation is to estimate the potential performance on the unseen data, if you are sure that the data you haven't seen is the same as the one you used for training, then there is no reason for cross-validation.
The different story would be if you had incorrect data (impossible or corrupted values, wrong measurements etc.) in your validation set, then you would remove them, but only then.
Comment: What if I am designing a model to work only a data set with $\mu_0$ and $\sigma_0$?

Consider voltage fluctuations. When a circuit is in steady state, fluctuations will have a small $\sigma_0$. when the circuit is in a transient state, the $\sigma_0$ will be large. If I were going to design a model for this case, I would design $2$ different models, one for each case.

Therefore, if one of the random samples has a $\sigma_i$ more like the transient case, and I know my model is not designed to work in this case, then in this senario, should the atypical case be thrown out?
Comment: Another example : in the stock market we know the volatitility of the market. I can calculate the volatility of any subset of companies in the market as well. If I want to build a model to work on the stock market with volatility between 12-17, does it make sense to train the model on atypical kfold datasets that have volatility of 20-30? If I know I will never use the model in those cases?
Comment: @Frank then you wouldn't use the inconsistent data neither in training, nor in validation set, as it would be irrelevant for your problem.
Comment: Does that mean it makes sense to drop any kfold partitions which have metrics much different from the whole? I want to find some reference about this.
Comment: @Frank as I said, it doesn't. It sounds like a really bad idea. On the opposite, in many cases you would deliberately put the hard cases to your test set, to see how well does the model perform with the edge cases.
Comment: Thank you for taking the time. By any chance do you know any papers that discuss designing models for transients versus steady state, and their data selection and testing process, or designing models for data with a certain standard deviation?
Answer: K-fold (For e.g. 10-fold) cross-validation evaluates the performance of classifiers. In this process, the training set is randomly divided into K (10) subsets, where the K-1 (9) subsets were used for training the model. This helps in assigning the score for each feature in the 10th test subset. This procedure was repeated ten times. The scores generated for each of the test data is measured using TPR and FPR values
Comment: That is not what I asked, I edited the question to further clarify.


Como descobrir o endereço git de um repositorio já criado?

Question: Comecei a trabalhar agora e a empresa usa o git para atualizar seu sistema, mas estou sozinho no departamento de ti como eu consigo o endereço desse repositorio já tentei pegar o msm endereço que utilizo para o git clone e aparece o seguinte erro
Comment: já tentou um `git remote -v` para ver pra onde está conectado o repositório?
Answer: Você pode utilizar de duas maneiras para conseguir o endereço:

Executar comando abaixo:

<code>$ git remote -v
</code>

Abre o arquivo de configuração no diretório <code>.git</code>:

<code>$ cd .git
$ more config
</code>
Uma das duas soluções vai resolver seu problema.


Question regarding the maximum principle for harmonic functions

Question: The principle is formulated the following way:
Let $h$ be a harmonic function on a domain $D$ in $\mathbb{C}$. If $h$ extends continuously to $\partial D$ and $h\leq 0$ on $\partial D$, then $h\leq 0$ on $D.$
The book states that this is with respect to the Riemann Sphere and $\textbf{not}$ $\mathbb{C}$, but I have trouble understanding the theorem in terms of that.
Take for instance $h(z)=\Re (z)$   on $D=\{z\in \mathbb{C}:Re (z)>0\}$
What is the image of D onto the Riemann Sphere? Isn't it the halfsphere? Shouldn't the extension then be continuous?
Answer: No. If $D$ is the upper half-plane then the boundary in the Riemann sphere includes $\infty$.
Comment: Could you elaborate why this isn't a continuous extension?


Migrate a two-textfield field

Question: I'm looking to migrate a text field from Drupal 6 to Drupal 9. The field has two text fields.
The table description  returned by describe content_field_telfono ;  is the following.

Field
Type
Null
Key
Default
Extra

vid
int(10) unsigned
NO
PRI
0

nid
int(10) unsigned
NO
MUL
0

field_telfono_value
varchar(10)
YES

NULL

delta
int(10) unsigned
NO
PRI
0

The table content returned by select * from content_field_telfono limit 0,2; is the following.

vid
nid
field_telfono_value
delta

48
48
xxxxxxxxx
0

48
48
xxxxxxxxx
1

I found examples to migrate a multi-value.
I tried with the following migration.
  field_school_phone:
    plugin: sub_process
    source: field_telfono
    process:
      value: field_telfono_value

Comment: Did you just try a simple map first? source: destination
Comment: How can I make it?
The only examples I find in the core modules it's to map constants values.
Thanks.
Comment: Make what? Simply try doing field_school_phone: field_telfono and running it again. There are several several examples in core for migrations, as well as contributed modules like Migrate Plus.
Answer: have you seen this? migration using csv and yml for multivalued image field
anyway i think if you have the multivalued field separated by commas, it should work directly
Comment: Thanks for helping out. This appears to be a comment rather than an answer.

Migrate a two-textfield field


Plotting graph against row number in Excel

Question: I have plotted a graph in excel from B8 to B45. But, it plots the values starting from 1 along the x-axis. I want to make sure B8 to B45 are plotted against their original row numbers i.e. from 8-45 while the numbers with no data ex: 1-7 are 0. Would appreciatre any suggestions.
Graph obtained:

Graph required to be obtained (Expected):
Answer: Create a column (i.e. between col A and col B) and populate with the row numbers (1, 2, 3...45). You may have to do that manually, or fill in the first few numbers then double click on the autofill toggle on the bottom right corner of the cell.
Then set this newly column as the X value for the chart.
Answer: On your graph click on "chart filters" then under categories, deselect the data 1-7 that are unwanted.
Is this what you wanted?


Repair vs Optimize table in MySQL

Question:
Does Optimize include repair table or vice versa internally?
Is it possible to execute repair table only if found corrupt, any tools can support this?

(I am using MyISAM table engine)
Answer:
REPAIR TABLE Fixes Table Corruption
Issues, such as Open File Handle
Counts, Resolution of Rows with
Variable Length Data, and so forth.
OPTIMIZE TABLE simply copies the
table to remove unused space. If the
table is MyISAM, ANALYZE TABLE is
also performed to update index
statistics for the sake of the Query
Optimizer. If the table is InnoDB,
ANALYZE TABLE is bypassed.

You could have mysqld auto check and repair all MyISAM tables.
In fact the book MySQL 5.0 Certification Study Guide, Section 30.5, Pages 444,445 state:

The MySQL server can be instructed to
  check and repair MyISAM tables
  automatically. With automatic repair
  enabled, the server checks each MyISAM
  table when it opens it to see whether
  the table was closed properly the last
  time it was used and is not marked as
  needing repair. If the table is not
  OK, the server repairs it.
To enable automatic MyISAM table
  maintenance, start the server with the
  --myisam-recover option, The option value can consist if a comma-separated
  list of one or more of the following
  values:

DEFAULT for the default checking.
BACKUP tells the server to make a backup of any table that is must
  change.
FORCE causes table recovery to be performed even if it would cause the
  loss of more than one row of data.
QUICK performs quick recovery : Tables that have no holes resulting
  from deletes or updates are skipped.

For example, to tell the server to
  perform a force recovery of MyISAM
  tables found to have problems but make
  a backup of any tables it changes, you
  can put the following lines in an
  option file:
[mysqld] myisam-recover=FORCE,BACKUP

You could also create a file called /root/StartUp.sql and put the REPAIR TABLE commands you want inside. Then add init-file=/root/StartUp.sql to /etc/my.cnf and restart mysql to trigger the init script.

Repair vs Optimize table in MySQL


What does "j" mean in a chord symbol?

Question: In a book of jazz trumpet duets (for Bb trumpets), I keep seeing chord symbols like "Fj" (shown below). I'm familiar with the various kinds of chord symbols (the various seventh chords, extensions, etc.), but I've never seen "j" before. What does it mean?

(Image Source: Wolf Escher, 20 Jazz-Duette: Heft 1, [Schott Music, 1982], page 23)
Comment: Of interest: [Standard format for jazz chord symbols](https://music.stackexchange.com/q/63925/70803).
Answer: It means "major seventh". "Fj" is equivalent to "FMaj7" or "FΔ7". It is rarely used.
A clue to its meaning is given a few bars later, in the final measure of the piece. The trumpets are playing their A and E, respectively, with "Fj" indicated as the chord. E being the major seventh of F, it's clear the chord would be a major seventh chord.

An even more clear example can be found on page 20 of the same book. As shown below, there is a progression "Dm Dmj Dm7". The second trumpet plays D, Db (C#), C respective to each chord symbol. In other words, the basic chord is D minor, with the second trumpet making a chromatic decent from ^8 to ^#7 to ^7. Thus, Dmj is D minor with a major seventh, or DmM7.
Comment: This is great, never seen "j" used.
Comment: Anecdotical fact: if you use the "Band in a Box" program, which generates accompaniments based on a chord sheet, you can press 'j' for Maj7. Also 'h' for m7b5 (half diminished), 'o' for diminished and 's' for 7sus.
Comment: I have seen j7 in form of this piece of documentation here https://lilypond.org/doc/v2.23/Documentation/snippets/chords#chords-chord-name-major7 This is a reasonable step, maj7 gets shortened to j7 (since m7 would cause problems with minor chords). And from there I guess it is not unreasonable to say: *Actually we only need j for j7, so we can simply leave out the 7.*
Comment: That's a probable. Maybe should have been followed up with 'n' for minor..?
Comment: Any ideas why 'j'? I've never ever come across that one! +1.
Comment: @Tim My thought is that it comes from the word "major", but avoids any "M/m" confusion.
Comment: @Tim I wondered about that, but "n" and "m" look similar enough that one could image it leading to misreading.
Comment: True, although Bn and Bm  would produce the same chord..! Maybe it (and 'j' ) just never caught on. I still get caught out with hand-written M and m sometimes.
Comment: it is not uncommon but a German symbol

What does "j" mean in a chord symbol?


Passing data from controller into Model in Laravel

Question: I have this comment controller:
class CommentsController extends Controller
{
    public function store(Article $article){
        $comment = new Comment();
        $comment->user_id = auth()->id();
        $comment->comment = request('comment');
        $comment->article_id = $article->id;
        $comment->save();
        return back();
    }
}

And it works. I tried to make my code cleaner by putting that logic into my model. So I changed it like this:
class CommentsController extends Controller
{
    public function store(Article $article){
        $article->addComment(request('comment'));
        return back();
    }
}

Meanwhile, in my Comment Model I'm doing like this:
class Article extends Model
{
    protected $fillable = ['title','content','user_id'];

    public function comments(){
        return $this->hasMany(Comment::class);
    }

    public function user(){
        return $this->belongsTo(User::class);
    }

    public function addComment($comment){
        Comment::create([
            'comment' => $comment,
            'article_id' => $this->id,
            'user_id' => auth()->id()
        ]);
    }
}

but when I do this, I'm getting this kind of error:
"SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value (SQL: insert into `comments` (`comment`, `article_id`, `updated_at`, `created_at`) values (Test comment bla bla bla..., 1, 2017-10-16 09:27:27, 2017-10-16 09:27:27)) ◀"

It seems I can't get the user_id in that manner, so how can I pass the user id so i can insert it into my comment tables? Thanks.
Answer: try
\Auth::id()

instead of
auth()->id()

and go to your  database and and make user_id default as NULL
The reason for this kind of error is that laravel protects database fields for mass assignment when you add the following code it makes all fields fillable.
protected $guarded = [];

Another way of doing is to add user_id in comments model. Is this case it will only allow the fields mentioned in the array to be mass assigned.
 protected $fillable = [
        'user_id'
    ];

Comment: add  protected $guarded = [];  in the comment model
Comment: but maybe u should adding it at your answer and i don't have to set user_id default into null.
Comment: if you declare that null it will still wont give you error because by default database will make user_id NULL :-)
Comment: no, currently my default is null, and i don't need to change anything like @Alexey said, i just need to put $fillable in Comment Model not just in my Article model. and it's work :)
Answer: Try this:
   public function addComment($comment){
        Comment::create([
            'comment' => $comment,
            'article_id' => $this->id,
            'user_id' => \Auth::user()->id
        ]);
    }

Comment: it give me Call to undefined method App\User::id() errors.
Comment: I guess, you're calling `\Auth::user()->id()` like this.
Comment: hahaha yeah i think so, but i still get the same errors, it say user_id doesn't have any value.
Comment: It  supposed to get the authenticated use id if the user is logged in.
Comment: yes that i confuse, when i using it in comment controller ive got no problem.
Answer: You need to add user_id to $fillable array in Comment model, not in Article model to make it work. Your original code works just because you do not use mass assignment there.
Comment: well you are right, i don't have to change anything. just add it into my fillable and it's work.


Definition of the ideal of a subset of affine $n$-space

Question: Let $K$ be an algebraically closed field. Then let $A = K[x_1, ... , x_n]$.
If $Y \subseteq \mathbb A^n$, then the ideal of $Y$ is to defined to be $I(Y) = \{f \in A | f(P) = 0 \ \forall P \in Y \}$. What is $I(\emptyset)$?
For $T \subseteq A$, define $Z(Y) = \{P \in \mathbb A^n | f(P) = 0 \ \forall f \in A\}$. Am I correct in thinking that $Z(A) = \emptyset$?
Thanks
Answer: You are correct that $Z(A)=0$. Correspondingly, $I(\emptyset)=A$, as all elements of $A$ vanish on every point in $\emptyset$ (trivially, as there are none). In general, for any ideal $J\subseteq A$ we have $I(Z(J))=\sqrt{J}$, where $\sqrt{J}$ denotes the radical of $J$.
Comment: Note that this last statement is one formulation of the weak Nullstellensatz.
Comment: Thank you. I'm aware of the statement; I was checking the details of an example that showed that statement doesn't necessarily hold if $K$ wasn't algebraically closed.
Answer: By definition,
$$I(\varnothing) = \{f\in A\mid f(P)=0\forall P\in\varnothing\} = A,$$
since every element of $A$ satisfies the condition by vacuity.
Since $P\in Z(A)$ requires $1=\mathbf{1}(P)=0$ (where $\mathbf{1}$ is the constant polynomial $1$), and this is impossible, this proves $Z(A)=\varnothing$.


null value in column "user_id" violates not-null constraint Django

Question: I know there are a lot of solutions for this problem but they seem a bit different than mine. Here is my models.py:
from __future__ import unicode_literals

from django.db import models
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.postgres.fields import HStoreField
# Create your models here.

class Events(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL)
    name = models.CharField(max_length=32)
    start = models.CharField(max_length=32)
    end = models.CharField(max_length=32)

Very simple table and I want the primary key in Auth_user to be the foreign key in my Events table. So of course this would mean that a User has to be logged in and authenticated for this to work. In my views.py I have:
def createEvent(request):
    if request.method == "POST":
        user = request.user
        print (user)        # Check for Authentication
        name = request.POST['name']
        start = request.POST['start']
        end = request.POST['end']
        Events.objects.create(
            name = name,
            start = start,
            end =end,
        )

The print statement will print out the current user logged in. I can confirm that this part does show that a user is logged in and that this user is in the auth_user table with a unique id. However, when I try to submit a form, I get a null value for the user column. Any ideas?
Comment: @jens, that should probably have been an answer. Also tell the op how to do proper is_authenticated check.
Comment: That says Event should have a field containing a user - you need to define what the value should be though in each Event. Models define the table in your database, when you do `Event.objects.create` you're creating a new row in that table - if that helps...
Comment: Thanks I had a misunderstanding but now I understand.
Comment: `Events.objects.create(name = name, start = start, end =end)` The user isn't being set anywhere...On a separate note, you should use a [ModelForm](https://docs.djangoproject.com/en/1.10/topics/forms/modelforms/) for something like this, will save a lot of work.
Comment: Wait sorry, shouldn't the user already bet set in the models.py? `user = models.ForeignKey(settings.AUTH_USER_MODEL)`
Answer: Just add the user instance because it's required by Events.  I think you should use DateField or DateTimeField on start and end field.  Not sure but I think you plan to put a date value there.

Events.objects.create(user=request.user, name=name, start=start, end=end)

You should also add a @login_required for your function.
Comment: Actually, I have a middleware provided for that `login_required` part so I don't have to put that everywhere.
Comment: Ok.  you can just assign `request.user`
Answer: My solution is this:

    from django.contrib.auth.models import User
    user = request.user
    user_id = User.objects.get(username=user).pk
    name = request.POST['name']
    start = request.POST['start']
    end = request.POST['end']
    Events.objects.create(
        user_id=user_id,
        name = name,
        start = start,
        end =end,
    )

Is that an alright solution? Could there be something better?
Comment: change user_id to user.  request.user already return a `User` object, no need another query `user_id = User.objects.get(username=user).pk`
Answer: Making what you have right now work:
def createEvent(request):
    if request.method == "POST":
        user = request.user
        print (user)        # Check for Authentication
        name = request.POST['name']
        start = request.POST['start']
        end = request.POST['end']
        # The user has to be included before being saved
        Events.objects.create(name=name, start=start, end=end, user=user)

Some better practices:
Using a ModelForm (note there are class based generic views that make this easier too), and the login_required decorator
# forms.py
from django.forms import ModelForm
from .models import Event

class EventForm(ModelForm):
    class Meta:
        model = Event
        fields = ('user', 'start', 'end', 'name')

# views.py
from django.contrib.auth.decorators import login_required

@login_required
def create_event(request):
    if request.POST:
        form = EventForm(request.POST)
        if form.is_valid():
            form.save()
    else:
        form = EventForm()
        return render(..., {'form': form})

Comment: Thank you, I am actually aware of the model Form. However, for this purpose I am using Jquery's Modal Form. So I am using ajax to send the data over.
Comment: I'd caution against ditching Django Forms to use javascript - you don't have to decide between one or the other (I went down that road, it gets messy), they can play together. For example, in your case, you can render the form manually but in your view pass the request.POST to the form instance for validation (it also turns all values into Python objects for you).


Lie algebra of 2 by 2 matrces that are upper triangular and their characteristics that define them

Question: I know how to find the orthogonal and the special linear group of $2$ by $2$ matrices. This is because I know their "defining" properties. How can I find the Lie algebra of:
$$A = \left(\begin{array}[c c]
- a_1 & a_2\\
   0& a_1^2
 \end{array}\right),$$
Where the matrices are invertible? I don't know their defining characteristic that is my big problem. If I know it, I can use dedicated to solve. Maybe it has to do something with their matrix potential or their trace?
Please help.
Comment: If you really mean that the matrix entry in the lower right is the square of the one top left, then this group is more specific than the "upper triangular" ones in the title; and the answer talks about those, not the ones with the extra condition in the question body. Please clarify.
Comment: I tried to put a general title. The group that I actually want is more specific and I denoted it by A.
Comment: Thanks, I get it now
Answer: Let $f:Gl(2,\mathbb{R})\rightarrow \mathbb{R}$ defined by $f(\pmatrix{a&b\cr c&d})=c$, $f$ is a submersion, we deduce that $f^{-1}(0)$  the set of invertible upper triangular matrices $U(2,\mathbb{R})$ is a  closed submanifold and a  Lie subgroup of $Gl(2,\mathbb{R})$. This implies  that the Lie algebra of $U(2,\mathbb{R})$ is the kernel of the differential of $f$ at the identity which is the subset of upper triangular matrices which are not necessarily invertible.


Evaluate double integral $\iint_A \log(y)\,dx\,dy$

Question: Calculate the double integral
$$\iint_A \log(y)\,dx\,dy$$
Where
$$ A = \{(x,y)\in R^2 : 0 \leq x \leq 1, \sqrt{x}\leq y \leq \sqrt[3]{x}\}$$
Help!
Answer: \begin{align}
\iint_A\log(y)dxdy &= \int_0^1\int_{\sqrt x}^{\sqrt[3] x}\log ydydx \\
&= \int_0^1 y(\ln y -1)|_\sqrt x^\sqrt[3] x dx \\
&= \int_0^1 \sqrt[3] x\left(\frac{\ln x}{3} -1\right) - \sqrt x\left(\frac{\ln x}{2} -1\right)
\end{align}
You can do the rest.
Answer: Well, I would invert the inequalities to $y^3\le x\le y^2$ and $0\le y\le 1$, and set up your iterated integral as follows:
\begin{align*}
\iint_A\ln(y)\,dx\,dy
&=\int_0^1\ln(y)\int_{y^3}^{y^2}dx\,dy\\
&=\int_0^1\ln(y)\left(y^2-y^3\right)dy\\
&=\left[\frac{y^4}{16}-\frac{1}{4} y^4 \ln (y)-\frac{y^3}{9}+\frac{1}{3} y^3 \ln(y)\right]_0^1.
\end{align*}
Recall that these are limits, so you might have to use L'Hospital's Rule to evaluate on the lower end.


What does a huge gap between P values of the same predictor computed in bootstrapped and non-bootstrapped versions of the same regression mean?

Question: My binary logistic regression gives P values significant at 0.05 level for some of the modeled independent variables. However, bootstrapping the same regression model gives P values significant at 0.01 or 0.001 levels for the same predictors which were mostly significant only at 0.05 level, or even for some of them which were not significant!
Does it have a worthwhile meaning? A huge discrepancy between the two P values of the same variable worries me, especially when I see the bootstrapped one that I expected to give more conservative results is giving much stronger results! I read somewhere that in such a case, we should discuss that the results pertaining to these variables should be assessed further. But there were no explanations and such a recommendation doesn't seem so specific.
Which P value is better here? Are both correct? (especially the bootstrapped one).
Do you have any recommendations for this strange P value behavior?
Comment: If bootstrapped and parametric ps differ a lot, my first guess would be that the assumptions of the parametric model somehow are violated. So I would check for that. I would not agree that the boostrap generally gives more conservative results.
Comment: Dear Felix I looked up logistic regression's assumptions and see none of them are violated. So do you have in mind any other reasons for the huge biases and differences between the P values calculated by the non-bootstrapped vs. bootstrapped models? Thanks again.
Comment: Many thanks dear Felix. Then the bootstrapped one is the more reliable one.
Answer: If bootstrapped and parametric ps differ a lot, my first guess would be that the assumptions of the parametric model somehow are violated. So I would check for that. I would not agree that the boostrap generally gives more conservative results.
Comment: I've copied this comment by @FelixS as a community wiki answer because the comment is, more or less, an answer to this question. We have a dramatic gap between answers and questions. At least part of the problem is that some questions are answered in comments: if comments which answered the question were answers instead, we would have fewer unanswered questions.


How to get inventory items from a PayPal API?

Question: I'm building inventory management software for Square and PayPal. After reviewing PayPal's RESTful API documentation, its not clear how I can retrieve inventory items from a merchant on their behalf.
For example, before a transaction is made or an invoice is created, I'd like to get their inventory items to beging improving the inventory management experience.
Does anyone know how I can retrieve inventory items from a PayPal API?
Thanks in advance - Royce
Answer: PayPal doesn't provide an inventory management system/service for merchants. The item list you see in the Restful API, is how a merchant can indicate what items the buyer is purchasing so PayPal can display that on the Payment confirmation page. If you are talking about how to obtain that information then you can do a GET on the payment resource id, which will include the items info that was originally provided by the merchant.
Comment: my question is which PayPal API do I use to retrieve items (i.e., products) added to the PayPal Here iPad app?


Como obrigar que diretiva so funcione se estiver dentro de uma diretiva específica?

Question: Estou tentando fazer com que as diretivas ngPanelHead, ngPanelBody e ngPanelFoot necessitem estar dentro da diretiva ngPanel, caso contrario um erro seja apresentado no console. Tentei com require porem não está funcionando. Estou utilizando a versão 1.4.8 do AngularJS.
angular
  .module('app')
  .directive('ngPanel', panel)
  .directive('ngPanelHead', panelHead)
  .directive('ngPanelBody', panelBody)
  .directive('ngPanelFoot', panelFoot);

function panel() {
  var directive = {
    restrict: 'EA',
    replace: true,
    transclude: true,
    template: '

'
  }

  return directive;
}

function panelHead() {
  var directive = {
    restrict: 'EA',
    // require: '^ngPanel',
    replace: true,
    transclude: true,
    template: ''
  }

  return directive;
}

function panelBody() {
  var directive = {
    restrict: 'EA',
    // require: '^ngPanel',
    replace: true,
    transclude: true,
    template: '

'
  }

  return directive;
}

function panelFoot() {
  var directive = {
    restrict: 'EA',
    // require: '^ngPanel',
    replace: true,
    transclude: true,
    template: ''
  }

  return directive;
}

Obrigado!
Comment: Uma observação, não inicie o nome dos seus `directives` com `ng`, os `directives` do Angular possuem esse prefixo, sendo assim, você pode acidentalmente criar um já existente. Utilize o seu próprio prefixo, ex.: `bwPanel`
Answer: O parâmetro require é a maneira correta de descrever requerimentos de dependência na definição da Directive.
.directive('subDiretiva', function() {
    return {
        scope: { data: "=" },
        require: ['?^^diretivaPai1', '?^^diretivaPai2'],  // Lista de possíveis diretivas-pai
        template: '<button></button>'
        link: function(scope, elem, attrs, diretivaParenteCtrl) {
              //conteúdo do link aqui
              };
        },
    }
})

Comment: Qual a versão do Angular você fez este teste? Talvez seja algum problema na versão do Angular pois na versão 1.4.8 não funciona.
Comment: @BrunoWego o teste da documentação do Angular funciona para mim - 'Creating directives that Communicate', https://docs.angularjs.org/guide/directive


How to make Drupal 7 render taxonomy tags as RSS categories?

Question: In Drupal 7, taxonomy tags do not show up in the RSS feed. How do I make them visible in the feed, so that RSS reader users can filter out stories based on these tags?
(I found it difficult to find an answer to this, so posting my findings in the hope this helps others)
Answer: This used to be the default behaviour in D6, but was accidentally removed from D7 after some refactoring. The latest versions of D7 contain a patch that allowed a third-party module to show RSS categories.
Step 1: download and install the RSS field formatters module.
Step 2: navigate to /admin/structure/types
Step 3: click "manage display" next to the desired content type
Step 4: expand "custom display settings" and make sure "RSS" is checked:

Step 5: select the "RSS" tab (after hitting Save if you had to enable the RSS checkbox). This one is a bit hard to notice:

Step 6: add the Tags to the fields list if not already there. Set the format to "RSS category":

Now save and enjoy your taxonomy tags in your RSS feed!


What factors does the shot power depend on and how can it be improved?

Question: I used to have pretty hard shots up until I had a persistent injury to my lower back, probably due to sedentary workdays coupled with irregular training. Well, a few months of physiotherapy and changing my work environment I have overcome this injury now and play football without any problems... except my shots seems to have withered altogether. I can run, tackle, dribble but have no real intensity in my shots these days.
That got me thinking; what does the shot power really depend on? What distinguishes players with incredibly hard/fast shots from others? Something I find particularly interesting is that there is no direct dependance on the body frame of the player, in other words some small and thin player can still have tremendous shots despite being undersized compared to others. So it's not all about being pumped..
As a follow-up, how can one improve his/her shot power?
Comment: Practice shooting with hard training ball and use ur bone area of foot to create more power. Doing exercises as mentioned by Ste can develop ur muscle can also increase power of shot
Answer: Shot power, which can be likened to the punch of a boxer, is predominantly dependent upon one's ability to create "explosive power".
Explosiveness is the amount of kinetic energy that can be generated by the relevant muscles in a short space of time.  In kicking a football, the main muscles used are the quads, glutes, hamstrings and calves.
To improve your power you need strong quadriceps but also the ability to generate speed and energy when straightening your leg and bringing your foot down.
If you want to kick harder you want to do be doing a lot of squats and jumps.  Not only will you strengthen the muscles but you'll also increase your ability to generate swing speed with your legs.
Also, don't neglect working your core.  Everything from your shoulder, abs and hips are used in stabilising your body whilst kicking too.
Here's a google search for "Explosive Power Drills".
Answer: Here's a link to a tutorial from Jared Montz, a former pro soccer player in the MLS.
How to Shoot a Soccer Bal with Power

Basic Key Points:

Ankle Locked, toe down, use laces (you don't hit a baseball with a
  loose bat)
Plant foot pointed at target
Land on Kicking Foot (you do this to help generate power and help keep the ball low)

Advanced Key Points:

Generate power from thigh, not calf
Shoulders face target (don't rotate them)
Keep head down (some of the best goals you will score you barely see them go in)

What Player Could Be Doing Wrong:
If you fee like you are not getting enough power it's mainly because
  you are not getting your thigh back and your knee down is just moving.
  Make sure you get your thigh back.

It's about 5 minutes long and he goes into details. It is more targeted towards younger players, so he can be quite cheesy at times.
To find the sweet spot, touch your top of your foot, towards the inside. There should be a very strong bone there. That is your sweet spot. Using the sweet spot means there is less energy loss when your strike the ball since less of it is absorbed/cushioned.
Here's another video talking about the Sledgehammer (Shooting with power).
A few key points he points out are:

It's not about the strength of your legs, it's the technique
Distance is not important for the run-up, but what is important is to be slightly off-set.
Use the sweet spot or the laces.
Hit the ball in the central area
You need to follow-through the ball.

They then show good and bad examples of each shots.
From this point on, hit the field and keep practicing. It's all about the techniques.


What is the correct representation for this equation?

Question: I tried to draw in the plane the next equation:
$$1<|z+i|<2$$
I did
$$1<\sqrt{x^2+(y-1)^2}<2$$
$$1<x^2+(y-1)^2<4$$
Do I have two circles here? The teacher draw only the outer circle $x^2+(y-1)^2<4$. Why was the inner circle not drawn?
Comment: There is something wrong here. For $z=z+iy$, we have $|z+i|=|x+i(1+y)|=\sqrt{x^2+(1+y)^2}$, so your solution is wrong, but also the solution of your teacher seems wrong.
Comment: Apart from the wrong minus sign, the inner circle is essential. For instance $z=-i$ satisfies $|z+i|<4$, but certainly not $|z+i|>1$. They should be the circles with radius $1$ and $2$ centered at $(0,-1)$.
Comment: really i should draw a ring, no?
Answer: Note that $|z+i|$ is simply the distance between $z=x+iy$ and $-i$. So the searched number $z$ is such that its distance from $-i$ must be greater than $1$ and the same distance must be less than $2$.
This means that, in the Argand plane, it is a point external to the circle of radius $1$ centered at $(0,-1)$ and internal to the circle centered at the same point but with radius $2$.
In other words, it is a point $(x,y)$ such that:
$$
\begin{cases}
x^2+(1+y)^2>1\\
x^2+(1+y)^2<4
\end{cases}
$$


Entidade com chave simples referenciando outra com chave composta

Question: Estou utilizando Fluent NHibernate para mapeamento das minhas classes, e tenho a seguinte situação:
Classe UsuarioMap
public class UsuarioMap : ClassMap<Usuario>
{
    public UsuarioMap()
    {
        Table("USUARIOS");
        Id(x => x.ID, "USUARIO_ID").GeneratedBy.Increment();
        //Comentado para evitar código desnecessário

        References(x => x.Proprietario).Columns("PROPRIETARIO_ID", "SERVIDOR_ID");
    }
}

Classe ProprietarioMap:
public class ProprietarioMap : ClassMap<Proprietario>
{
    public ProprietarioMap()
    {
        ReadOnly();

        Table("PROPRIETARIOS");
        CompositeId().
            KeyProperty(x => x.ID, "PROPRIETARIO_ID").
            KeyProperty(x => x.ServidorId, "SERVIDOR_ID");

        Id(x => x.ID, "PROPRIETARIO_ID").GeneratedBy.Assigned();

        //Comentado para evitar código desnecessário
    }
}

Ao tentar salvar um Usuario, recebo uma ArgumentOutOfRangeException. O objeto que tento salvar está da seguinte maneira:
var usuario = new Usuario
{
    Proprietario = new Proprietario { ID = 1497196, ServidorId = 2 }
    // Comentado para evitar código desnecessário
};

É interessante que, se eu criar uma propriedade ProprietarioID na classe Usuario e mapeá-la, o objeto é salvo sem problemas.
O que estou fazendo de errado? O mapeamento de uma entidade composta em outra simples está correto?
Comment: É necessário o `Id(x => x.ID, "PROPRIETARIO_ID").GeneratedBy.Assigned();` no mapeamento do `Proprietario`? Pois conferi com um cenário parecido que tenho aqui em meu projeto, e está muito parecido com o seu.
Comment: Oi Fernando, obrigado pela resposta.

Tentei retirar o GeneratedBy.Assigned, mas o erro persistiu...
Comment: Na tabela de `Proprietario` tem um registro com os identificadores `new Proprietario { ID = 1497196, ServidorId = 2 }`, previamente cadastrado? Não que seja isso, mas é uma possibilidade.
Comment: Sim, o registro já existe em Proprietario
Comment: Você poderia obter mais detalhes da `ArgumentOutOfRangeException`, tipo capturar toda a pilha de erro. Para tentarmos descobrir a origem da `Exception`, já que [ArgumentOutOfRangeException](http://msdn.microsoft.com/en-us/library/system.argumentoutofrangeexception.aspx) é uma `Exception` disparada por um argumento invalido e não nulo.
Comment: Segue então a Stack Trace gerada:

http://pastebin.com/jAjsR2C5
Comment: Alterei o mapeamento de `Proprietario` para a seguinte forma:
`References(x => x.Proprietario).Columns("PROPRIETARIO_ID", "SERVIDOR_ID").Not.Update().Not.Insert();`

O erro agora consiste em `ORA-01400: não é possível inserir NULL em ("BANCO"."USUARIOS"."PROPRIETARIO_ID")`
Comment: É possível você obter o SQL gerado pelo NHibernate antes de executar efetivamente no banco de dados? Para mostrar o SQL adicione o `.ShowSql()` em suas configurações, é algo similar a isto se você está utilizando o Oracle: `OracleClientConfiguration.Oracle10.ConnectionString(ConnectionString).ShowSql();`
Comment: Segue o SQL, que realmente não está passando o `PROPRIETARIO_ID`: http://pastebin.com/0bR7nNAK

Em relação ao cenário de mapeamento sem `.Not.Update().Not.Insert()`, nem é gerado SQL (estou verificando pelo NHibernate Profiler)
Comment: Resolvi a questão mapeando um campo privado chamado `proprietarioID`, e apontando o mapeamento para ele:
`Map(x => x.ProprietarioID).Column("PROPRIETARIO_ID").Access.CamelCaseField(Prefix.None);`

Na classe Usuario, alterei o construtor para receber um parâmetro do tipo Proprietario, com pelo menos ID e ServidorID, e a propriedade Proprietario agora somente possui get, onde retorno o objeto do banco.

Em todo caso, muito obrigado @Fernando pela ajuda!
Answer: Resolvi a questão mapeando um campo privado chamado proprietarioID, e apontando o mapeamento para ele:
Map(x => x.ProprietarioID).Column("PROPRIETARIO_ID").Access.CamelCaseField(Prefix.None);`

Na classe Usuario, alterei o construtor para receber um parâmetro do tipo Proprietario, com pelo menos ID e ServidorID, e a propriedade Proprietario agora somente possui get, onde retorno o objeto do banco. Em todo caso, muito obrigado @Fernando pela ajuda!
 public virtual Proprietario Proprietario
 {
     get
     {
         if (proprietario != null)
             return proprietario;

         if (proprietarioID == 0 || ServidorID == 0) return null;
         proprietario = new Repository<Proprietario>().Get(proprietarioID, SrvUn);
         return proprietario;
     }
 }

 public Usuario() : this(null)
 {

 }

 public Usuario(Proprietario proprietario)
 {
     if (proprietario == null) return;

     proprietarioID = proprietario.ID;
     this.proprietario = proprietario;
 }

Comment: Se você resolveu o problema, pode marcar sua resposta como aceita.


Does the series converge? If so, find the sum.

Question: $$\sum^\infty_{n=1}\frac{1+2^n}{3^n}$$
I think it can be shown to converge because $r=\frac23<1$. But I can't seem to get the correct sum, which is $\frac53$.
Comment: Splitting it into the sum of two geometric series?
Comment: What is $r$? Try to make your question self contained!
Answer: $$ \sum^\infty_{n=1}\frac{1+2^n}{3^n} = \sum^\infty_{n=1} \left(\dfrac  1{3}\right)^n + \sum^\infty_{n=1}\left(\frac{2}{3}\right)^n$$
Find the sum in each case (indeed, both sums converge), then add the two sums. In the first sum, you have $r = \dfrac 13$, and in the second case, you have $r = \dfrac 23$, knowing for each $r$, since $0\lt r\lt 1$, $$\sum_{n=0}^{\infty} r^n = \frac{1}{1-r}$$
Indeed, the sum totals $\dfrac 32 + 3 = \dfrac 92 \neq \dfrac 53$
Answer: HINT: $$\frac{1+2^n}{3^n}=\left(\frac13\right)^n+\left(\frac23\right)^n$$
And the correct sum is not $\dfrac53$ (so it's possible that you've actually done it right and simply don't realize it).
Answer: Hint:
$$
\frac{1+2^n}{3^n}=\left(\frac{1}{3}\right)^n+\left(\frac{2}{3}\right)^n
$$


Second order differential equation - complete solution

Question: I am tasked with finding for all valid values of the constant a the complete solution for the differential equation:
$y''+2y'-3y=e^{ax}$
Now i am getting
$y(x) = e^{-3x}\cdot C2 + e^x \cdot C1 + \frac{e^{ax}}{a^2+2*a-3}$
We can see that $a^2+2*a-3 = 0$ at $a \in \{1, -3\}$
So the equation is not valid at that point.
Apperently this is not an acceptable answer and i have to find a solution for
$a=1$ or $a = -3$.
How do i do this? It seems impossible to me.
Comment: Which textbook are you following? Nearly every one I know indicates that when $a$ is a root of the characteristic equation (this is your case!), one should turn to the functions $xe^{ax}$, then $x^2e^{ax}$, and so on.
Comment: Since you already have $e^{-3x}$ and $e^x$, for the cases where $a=1$ or $a=-3$, you need to consider terms as $x e^{x}$ and $x e^{-3x}$.
Comment: How should i use these functions?
Answer: You can modify the particular solution by parts of the homogeneous solution to finally read
$$
y_p(x)=\frac14\left(\frac{e^{ax}-e^x}{a-1}-\frac{e^{ax}-e^{-3x}}{a+3}\right)
$$
In this form it stays bounded also for values of $a$ close to the resonance cases. Obviously, in the case of $a\in\{-3,1\}$ one has to replace one of the quotients of the divided differences by the $a$-derivative $xe^{ax}$.


Forward port and keep source IP

Question: I have a system with a static IP address running several LXC containers.
I can communicate with the containers over an interface as it would be a physical machine.
One of this containers is a postfix server. I forward port 25 from the host to the container, however in the progress the source IP get's replaced with the interface one, resulting in postfix failing rDNS checks.
Setup
Host access to internet via interface eth0, IP 188.xxx.xxx.xxx
Container IP address 192.168.1.12 (br2) on the hosts site and 192.168.1.2(eth0) on the container side.
Container gain internet access via host as default gateway and iptable rule.
There are other containers with similar setups, containers don't talk directly to each other but by iptable rules for specified ports.
I post all iptable rules in case they interfere with each other
# Generated by iptables-save v1.4.21
*nat
:PREROUTING ACCEPT [760:48985]
:INPUT ACCEPT [707:45761]
:OUTPUT ACCEPT [114:7445]
:POSTROUTING ACCEPT [50:2740]

# Route HTTP & HTTPS to web container
-A PREROUTING -i eth0 -p tcp -m tcp --dport 80 -j DNAT --to-destination 192.168.1.1:80
-A PREROUTING -i eth0 -p tcp -m tcp --dport 443 -j DNAT --to-destination 192.168.1.1:443

# Route internal mysql request to mysql container
-A PREROUTING -i br1 -p tcp -m tcp --dport 3306 -j DNAT --to-destination 192.168.1.3:3306
-A PREROUTING -i br2 -p tcp -m tcp --dport 3306 -j DNAT --to-destination 192.168.1.3:3306

# Route mail from outside to mail container
-A PREROUTING -i eth0 -p tcp -m tcp --dport 25 -j DNAT --to-destination 192.168.1.2:25
-A PREROUTING -i eth0 -p tcp -m tcp --dport 143 -j DNAT --to-destination 192.168.1.2:143
-A PREROUTING -i eth0 -p tcp -m tcp --dport 587 -j DNAT --to-destination 192.168.1.2:587
-A PREROUTING -i eth0 -p tcp -m tcp --dport 993 -j DNAT --to-destination 192.168.1.2:993
-A PREROUTING -i eth0 -p tcp -m tcp --dport 4190 -j DNAT --to-destination 192.168.1.2:4190

# Route mail from web container to mail container
-A PREROUTING -i br1 -p tcp -m tcp --dport 25 -j DNAT --to-destination 192.168.1.2:25
-A PREROUTING -i br1 -p tcp -m tcp --dport 143 -j DNAT --to-destination 192.168.1.2:143
-A PREROUTING -i br1 -p tcp -m tcp --dport 587 -j DNAT --to-destination 192.168.1.2:587
-A PREROUTING -i br1 -p tcp -m tcp --dport 993 -j DNAT --to-destination 192.168.1.2:993
-A PREROUTING -i br1 -p tcp -m tcp --dport 4190 -j DNAT --to-destination 192.168.1.2:4190

# Mark packages
-A POSTROUTING -o eth0 -j MASQUERADE
-A POSTROUTING -o br1 -j MASQUERADE
-A POSTROUTING -o br2 -j MASQUERADE
-A POSTROUTING -o br3 -j MASQUERADE

COMMIT
# Completed
# Generated by iptables-save v1.4.21
*filter
:INPUT ACCEPT [35371:3912708]
:FORWARD ACCEPT [48:2620]
:OUTPUT ACCEPT [29159:6870938]

# All containers are allowed to place calls from inside to outside
-A FORWARD -i eth0 -o br1 -m state --state RELATED,ESTABLISHED -j ACCEPT
-A FORWARD -i eth0 -o br2 -m state --state RELATED,ESTABLISHED -j ACCEPT
-A FORWARD -i eth0 -o br3 -m state --state RELATED,ESTABLISHED -j ACCEPT

COMMIT
# Completed

IP Route in case it matters
192.168.1.1     *               255.255.255.255 UH    0      0        0 br1
192.168.1.2     *               255.255.255.255 UH    0      0        0 br2
192.168.1.3     *               255.255.255.255 UH    0      0        0 br3

How should I modify this rules to keep the source IP or should I approach this differently?
Comment: To clarify: I want traffic to be seen as it comes from the host to the _outside_, but need the original client ip _inside_.
Comment: To be clear : once the outgoing trafic NATed with the public IP, you still want to be able to get the original private IP ? In this case you should approach things differently...but from now i don't know how because i am not sure to really get what you are trying to achieve...
Comment: No: A calls my server B. B forwards traffic to C and currently replaces A's IP with the IP from B. Now C tries to validate the IP via rDNS and (of course) finds nothing because it's private address space, so the check fails and the mail get's rejected.
What I want is A calling B, B forwarding to C **keeping the IP from A**, C can validate correctly, send response via B, which replaces C's private IP with the public one from B, so A never knows there is C. (As supposed by NAT)
Comment: What about not masquerading outgoing packets to br2 on port 25 ?
Comment: "_What I want is A calling B, B forwarding to C keeping the IP from A,_" That is called routing. If you NAT when you route, you normally translate the destination address, not the source address. Why are you translating the source address?
Answer: Drop these rules:
-A POSTROUTING -o br1 -j MASQUERADE
-A POSTROUTING -o br2 -j MASQUERADE

They perform SNAT on all traffic going to br1 and br2.  Normally you will only want to have one MASQUERADE rule on the interface connected to the Internet.
If each container is on on a separate bridge, I would put the containers in different subnets.  They don't need to be full /24s.  A /30 would is sufficient to route one IP address.
Comment: Using `/30` wastes half the addresses. You should be able to use `/31` for point-to-point networks. Way back in the year 2000, [RFC 3021, Using 31-Bit Prefixes on IPv4 Point-to-Point Links](https://tools.ietf.org/html/rfc3021) was approved.
Comment: I mark this a the correct answer to my question, but to anyone who might stumble upon this while searching note that this will break the forwarding between container interfaces
Comment: @Kimmax. Updated with routing that won't break and won't need NAT for local connections.
Comment: thanks, however they actually are /32's already (IP scheme is as is because they were on the same subnet initially) and the bridges don't have a uplink at all
Comment: @Kimmax Convert them to /30s. These can be subnets of /192.168.1.0/24 if you wish.  /32s cause the kind of issues you are encounteriing.
Comment: @RonMaupin If that is a concern on 192.168 addresses. Try a 172.16 or 10.  Minimal wastage of private addresses shouldn't be a concern if you are on 192.168.1.0/24  Just move them to 192.168.10.0
Comment: We don't actually set all user networks to `/24`. Actually, we have run out of all RFC 1918 address space...
Comment: @RonMaupin  All three blocks?  Have you considered IPv6 (at least for inter-container communication) ?   Or add routes for the container IPs via the containing host's IP.
Comment: @BillThor, yes, all three blocks (our network is larger than many ISPs' networks), and we are rolling out IPv6, too, but IPv6 is a challenge because of vendors' promises of IPv6 support that ends up being smoke and mirrors, and we are trying to do it right the first time. It turns out that the average number of times a company changes its IPv6 address scheme and must readdress everything is three times, but we only want to do it once because the network is just too large.

Forward port and keep source IP