Email validation '+' not accepting

Question: I have written email validation as follow.
if($email != ''){
             if (!ereg("^[_a-zA-Z0-9]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,3})$",$email)) {
               form_set_error($email, t('Please enter a valid Email address.'));
             }
          }

But when i try to register with 'firstname.lastname@example.com' , Not accepting with '+'. Can any one correct my code..Thanks
Comment: The problem with your code is that you're using a [regular expression to validate email addresses](http://www.regular-expressions.info/email.html). [A "correct" regex is a beast](http://ex-parrot.com/~pdw/Mail-RFC822-Address.html).
Answer: No need to reinvent the wheel: valid_email_address().
Answer: Couldn't resist adding this in...the only regex that will correctly identify any* valid email address:
(?:(?:\r\n)?[ \t])*(?:(?:(?:[^()@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t]
)+|\Z|(?=[\["()@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:
\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()@,;:\\".\[\] \000-\031]+(?:(?:(
?:\r\n)?[ \t])+|\Z|(?=[\["()@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[
\t]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t])*(?:[^()@,;:\\".\[\] \000-\0
31]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\
](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()@,;:\\".\[\] \000-\031]+
(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:
(?:\r\n)?[ \t])*))*|(?:[^()@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z
|(?=[\["()@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)
?[ \t])*)*\@,;:\\".\[\] \000-\031]+(?:(?:(?:\
r\n)?[ \t])+|\Z|(?=[\["()@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[
 \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)
?[ \t])+|\Z|(?=[\["()@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t]
)*))*(?:,@(?:(?:\r\n)?[ \t])*(?:[^()@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[
 \t])+|\Z|(?=[\["()@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*
)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t]
)+|\Z|(?=[\["()@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*)
*:(?:(?:\r\n)?[ \t])*)?(?:[^()@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+
|\Z|(?=[\["()@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r
\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()@,;:\\".\[\] \000-\031]+(?:(?:(?:
\r\n)?[ \t])+|\Z|(?=[\["()@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t
]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t])*(?:[^()@,;:\\".\[\] \000-\031
]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](
?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()@,;:\\".\[\] \000-\031]+(?
:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?
:\r\n)?[ \t])*))*\>(?:(?:\r\n)?[ \t])*)|(?:[^()@,;:\\".\[\] \000-\031]+(?:(?
:(?:\r\n)?[ \t])+|\Z|(?=[\["()@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?
[ \t]))*"(?:(?:\r\n)?[ \t])*)*:(?:(?:\r\n)?[ \t])*(?:(?:(?:[^()@,;:\\".\[\]
\000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()@,;:\\".\[\]]))|"(?:[^\"\r\\]|
\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()
@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()@,;:\\".\[\]]))|"
(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t]
)*(?:[^()@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()@,;:\\
".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?
:[^()@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()@,;:\\".\[
\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*|(?:[^()@,;:\\".\[\] \000-
\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(
?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)*\@,;
:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()@,;:\\".\[\]]))|\[([
^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()@,;:\\"
.\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()@,;:\\".\[\]]))|\[([^\[\
]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*(?:,@(?:(?:\r\n)?[ \t])*(?:[^()@,;:\\".\
[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()@,;:\\".\[\]]))|\[([^\[\]\
r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()@,;:\\".\[\]
\000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()@,;:\\".\[\]]))|\[([^\[\]\r\\]
|\\.)*\](?:(?:\r\n)?[ \t])*))*)*:(?:(?:\r\n)?[ \t])*)?(?:[^()@,;:\\".\[\] \0
00-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\
.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()@,
;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()@,;:\\".\[\]]))|"(?
:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t])*
(?:[^()@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()@,;:\\".
\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[
^()@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()@,;:\\".\[\]
]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*\>(?:(?:\r\n)?[ \t])*)(?:,\s*(
?:(?:[^()@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()@,;:\\
".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:(
?:\r\n)?[ \t])*(?:[^()@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[
\["()@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t
])*))*@(?:(?:\r\n)?[ \t])*(?:[^()@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t
])+|\Z|(?=[\["()@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?
:\.(?:(?:\r\n)?[ \t])*(?:[^()@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|
\Z|(?=[\["()@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*|(?:
[^()@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()@,;:\\".\[\
]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)*\@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["
()@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)
?[ \t])*(?:[^()@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()
@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*(?:,@(?:(?:\r\n)?[
 \t])*(?:[^()@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()@,
;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t]
)*(?:[^()@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()@,;:\\
".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*)*:(?:(?:\r\n)?[ \t])*)?
(?:[^()@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()@,;:\\".
\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:(?:
\r\n)?[ \t])*(?:[^()@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\[
"()@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])
*))*@(?:(?:\r\n)?[ \t])*(?:[^()@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])
+|\Z|(?=[\["()@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\
.(?:(?:\r\n)?[ \t])*(?:[^()@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z
|(?=[\["()@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*\>(?:(
?:\r\n)?[ \t])*))*)?;\s*)
Scary, huh?
*With the following caveat:

This regular expression will only validate addresses that have had any comments stripped and replaced with whitespace

From http://www.ex-parrot.com/~pdw/Mail-RFC822-Address.html
Comment: @Thirupathi I only put this here for fun really, you should really go with Berdir's suggestion (if you profile your CPU while running that regex you'll see why!) It's totally your call but might I suggest accepting that one as the correct answer instead of this one? :)
Comment: fun-fun-fun!)))
Comment: This will be fun if this was on Stack Overflow , there s no tag called `regex` in this stack exchange !!!
Comment: @kantu I see you've taken care of that ;)
Comment: And I can't resist mentioning that this validates the `address` grammar element when it should validate the `addr-spec` element for what we think of as a [normalized] email address today. There's no legitimate need to allow people to specify their address as "John Q. Public " when "email@example.com" will do, with the other bit either as a separate field, or omitted entirely because what we REALLY want is an RFC **821** `mailbox` element. And 90% of that regex is for a totally obsolete 'group syntax' for specifying certain kinds of mailing lists.
Comment: This regex [which incidentally, you pasted wrong or markdown messed up] repeats the code for `addr-spec` four times surrounded by other stuff, and within it there are extra bits intended for allowing, of all things, _line breaks_ in the middle of the address.
Comment: @Random382 It's copied verbatim from the linked page so if there's a discrepancy it's an issue with markdown. Just to clarify, I posted this as a playful example of a regex that conforms to RFC822 (not RFC821), don't take it too seriously, I would hope no-one ever actually tried to use it :)
Answer: The problem with your code is that you aren't allowing the + in the regex.
<?php

$email = 'firstname.lastname@example.com';

if ($email != '') {
  if (!preg_match("/^[_a-zA-Z0-9]+(\.[_a-zA-Z0-9-\+]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,3})$/",$email)) {
    print "'{$email}' is not valid\n";
  } else {
    print "'{$email}' is valid\n";
  }
}

I converted this to use PCRE.  Note the change right before the @ in the regex.
But don't use this.  Use the builtin as @Berdir suggested or use the Email Field module, which has some nice extras in addition to validation.
Comment: MPD, your code also i tested, worked for me..
Answer: A regex to validate the a version of the addr-spec RFC grammar element [RFC 822, but corrected to not have local-parts like "foo bar".baz."a b c" as later versions of the RFC, and RFC 821, only allow a single quoted string rather than a quoted string as part of a dot string] without allowing embedded comments or whitespace/linebreaks:
(?:[^()<>@,;:\\". \000-\031]+(?:\.[^()<>@,;:\\". \000-\031]+)*|"(?:[^"\]|\.)*")
@
(?:[^()<>@,;:\\". \000-\031]+(?:\.[^()<>@,;:\\". \000-\031]+)*|\[(?:[^ \]\\]|\.)*\])

I have not tested this, so there may be typos or markdown problems.
Note that this does not allow a username portion containing two dots in a row, or beginning or ending with a dot, or a domain ending with a dot, as the spec does not technically allow these. It does allow such as firstname.lastname@example.com, even though by the spec such an address should be firstname.lastname@example.com, to simplify the number of character classes used.
A simpler version of the regex which allows two dots in a row or beginning or ending with a dot, despite the spec not technically allowing this:
(?:[^()<>@,;:\\" \000-\031]+|"(?:[^"\\]|\.)*")
@
(?:[^()<>@,;:\\" \000-\031]+|\[(?:[^ \]\\]|\.)*\])

Comment: Nice solution (I don't have time to test exhaustively but it seems to work fine). Any chance you've got any links to good articles/discussions on this topic? I'd be interested to learn a bit more about it

Email validation '+' not accepting


Is it allowed to use augmented matrix technique in solving system of non-linear equations

Question: Question is :
The system of equations:
$$\begin{align}
1⋅x+2⋅x^2+3⋅xy+0⋅y=6\\
2⋅x+1⋅x^2+3⋅xy+1⋅y=5\\
1⋅x-1⋅ x^2+0⋅xy+1⋅y=7\end{align}$$
(a) has solution in rational numbers
(b) has solution in real numbers
(c) has solution in complex numbers
(d) has no solution
The given system is not linear and the variables are also not independent, so I was skeptical to use augmented matrix technique that we use in linear case.
Doing $(ii)+(iii)$ and $2(ii)-(i)$, we get two contradictory equations, by which we can conclude option (d) is correct.
Then I just thought of using augmented matrix technique, to see what that will result in.
Doing some row operations, last row became $\begin{bmatrix}0&0&0&0&|&8\end{bmatrix}$, which also says no solution.
My question is, can we apply augmented matrix technique in case of non linear equations also?
Answer: You can apply the technique, but you must be careful when interpreting its results.
In particular, what you can do is this. You can introduce $4$ new variables like so: $a=x, b=x^2,c=xy, d=y$. Now, any solution to the original set  of equations will also be the solution to the set of linear equations
$$a+2b+3c+0d = 6\\
2a+b+3c+d=5\\
a-b+0c+d=7$$
and because the linear system above has no solutions (this part can be proven using the augmented matrix technique), you can conclude that the original system has no solutions.

However, this line of reasoning is a one way street. In general, the linear system might have solutions even if the original system does not have them. A trivial example would be the equation $$x^2=-1$$ which has no solutions in $\mathbb R$, but if you introduce a new variable $a=x^2$, the linear equation $a=-1$ clearly has a solution.
A less trivial example would be the system of equations as follows:
$$\begin{align}
1\cdot x^2+2\cdot xy+1\cdot y^2 + 0\cdot x + 0\cdot y = 1\\
0\cdot x^2+0\cdot xy + 0\cdot y^2 + 1\cdot x+1\cdot y=2
\end{align}$$

If you transform the system to $$1\cdot a + 2\cdot b + 1\cdot c + 0\cdot d + 0\cdot e = 1\\
0\cdot a + 0\cdot b + 0\cdot c + 1\cdot d + 1\cdot e = 2$$
then this system has infinitely many solutions.
The original system has no solutions, because the first equation translates to $(x+y)^2=1$, which is incompatible with the second equation which is $(x+y)=2$.

So, TL;DR: you can use linear equations to prove there is no solution, but the existence of a linear solution does not mean that a solution exists.
Comment: Great answer! In the last system of two equations the first equation has an $x$ that should be a $c$. I cannot edit is since edits should be at least 6 characters long
Comment: @Vincent Thanks, fixed!


How do you make text in a frame change dependent on cursor position?

Question: I have a program that is basically just supposed to change the text of a label when your cursor enters a polygon that is shown on the JPanel. I have tried a few different things with nothing working. Currently I am trying an if statement to make it choose which button to add but it still doesn't change if i move my cursor into the polygon. when the cursor is outside of the polygon the label should say "point is not in the polygon" and when inside it should say "point is in the polygon". Any help would be greatly appreciated.
import javax.swing.*;

import java.awt.*;
import java.awt.event.*;

public class Chapter3Lab1  extends JFrame{

private RegularPolygonPanel canvas = new RegularPolygonPanel();

public Chapter3Lab1()
{

    JPanel panel = new JPanel();

    add(canvas, BorderLayout.CENTER);
    add(panel, BorderLayout.SOUTH);

    canvas.setFocusable(true);
    canvas.requestFocusInWindow();

}

public static void main (String[] args)
{

     String isInside = "The point is in the polygon";
     String notInside = "The point is not in the polygon";

     //Create a Polygon object
     Polygon polygon = new Polygon();

    polygon.addPoint(40,20);
    polygon.addPoint(70,40);
    polygon.addPoint(60,80);
    polygon.addPoint(45,45);
    polygon.addPoint(20,60);

    JLabel label = new JLabel(isInside, JLabel.CENTER);
    JLabel notlabel = new JLabel(notInside, JLabel.CENTER);

    Chapter3Lab1 frame = new Chapter3Lab1();;
    frame.setTitle("Chapter 3 Lab 1");
    frame.setLayout(new FlowLayout());
    frame.setLocationRelativeTo(null);// Center the frame
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(200,200);
    while (true)
    {
        PointerInfo a = MouseInfo.getPointerInfo();
        Point b = a.getLocation();
        int x = (int) b.getX();
        int y = (int) b.getY();
        if(polygon.contains(x, y) == false)
        {
        frame.remove(label);
        frame.add(notlabel);
        }
        else
        {
        frame.remove(notlabel);
        frame.add(label);
        }

        frame.setVisible(true);
        try
        {
            Thread.sleep(1000);
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
    }

}

class RegularPolygonPanel extends JPanel
{

     protected void paintComponent(Graphics g)
     {
         super.paintComponent(g);

         //Create a Polygon object
         Polygon polygon = new Polygon();

        polygon.addPoint(40,20);
        polygon.addPoint(70,40);
        polygon.addPoint(60,80);
        polygon.addPoint(45,45);
        polygon.addPoint(20,60);

         //Draw the polygon
         g.drawPolygon(polygon);
     }

     public Dimension getPreferredSize()
     {
         return new Dimension(200,200);
     }
}
}

Answer: Start by taking a look at How to Write a Mouse Listener
You will need to maintain a reference to the Polygon object and make use of it's contains method to determine if the mouse is within the Polygon itself...
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Polygon;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private RegularPolygonPanel polyPanel;
        private JLabel label;

        public TestPane() {
            polyPanel = new RegularPolygonPanel();
            polyPanel.addMouseMotionListener(new MouseAdapter() {
                @Override
                public void mouseMoved(MouseEvent e) {
                    if (polyPanel.isWithinPolygon(e.getPoint())) {
                        label.setText("Is inside");
                    } else {
                        label.setText("Is outside");
                    }
                }
            });
            label = new JLabel("...");
            setLayout(new BorderLayout());
            add(polyPanel);
            add(label, BorderLayout.SOUTH);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

    }

    class RegularPolygonPanel extends JPanel {

        private Polygon polygon;

        public RegularPolygonPanel() {
            //Create a Polygon object
            polygon = new Polygon();

            polygon.addPoint(40, 20);
            polygon.addPoint(70, 40);
            polygon.addPoint(60, 80);
            polygon.addPoint(45, 45);
            polygon.addPoint(20, 60);
        }

        public boolean isWithinPolygon(Point p) {
            return polygon.contains(p);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);

            //Draw the polygon
            g.drawPolygon(polygon);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }
    }
}


Is $this->load->model('model_name'); == $var = new Model_name();?

Question: I want to know if I'm doing the right thing Object Oriented Programming in Codeigniter Models because I'm confused with $this->load->model('model_name'); and $var = new Model_name();
Right now I'm using $this->load->model('model_name'); and I can call all functions using $this->model_name->functionName(); while on the other hand, where lots of tutorials of OOP using this one $var = new Model_name(); and I also able to call all functions using $model_name->functionName().
Thanks!
Answer: Don't worry. You are using it correctly and assigning it to the CI object. The vast majority of times when you see it structured
$model = new Model();

Is when models are implemented in custom libraries out of the CI instance.
Comment: Thanks for the reply. Actually I can also do like `$this->ci =& get_instance();` and load the model with `$this->ci->load->model('model_name');`. Can you discuss it further? cause I've that feeling that I'm still doing the procedural way not the OOP way
Comment: The only time you need to get an instance of CI is when the class you in does not extend CI. When your class starts.. my controller extends CI_Controller you automatically inherit the parent classes methods hence $this is refering directly to CI. If you have an external class your loading that you would like to access CI features in you need to get an instance in order to access the CI object. Hence $this->ci. If your working in a CI model/controller rather use your inherited methods or you will pollute your scope
Comment: Sorry I forgot to say that I'm talking of what you said earlier `custom libraries`. I just want to know if `$this->load->model('model_name');` and `$var = new Model_name();` is identical? why? why not?
Comment: Yes they are,except that $this->load->model automatiocally assigns the model to a variable within the $CI class, equivelant to $this->ci->my_model = new my_model()


Can we read environment variables of child from parent process

Question: I know that fork will create a child process and then execve in the child process will execute  the program setting some environment variables.
My task here is, My parent process parent1 has initially created a child process Child1 following the fork/exec procedure and set an Environment variable "CHILD=first".
Later in the execution of parent process, I have created another child process
Child2 following the same fork/exec procedure. This child2 has an environment variable set as "CHILD=second".
Now, later in the execution of parent process, I have to read all the environment variables of child1 and child2 from Parent1 for some operations based on the env values. Is it possible to read these child environment variables from parent process? If so, how can I do it?
Comment: Why do you want this?  The parent should maintain interesting information about its children in its own data structure, probably indexed by process ID.
Comment: See [Q&A here](http://unix.stackexchange.com/questions/29128/how-to-read-environment-variables-of-a-process).
Comment: Use can check using any of `IPC` mechanisms like pipe,..
Comment: Why not just hold "child state" within the parent?
Answer: You can read the environment from <code>/proc/<pid>/environ</code>, on Linux. The variables are separated by nul-characters.
Comment: The values in `/proc//environ` are not updated dynamically, but display only the initial environment of the process.  It is not clear to me from the question whether the value of CHILD is set pre-fork or only in the child, so reading `/proc//environ` may not be useful.
Comment: Hmm, in that case he's gonna need IPC, via pipes, files, or shared memory.


Computation of the intercept in logistic regression model

Question: I'm trying to understand the way the odds of the reference groups are computed. Let's consider an example from this paper. Data can be summarised in the table:

The reference group is Older and New. The authors run a logistic regression model and found that:

So, exp(β0) = exp(−2.121) = 0.12 is the chance of death among those individuals that are older and received new treatment.

How can this chance of death (0.12) can be computed directly from the data? Why it's not just 6/34?
Thanks!
Answer: Essentially it's because of the way they parameterized the model. The model they used is
$$\log (\frac{\pi}{1-\pi}) = \beta_0 + \beta_1 X_{young} + \beta_2 X_{stand}$$
This model assumes that age and treatment have additive effects on the log odds of the outcome, meaning that whether you are old or young has no bearing on the effect of the treatment. It's not straightforward to compute the coefficients from the table because the effect of treatment "averages across" levels of age in a somewhat opaque way determined by the statistics behind how the coefficients are estimated. Rather than being directly computable from the table, the coefficients are estimated as those that make the data in the table most likely, again assuming additive effects of age and treatment. So the intercept represents the "model-implied" estimate of the log odds of the event for those that are older and received the new treatment.
The reason the model-implied estimate and the empirical (i.e., observed) odds ratio differ is that the model isn't saturated: three quantities were estimated, but there are four unique odds ratios (one for each combination of age and treatment). In a saturated model, the same number of quantities are estimated as there are combinations of the variables. A saturated model would be the following:
$$\log (\frac{\pi}{1-\pi}) = \beta_0 + \beta_1 X_{young} + \beta_2 X_{stand} + \beta_3 X_{young} X_{stand}$$
In this model, there are four quantities being estimated. This model doesn't assume that the effect of treatment is consistent across levels of age. It allows for an interaction between treatment type and age, which is what the $\beta_3$ term represents. In this model, $\exp(\beta_0)$ is indeed equal to the empirical odds for the older group who received the new treatment. The model fits the data perfectly in that the model-implied odds are exactly equal to the empirical odds for each of the four groups.
We can see this using R:
fit1 <- glm(state ~ age + treatment, data = d,
            family = binomial, weights = count)

coef(fit1)
#>    (Intercept)       ageyoung treatmentstand
#>     -2.1204648      0.4543151      1.3329042
exp(coef(fit1))
#>    (Intercept)       ageyoung treatmentstand
#>      0.1199759      1.5750942      3.7920402

fit2 <- glm(state ~ age + treatment + age:treatment, data = d,
            family = binomial, weights = count)

coef(fit2)
#>             (Intercept)                ageyoung          treatmentstand
#>              -1.7346011              -0.1016102               0.8906310
#> ageyoung:treatmentstand
#>               0.6397159
exp(coef(fit2))
#>             (Intercept)                ageyoung          treatmentstand
#>               0.1764706               0.9033816               2.4366667
#> ageyoung:treatmentstand
#>               1.8959421

6/34
#> [1] 0.1764706

Created on 2020-01-09 by the reprex package (v0.3.0)
fit1 is the model used in the paper. When we take $\exp(\beta_0)$ we get $.12$. fit2 is the saturated model with the interaction. If we take $\exp(\beta_0)$, we get $.176$, which is indeed equal to $6/34$.
Comment: That's a great and clear explanation. I wonder why I have never come across this issue in the textbook. It's a nice example of how model specification affects an interpretation of otherwise "easily interpretable "regression parameter. Thanks


Importando dados EXCEL para PHP!

Question: Olá, venho pedir uma ajuda em relação a EXCEL e PHP;
A pouco tempo entrei em uma empresa, onde tem um dashboard feito em VBA em EXCEL, porém, percebi que ele da muito problema. Então resolvi desenvolver um novo dashboard, retirar do VBA e ir para o Browser(HTML5, PHP e Mysql pois tem sistema de login e senha).
O dashboard no excel faz o seguinte:

Ao aperta a seta verde ele começa a fazer suas funções
Com a extensão do SELENIUM, ele acessa automaticamente o site, faz o dowload das planilhas em Excel e coloca os valores no dashboard
A cada 4 minutos ele deleta tudo que está na pasta dowload(onde os arquivos são baixados) e faz esse procedimento todo de novo, sempre atualizando os dados;

Aqui está a imagem do dashboard: https://prnt.sc/fhdemt
Ele imprime os valores na tela tudo bonitinho, sobe a barrinha ali onde está o "Planejado x Produzido", calcula a porcentagem, etc...
Eu quero migrar tudo isso pro Browser, pra PHP. Quero que ele faça o mesmo dessas funcionalidades dele. Mas como?! Como fazer o PHP também acessar o site automaticamente, fazer o dowload e jogar tudo na tela?
OBS: Vou utilizar o mesmo modelo do dashboard do excel, no browser...
Salvo a imagem em PNG e coloco no browser e depois jogo as informações em cima? Ou faço o mesmo dashboard do 0?
Agradeço de coração a quem me ajudar!!! Estou pegando muito fragmentos de códigos desse tipo na internet, mas nada concreto.
Answer: Sim, você pode fazer isso via PHP também.
Você precisará fazer o download do arquivo usando a função file_get_contents() do PHP.
Precisará usar uma biblioteca para ler o conteúdo dos arquivos Excel, como por exemplo:
https://sourceforge.net/projects/phpexcelreader/
Ou então:
https://github.com/PHPOffice/PHPExcel
Eu sugiro que você crie o dashboard do zero com HTML e CSS ao invés de gerar uma imagem e sobrepor os dados.
Comment: Agradeço pela informação Diego! Abraços
Answer: Foram várias dúvidas em apenas uma única pergunta, então vamos por parte:

Você deverá desenvolver um dashboard do zero, assim será mais fácil prestar manutenção futuramente.
Sobre acessar o arquivo do site, você pode fazer uma cópia dele para o /tmp do seu projeto, usando o método Copy. Assim, caso necessite manipular o arquivo novamente não precisará realizar uma nova requisição ao site. Segue um exemplo usando Copy:
$url = "http://site.com/arquivos/nome.csv";
if (copy($url, '/tmp/' . urldecode(basename($url)))) {
    echo 'Arquivo copiado com sucesso!';
} else {
    echo 'Erro ao copiar arquivo!';
}

Para manipular arquivos .csv no php, segue uma resposta no Stack sobre o assunto;
Para manipular as informações no html. Não é a melhor forma, mas como você está no início, já ajuda;

Acredito que respondi todas as informações que havia descrito. Caso tenha mais dúvidas, divida em perguntas no Stack. Quando mais descrição melhor será ajuda.
Comment: O site tem login e senha. Como faço pra por pra ele mesmo colocar o login e senha e apertar o botão?
Comment: selenium.Start "chrome", "about:blank"
selenium.Window.SetPosition 0, -1100
On Error GoTo Erro
selenium.Get "https://siteaqui/"
selenium.FindElementById("user_login").SendKeys cUsername
selenium.FindElementById("user_password").SendKeys cPassword
selenium.FindElementById("sign_in_button").Click

Em VBA eu uso assim.
Comment: @AlexandreAmado sua pergunta refere-se sobre excel e php, mas seu comentário é contendo o erro é sobre [selenium](https://wiki.saucelabs.com/display/DOCS/Getting+Started+with+Selenium+for+Automated+Website+Testing#GettingStartedwithSeleniumforAutomatedWebsiteTesting-IntroducingSelenium). Eu não tenho o conhecimento necessário para te ajudar referente automatização de interação web. Recomendo que crie um novo post para que entendedores do assunto possam te ajudar.
Comment: Não, foi apenas um exemplo @DjalmaManfrin. Eu quero saber como eu faço pra ele automaticamente colocar login e senha, acessar o site e fazer o download. Ai em cima você ensinou apenas como entrar no site e baixar, mas o site que quero acessar pede login e senha( eu tenho o login e senha ).
Comment: Sabe me dizer se o servidor é ftp?
Comment: Esse é o site: https://packmanager.nulogy.net/sign_in
Comment: Entre em contato com o suporte da hospedagem e veja se elem trabalham com ftp
Comment: Estou longe da empresa nesse momento, mas deixei uma mensagem pro Gestor de produção. Pra que será necessário saber se é FTP?! Pode apenas me dizer o código pra eu ter uma base de como seria esse acesso? Pra eu testar aqui, em vez de esperar a resposta do Gestor.

Importando dados EXCEL para PHP!


Maven exception "Plugin org.apache.maven.plugins:maven-surefire-plugin:2.12.4 or one of its dependencies could not be resolved"

Question:
i have a problem that i can't execute this order "mvn clean package -DskipTes" in my vitural machine (centos)
Comment: The message `protocol version` shows that you are going with Java 6 or Java 7...See https://central.sonatype.org/articles/2018/May/04/discontinued-support-for-tlsv11-and-below/
Comment: Side comment: This version is ~6 years old. You should probably try using a newer one.
Comment: it's my first big data demo,so i just use it in recently,and when i finished this demo,i will using a newer one.
Comment: so appreciate,buddy!
Answer: It seems like you've missed the message that Maven Central now only supports TLSv1.2, see Why am I getting "Received fatal alert: protocol_version" or "peer not authenticated" from Maven Central?


$L(V)$ is infinite-dimensional

Question: Let $V$ be a vector space. Let $T$ and $S$ be in $L(V)$ and satisfy $ST-TS=I$ where $I$ is identity operator. We want to prove that $L(V)$ is infinite-dimensional.
My try is:
Using the given condition we can show using induction
$S^n T - TS^n=(n+1)S^n$ where $n$ is non negative integer.
Now a vector space is infinite-dimensional if and only if it has a infinite linearly independent subset. Here I am stuck.
Thanks.
Comment: @Aweygan Thank you for pointing it out.
Answer: Suppose that $V$ is a vector space of dimension $n$ over a field $F$ of characteristic not dividing $n$. If there are linear operators $S,T$ on $V$ such that $ST-TS=I$, then taking the trace of both sides leads to
$$ 0=\mathrm{tr}(ST-TS)=\mathrm{tr}(I)=n $$
which is a contradiction. Hence no such $S$ and $T$ can exist.
In particular, if $F$ has characteristic zero then we can conclude that if there are linear operators $S$ and $T$ on $V$ such that $ST-TS=I$, then $V$ must be infinite dimensional.
However, if $F$ has non-zero characteristic then it is possible to have $ST-TS=I$ when $V$ is finite-dimensional. Consider for instance $F=\mathbb{F}_2$, $V=F^2$, and
$$ S=\begin{bmatrix}0&1\\0&0\end{bmatrix}$$
and
$$ T=\begin{bmatrix}0&0\\1&0\end{bmatrix} $$
Then
$$ ST-TS=ST+TS=\begin{bmatrix}1&0\\0&0\end{bmatrix}+\begin{bmatrix}0&0\\0&1\end{bmatrix}=I $$
since $1=-1$ in $F$.
Comment: They're called Weyl pairs if I'm not mistaken, and as you pointed out they can only exist if $char(F) >0$
Answer: This answer may include some ideas you're not familiar with, but it does provide a proof.  Also, I will assume the vector space is over $\mathbb R$ or $\mathbb C$.
Suppose $V$ is finite-dimensional (which occurs if and only if $L(V)$ is) then it can be given the structure of a normed vector space (by choosing a basis then choosing an $\ell^p$-norm).  Since $V$ is normable, $L(V)$ can be instilled with the corresponding operator norm, making it a unital normed algebra.  From here, there is a well-known result that in any unital normed algebra $A$ with unit $I$, then $ST-TS=I$ cannot be satisfied by any $S,T\in A$  (i.e. the identity is not a commutator).
By contraposition, we obtain the result.

$L(V)$ is infinite-dimensional


implementation error when i try to put 2

Question: This is my implementation line
@implementation ViewController

however I want to add pickerViewController but even though I do
@implementation ViewController, pickerViewController I can't do it

Is there something wrong?
Answer: If I'm understanding you correctly, and you want two implementation directives on a single .m file, then you can't just comma separate the implementations. Each @implementation requires you to explicitly add @end.
@implementation ViewController
    // code here
@end

@implementation pickerViewController
    // other code here
@end


In what cases do I need to consider byte order?

Question: Do I need to consider endianness when serializing/deserializing data to write/read binary to/from the same machine? There's no network communication involved.
Comment: Why do you think you need to consider it?
Comment: I've seen byte-order-specific serialization solutions, and I wasn't sure in what situations do these come handy.
Answer:
In what cases do I need to consider byte order?

Always when de-/serialising. The reader has to interpret the bytes in the same order as the writer.
When the processes are on the same system, it is generally safe to use the native byte order. That is not safe when multiple systems may be involved because the native byte order may differ.


How to calculate chi squared from mauchly of R's ezANOVA output?

Question: I'm working through Andy Field's Discovering Statistics with R and in the repeated measure's section he shows how to calculate Mauchly's $W$ using ezANOVA from the ez package.  He then goes on to say that the chi-squared value (approximation not exact) is to be reported in a write up but doesn't explain how to jump from $W$ to $\chi^2$ (at least that I can see).  I get the df for the $\chi^2$ but not the calculation of the $\chi^2$ value.
Code to make a reproducible example:
library(reshape2); library(ez)
dat <- data.frame(id=as.factor(1:10), matrix(rpois(90, 10), ncol=9))
dat2 <- melt(dat)
ezANOVA(data=dat2, dv = .(value), wid=.(id), within=.(variable),
    detailed=TRUE, type=3)

Data frame looks like this:
   id X1 X2 X3 X4 X5 X6 X7 X8 X9
1   1  8  9  7  4 11  7 17  2  6
2   2 14 10  9  8  5 14 11 11  8
3   3  9  9  9  9 19 13  5  9 10
4   4  8  7 14  9  5  9 10  6 12
5   5  7  8 10  3  8 10  6 14 11
6   6  6  7 14  6  8 10  9  9 16
7   7  7 13 11 11  7  7 13  6  9
8   8  9  8 14  9  7  5 14  9  7
9   9 12  4  8 12  5 15 14 11  5
10 10  1  9 11  6  6  9  8  9 11

Output from ezANOVA:
$ANOVA
       Effect DFn DFd       SSn       SSd           F                   p p<.05       ges
1 (Intercept)   1   9 7416.5444  54.01111 1235.836453 0.00000000006027733     * 0.8943306
2    variable   8  72  106.1556 822.28889    1.161879 0.33404053851453236       0.1080513

$`Mauchly's Test for Sphericity`
    Effect           W         p p<.05
2 variable 0.003960765 0.6793373

$`Sphericity Corrections`
    Effect      GGe     p[GG] p[GG]<.05      HFe     p[HF] p[HF]<.05
2 variable 0.548411 0.3435378           1.134714 0.3340405

I don't care if the solution is already in some R package or if the calculation has to be done by hand (the later may be more instructive though).
Answer: Using this paper on Mauchly Test (switched the $W$ to $\log(W)$),
I can get an approximate value for $\chi^2$:
library(reshape2); library(ez)
dat <- data.frame(id=as.factor(1:10), matrix(rpois(90, 10), ncol=9))
dat2 <- melt(dat)
mod <- ezANOVA(data=dat2, dv = .(value), wid=.(id), within=.(variable),
    detailed=TRUE, type=3)
mod

#or repeated measures
k <- 5
#number of particpants
n <- 9
d <- 1 - ((2 * ((k - 1)^2)+(k - 1)+2)/(6*(k - 1)*(n - 1)))

W <- mod[[2]][2]     #Mauchly's W from ezANOVA
-(n-1)*d*log(W)      #chi^2
(k*(k - 1)/2) - 1    #df


Constrution of a particular topological space

Question: Let $n \in \mathbb N$ be a fixed natural number.

Does there always exists a topological space $(X, \tau)$ such that $\vert \tau \vert=n$ ? I am interested in both cases when the cardinality of $X$ is finite and cardinality of $X$ in infinite?

Its is clear that if $n=2^k$ then we can easily construct required topological spaces in which cardinality of $X$ is $k$ and cardinality of $\tau$ is $2^k$. It is also clear that the above fact is true for numbers other than $2^k$. For example, Sierpinski Space. But I am unable to see the other cases?
P.S: The above question is motivated from this question of Measure Theory about cardinality of sigma algebra.
Comment: Don't see the need of that edit. I would say: yes for $n=1$ (just take $X=\varnothing$).
Comment: @drhab thanks,edited : )
Comment: The spectrum of $n$ copies of a field $k$ is an answer for the first case.
Answer: Let $X = \{1, 2, \dots, n-1\}$ and let,
$$\tau = \{ O_0, O_1, \dots O_{n-1}\}$$
where,
$$O_i = \{ 1, 2, \dots i\}.$$
Notice $|\tau| = n$ and it satisfies all the conditions of a topology,

$O_0 = \emptyset$ and $O_{n-1} = X$, thus $\emptyset, X \in \tau$.
If $O_i, O_j \in \tau$ with $i \leq j$, then $O_i \cup O_j = O_j \in \tau$.
If $O_i, O_j \in \tau$ with $i \leq j$, then $O_i \cap O_j = O_i \in \tau$.

EDIT:
If $X$ is infinite and if $\{1, 2, \dots, n-2\} \subset X$, then we can pick,
$$\tau = \{O_0, O_1, \dots, O_{n-2}, X\}.$$
Comment: @Dontknowanything I know in the case that $X$ is finite and Hausdorff, then the only topology on $X$ is the discrete topology which contains $2^{|X|}$ elements so such a construction is not possible at least in the finite case.
Comment: Looking at some old class notes, the proof of the claim I made in my last comment is proved by using the fact that a finite set has a finite number of open sets so the same argument works for an infinite set and finite number of open sets. So there is no such construction if the topology is Hausdorff, regardless if $X$ is finite or infinite.
Comment: I think you can use in a similar way  $\{1,\ldots,n\}, n \in \mathbb{N}$ to define a topology with countable number of sets and $(-\infty,r), r \in \mathbb{R}$ to define a topology with an uncountable number of sets.
Comment: @benguin: Great! Thank you.
Comment: @Dontknowanything No problem! These topologies have a nice structure to them. I read a paper awhile back that uses these topologies (which they call chain topologies) to tackle the problem of counting the number of topologies on a finite set (https://cs.uwaterloo.ca/journals/JIS/VOL9/Benoumhani/benoumhani11.pdf).
Comment: @miracle173 Indeed!
Comment: @benguin Awesome..I'll surely have a look.Thank you again.
Comment: @benguin..Is there any construction if we require the topology to be  $T_2$ ?
Answer: I guess the answer is affirmative for infinite space $X$.
Just pick $n-2$ nonempty subsets $\{U_i\}$ of $X$ such that $U_1\subsetneq U_2\subsetneq U_3\subsetneq\cdots\subsetneq U_{n-2}\subsetneq X$, and let $\mathcal{T}=\{\varnothing, U_1, U_2,\ldots,U_{n-2},X\}$. Here is a visualization for $n=5$:
Comment: This is similar with  the finite case in @benguin 's post.


Existe algum padrão semelhante ao Singleton?

Question: É realmente frustrante, um pouco interessante talvez, mas frustrante acima de tudo, ainda ontem descobri como e porquê usar o padrão Singleton, e hoje, quando ia terminar uma pequena melhoria à um projecto, vi a verdadeira face do padrão. Digamos que estou um bocado perdido neste momento, por ter feito o sistema com base nesse padrão, sendo que são cerca de 10 classes, cada uma contendo uma média de 6~7 métodos, sem contar com as propriedades. Desconheço os restantes padrões pois nunca tive a chance de os experimentar e ver como funcionam, ou até onde vão.
Digamos que eu tenho este script:
# instancia para retornar todos os valores no banco de dados
$database = Database::getInstance()->get(false,array('nickname','like','',true));

# teste, para a mensagem da sessão
if(Session::exists('sucesso')):
    print Session::pop('sucesso');
    print "
";
endif;

# teste, para a sessão
if(Session::exists(Config::get('session@session_name'))){
    //print Session::get(Config::get('session@session_name')) . "
";
    print Hash::decode(Session::get(Config::get('session@session_name'))) . "
";
}

# teste, para o login
# classe faz o uso de Database::getInstance()
$usuario = new User();
if($usuario->logado()){
    print "Logado";
} else {
    print "Logue primeiro";
}

# Iterar o objecto e imprimir os respectivos valores
if($database){
    print "
(".$database->count().") Resultados Encontrados
";
    $campo_s = Config::get('mysql_fetch@campo_s');
    $campo_n = Config::get('mysql_fetch@campo_n');
    foreach($database->results() as $key=>$object){
        print $object->$campo_s . ' - ' . $object->$campo_n. "
";
    }
} else {
    print Database::error();
    print "Consulta não efetuada";
}

# teste, para a hora
print "
Data:\r".Config::dateTime()."
";

Bem na primeira linha de código deste script, tenho uma instância da minha conexão, e nela passei também alguns parâmetros para efetuar uma consulta, por hora está tudo bem.
Algures pela metade do script, crio uma instância da classe User que por ventura, também faz uso da classe de conexão, e define parâmetros para uma busca de autenticação.
No loop foreach era suposto, eu conseguir imprimir todos os valores correspondentes à minha primeira consulta no banco de dados, mas não é o que acontece, recebo apenas 1 único resultado, que é referente ao usuário autenticado. Logo pus-me a pensar, o que estarei eu a fazer de errado, passados 35~40s apercebi-me que era do padrão que estou atualmente a usar, ou seja, se for definido uma base de operação bem no cimo, e de repente surgir outra instrução ainda no meio, o resto do bloco age de acordo com essas instruções, mesmo que isto implique reescrever a busca.
No fundo não passa de uma operação linear, onde todas as instruções são processadas em linha, como se fosse um tubo de canalização fino.
Eis o padrão, utilizado:
private function __construct(){

}
// Singleton initialization
public static function getInstance(){
    if(is_null(self::$_instance)){
        self::$_instance = new Database();
    }
    return self::$_instance;
    # Desta forma funciona, mas viola o principio do padrão aplicado
    # Procurar possível solução (encontrada).
    /*
    self::$_instance = new Database();
    return self::$_instance;
    */
}

À principio fiz testes para ver se era realmente por causa do padrão, assim sendo, comecei pelo núcleo desse padrão, onde removi a condição responsável pela criação de instâncias únicas, e fiz o seguinte:
self::$_instance = new Database();
return self::$_instance;

Passei para o teste e funcinou, logo tive que devolver o método tal e qual como estava, porque desta forma estaria a violar o padrão, e fazer "sei lá oquê", que de alguma forma me tinha resolvido o problema.
Depois, veio-me a cabeça, que, por se tratarem de instruções lineares e processadas uma à uma, porquê não mover a primeira instância para o final do primeiro bloco? Então, foi o que fiz.
$database = Database::getInstance()->get(false,array('nickname','like','',true));

Movi esta instância para depois da primeira, fiz o teste e funcionou normalmente.
Posso dizer que de momento não encontrei problemas em usar o padrão neste projecto, mas o que eu realmente gostaria de saber é:
Qual é o padrão com mais semelhança com o Singleton, que me permita usar métodos públicos sem prévia instância?
Ou ainda, qual é o método alternativo e que pode ser facilmente implementado num projecto à metade, ou quase no fim? Tendo em conta que reescreveria apenas a instância de conexão na clase de conexão, mantendo a estrutura nos scripts ou clases que fazem o uso dela.
Answer: Eu não vou responder nada do início que não é muito relevante porque iria tomar muito tempo e no fundo você não vai querer a solução que tenho, mas está tudo errado. Não é um problema do padrão, é da falta dele como ele foi concebido. Isto não aconteceria se tivesse desenvolvido de forma simples usando técnicas que domina.
Não tem padrão parecido. Na verdade o mais parecido é não usar este padrão. Ou usa uma classe totalmente estática, sem precisar criar instância ou nem a classe cria, faz tudo "procedural". Ou deixa do jeito que está porque o problema é outro. Isto seria o melhor, já que começou fazer assim. Seria difícil mudar sem repensar todo o projeto.
Eu acho que você caiu na síndrome do design pattern. O que é muito comum. Ouviu falar tanto do tal do DP que achou que tinha que usá-lo em algum lugar. Você consegue dizer alguma vantagem real para seu código obtida pelo uso dele? Seja comparado com uma classe estática, ou sem classe alguma.
Eu sinto que você só queria fazer uma viagem e teve que aprender mecânica e montar o motor para conseguir o que queria. Óbvio que as primeiras montagens vão sair erradas, quando começar montar certo vai perceber que não precisava fazer isto.
Programadores experientes - e não teimosos - aprenderam (ou por ter errado, ou por ter lido boas publicações, ou por percepção própria) que é mais fácil só fazer a viagem.
Comment: Em parte tens razão, por dizer que talvez esteja tudo errado, e que me deixei levar pelo síndrome, e por outro lado devo dizer que estás errado, porque ainda antes de começar a _melhorar/atualizar_ esse projeto eu já sabia, e ainda pus-me a pensar por qual das vias deveria prosseguir, sabendo que às vezes fazer as coisas utilizando as técnicas que melhor dominamos é melhor do que experimentar técnicas novas com que não temos prática ...
Comment: E eu simplesmente decidi implementar o padrão com o objetivo de padronizar ou parametrizar a conexão utilizando técnicas digamos _"recomendadas"_, porque deves saber também que às vezes é preferível fazer o uso de métodos testados e aprovados por uma comunidade, por já terem passado nos testes de _"pros/cons"_, mas não é isso o que se pretendia de todo, digamos que eu queria fazer uma melhoria, ao mesmo tempo que fazia testes, testes estes baseados em padrões ...
Comment: Ainda em uma das minhas perguntas eu disse que não sou provido de muito conhecimento em _POO_, por isso tento aprender as mais diversas práticas existentes para esse tipo de programação. Acima de tudo agradeço a tua construtiva e sincera resposta. Posso ver qual é a solução que tens ?
Comment: Experimentação não se faz em código que vai pra produção. Essas "recomendações" são problemáticas, porque elas não contextualizam e as pessoas acham que vale pra tudo. Então você faz uso de algo aprovado para outra coisa. Mudou uma vírgula pode não estar aprovado mais. A solução você tem que dar, a não ser que eu faça tudo por você. Na outra resposta que dei sobre o assunto eu falo mais sobre a inadequação deste tipo de solução. Mas cada um faz o que achar melhor, até porque é cada um que vai arcar com as consequências de suas escolhas.
Comment: A própria produção é um teste, é basicamente isto. Eu estou neste momento a ler a outra resposta, depois analiso melhor o conteúdo nela existente.
Comment: se puderes editar a tua resposta, deixando apenas o segundo parágrafo seria bem mais direto e gratificante.


stop ie showing security warning when loading non secure images on secure page

Question: I am using the following JQuery plugin to load an image slider http://www.orionseven.com/imageloader/index.php
However this is on a secure page (https) although the images are from external urls so therefore are not on secure pages.  Is there anyway I can stop IE 7 displaying the security warning? Maybe changing my code or something?
Comment: Is it possible for you to save the files to your local server and access them relatively?
Comment: I dont think there is - you can either ensure that the external images come from an HTTPS connection or you can move them locally to your server and reference them relatively
Answer: You cannot disable those warnings.
The reason you're seing them is because the user should be notified that non-secure requests are being made (and potentially compromising the security in the process). Turning them off would be bad for the user.
Comment: ...Expect when the "user" is an actual programmer and knows what they're doing, in which case the "user" should be allowed full control. Why not just start locking down all customization options for everyone right? It's working for APPL.
Comment: I mean seriously, are you really advocating that position? I shouldn't have to figure out a work around for a simple app that I'm coding, purely for myself, just because MS *thinks* something is unsafe when I, the actual CODER, know it IS safe.
Comment: Of course I advocate for this. The browser is making a statement of fact. It's telling you that while you're loading a page that is encrypted, some items on the page are not. This defeats the purpose of encrypting anything at all.
Comment: I understand your position, however I don't believe this is something MS should restrict out-right. In my example, I'm using local JS to try and call an API from an external http domain from a well-known sit. It's absurd for MS to not allow the user to decide whether or not they want this "protection" enabled or not.
Answer: You should probably be hosting the images on your local server rather than expecting a third party to host them for you. That way they can all be served as HTTPS from the same site, and problem solved.
If you must fetch them from the third party server, you'll only be able to solve this issue if that third party also provides HTTPS on their server. In that case, you'd need to modify the URL used to request the images to change the protocol depending on what protocol the main page is being served with.
If you want to load them remotely and that remote server doesn't provide HTTPS, then you cannot get rid of the message -- it's there intentionally in IE to provide a legitimate security warning. You can't override it.
Answer: I have the exact same issue. Since M$ considers every single one of their users to be brain-dead and decided to lock-down the ability to bypass that warning, I've decided on a much simpler solution- Use literally any other browser. Check out this solution-
https://stackoverflow.com/a/23047482/3692082
Answer: You could proxy images through localy hosted php script.
https://server/image.php?url=foobar.com/foo.gif
<code><?php
echo file_get_contents("http://".$_GET['url']);
?>
</code>
some comments about cross-site-scripting vulnerability should follow:)


Prove that $\pi$ is a quotient map which is neither open nor closed

Question: Exercise: Let $X:=\mathbb{R}^2\smallsetminus((-1,1)\times(-2,2)\cup[2,3]\times[-2,2])\subset\mathbb{R}^2$ be equipped with the subspace topology and consider the map $\pi:X\rightarrow\mathbb{R}$, which is the restriction to $X\subset\mathbb{R}^2$ of the projection to the $x$-axis. Show that $\pi$ is a quotient map which is neither open nor closed.

Thoughts: It's straight-forward to see that the map is surjective as it covers all of $\mathbb{R}$ by definition, but I fail to see that it is continuous, and why the map is neither open nor closed. If $X$ were to be equipped with the product topology, then continuity would follow straight from that, but not we are dealing with a projective map with the subspace topology, which stuns me a bit. I also don't really have a clue about not being open nor closed for similar reasons.
Comment: It's actually a very nice exercise. I wish I had seen it a couple years back, when I was struggling with the definition of a quotient map.
Answer:
Continuity is trivial, as you write, because the restriction of a continuous map to a subspace is always continuous. It does not matter that the map you restrict is a projection, it is still a continuous map. (You can also check this directly, by considering preimages of open intervals on the X axis.)
To see that it is not open, consider the projection of (the intersection with $X$ of) a small open ball around a point on the left side of $(-1,1)\times(-2,2)$.
To see that it's not closed, consider instead a closed ball around a point on the left side of $[2,3]\times[-2,2]$.
To see that it is a quotient map, take the preimage of a subset of the line and notice that if it is open, so is its intersection with e.g. $\mathbf R\times (10,11)\subseteq X$; the restriction of $\pi$ to this set is an open map, which you can use to show that the set you started with had to be open on the line.


Trigonometry Functions/equations

Question: Given that $\sin A=\dfrac{8}{17},\;$ find the possible values of $\cos A$ and $\cot A$.
Can someone please explain this question? I' new to the topic, and I'm very unsure as to how its done.thanks
Answer: Well, $\sin^2A+\cos^2A=1$; this is the Pythagorean theorem.
So you know two possible values of $\cos A$. Hence you can deduce the possible values of $\cot A$.
Answer: $\cos A=\pm\sqrt{1-(8/17)^2}=\pm15/17$. Hence $\cot A=\pm15/8$.

Hope this helps.
Comment: $\cot A=\cos A/\sin A$. I think this is the definition.
Comment: May I ask how did you get cot?
Answer: Another method that might be easier would be to draw a picture.  Recalling that $\sin{A} = \frac{\text{opposite}}{\text{adjacent}}$, you would draw a right triangle with hypotenuse $17$, one side of length $8$, and use the pythagorean theorem to find the length of the other side (it happens to be $15$).  The angle $A$ is opposite to the side of length $8$, and thus adjacent to the side of length $15$, so that $\cos{A} = \frac{15}{17}$.  Drawing the picture in a Cartesian plane you'd notice a length of $\pm 15$ would work for the adjacent side, so that you would have $\cos{A} = \pm \frac{15}{17}$.  Then the definition of $\cot{A} = \frac{1}{\tan{A}} = \frac{\text{adjacent}}{\text{opposite}}$ would give you your answer.

Trigonometry Functions/equations


Como faço para usar as funções do OpenSSL no VB.Net?

Question: Existe uma DLL que eu possa usar as funções do OpenSSL, para trabalhar com assinaturas, PEM, etc.? Como trabalhar com ela?
Answer: Dê uma olhada no projeto OpenSSL.NET. Nunca utilizei, nem sei qual a completude da API, etc, mas é o único que conheço que entrega uma solução mais ou menos pronta.
Outra opção seria escrever você mesmo os PInvokes e as estruturas.
Comment: `PInvoke` é bem chato de fazer mesmo... depois que acerta funciona perfeito, mas até lá é complicado. Não conhecia essa lib. Boa sorte!
Comment: Isso é verdade, e sem falar que eu precisava descobrir as funções escritas nessas dll, que até então também não encontrei.
Obrigado!
Comment: Não seja por isso: `https://www.openssl.org/docs/ssl/ssl.html` e `https://www.openssl.org/docs/crypto/crypto.html`
Comment: Opá, agora posso ver se consigo me divertir um pouco, hehe
Obrigado mesmo, Vinicius!
Grande Abraço!
Comment: Obrigado, Vinicius!
Então, eu tentei o montar as estruturas das dll que o próprio openssl fornece, mas não consegui.
Eu encontrei uma dll com o nome de ManagedOpenSSL, consegui importar no sistema e estou verificando as funções, mas não  muita coisa a respeito dela lib.
Mas obrigado por ora!


Restrict Javascript modification of particular objects' hrefs / find out WHAT is modifying the hrefs

Question: I am working with a really old application that fills a div by calling a JavaScript on a remote server and injecting the content into the DOM.
For some reason, in Firefox, it is also replacing all of my URL hosts with another host address.
This behavior is not happening in Chrome or IE.
While I would to prevent this from happening by fixing the application, I more immediately need to know if I can write some JavaScript to "protect" particular elements in the document from being modified. (ie, the href attribute of several objects)
Is this even possible?
Even better, is there some way I can use the developer tools to find out exactly what line of the script is causing my links' domain to change?
Comment: Try [`Object.freeze`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze)
Answer: Use Object.defineProperty() to make the property readonly.
 Object.defineProperty(obj, "key", {
    enumerable: false,
    configurable: false,
    writable: false,
    value: "static"
 });

Source:
defineProperty MDN Reference
Note:
defineProperty is not supported in old browsers, if you want to support old browsers, you have to use closures to protect the data from outside. You will provide them getters, so that others can access your read only data.


How to replace "\\" to "\" C#

Question: Here is an example: "\\\r\\\n\\\u003c"
Expected Result: "\r\n\u003c"
I have tried string.Replace(@"\\\", @"\");, but it doesn't work.
Comment: `\n`, `\r` and `\u003c` are string representations of chars. Each of them is not a string but a single char. I'm not sure what you want to do but you should know that.
Comment: It looks to me like a case of the [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). OP could be trying to replace backslashes, but actually, the string already would look like "\r\n\u003c" beause the backslashed are escaped ("\\"). Now, perhaps OP does not really want "\r\n\u003c" but new line followed by "<", then that is parsing escape sequences, which is a different problem entirely. Just [adding more backslashes looks doomed to fail from my perspective](https://www.xkcd.com/1638/).
Comment: @Theraot - Didn't understand what you intend to say! Would you mind to rephrase?
Comment: @Theraot - Oops, I used `@` while escaping, my bad. Now I understood your point too.
Answer: You can use Regex.Unescape method for this approach. It will replace all double \\ with \.
Answer: Hard to tell since you don't show your exact code, but possibly you're not saving the result of your string.Replace().  Your code looks good.
The @ symbol in front of your literal strings make them verbatim literal strings, and therefore prevents the backslashes from being uses as escape characters, which is what you want here.
string.Replace() doesn't modify the input string, but rather it returns the modified string.  Perhaps you're not using the return value from string.Replace().
The following code works:
var stringWithDoubleSlashes = @"\\r\\n\\u003c";

var stringWithSingleSlashes = stringWithDoubleSlashes.Replace(@"\\", @"\");
Console.WriteLine(stringWithSingleSlashes); // displays \r\n\u003c

Answer: Replace the full char \\n to \n. Your way does't work because a backslash is used to escape charachters.

How to replace "\\" to "\" C#


O que é localidade de referência?

Question: Há várias respostas aqui que fala sobre localidade de referência, mas não explicam o que é.
Onde ela é aplicada?
E por que ela é tão importante para estruturas de dados e algoritmos?
Comment: No sentido de localidade temporal/espacial? Como [nessa resposta](https://pt.stackoverflow.com/a/94335/64969)?
Comment: @JeffersonQuesado deixei em aberto, pode falar sobre isso, eu quase perguntei sobre os tipos, mas achei que poderia torná-la ampla
Comment: [Esta resposta](https://pt.stackoverflow.com/a/33330/357) também cita localidade de referência.
Answer: Localidade de referência é um conceito vindo de arquitetura de computadores, como a memória do computador é finita existe alguns algoritmos que visam deixar o acesso a memória mais rápidos.A ideia principal é que existe memórias que são mais rápidas que outras, por exemplo, é muito mais rápido acessar um conteúdo na memória RAM do que no disco.
Esse conceito se estende também para outros softwares comercias, imagine que você tem uma parte do seus dados que é muito acessada, e outras que não são tanto, e que todos eles estão no banco de dados, toda vez que você ler ou escreve esse dado, você precisará ler e escrever no banco de dados, isso envolverá operações de I/O e são demoradas. O ideal seria que os dados que são mais acessados estivessem na memória RAM do software, dai nasce o conceito de cache.
Você pode ter vários níveis de cache, seja o cache em RAM que será o mais rápido, ou um cache em um banco de dados apropriado para isso, como é o caso do REDIS.
Quando falamos em algoritmos ou estrutura de dados o mesmo conceito é aplicado, por exemplo, imagine que você precisa calcular a sequencia de Fibronacci de um certo número, e usa um algoritmo recursivo para fazer isso, você pode usar duas abordagens, a primeira é que você sempre irá calcular o número e a segunda é que você guardará em cache os 200 últimos números calculados.
Na primeira opção você gasta menos memória porém, gasta mais processamento, já na segunda você gasta mais memória, em contrapartida com o decorrer do tempo o seu software conseguirá calcular o número mais rápido.

O que é localidade de referência?


Smoothest key change when playing same song in different key?

Question: Let's say I'm playing a song. Let's keep this easy for this example "London Bridge" and I play it in C major. After I finish this song, if I'd like to play it again but in a different key, what key would that be. What would be the smoothest key change?
I'm currently thinking this would be G, as its the next key in the circle of fifths going clockwise. But is this right? Do I just go clockwise when I want to play the same song in a different key. Or is there a better way? (Maybe from C to G is not as interesting as other keys.. not sure).
Comment: For more about this than you ever wanted to know, see https://archive.org/details/supplementtotheo00rege. (For even more information than that, Google for the complete book for which this is the supplement).
Answer: Short answer: I think it depends on the melody and the chords, because key changes often sound seamless when the transition re-purposes the existing melody notes.
Long answer: key changes are often implemented using a transition/lead-in chord. For example, if you're transitioning from the key of Cmaj to the key of D♭maj, you might add a V chord (an A♭7 chord) before moving to the new D♭maj tonal center. The A♭7 would signify a coming key change and prepare the listener for the change.
I'll use London Bridge as an example. When played in the key of Cmaj, this song ends on the notes E-C (played over the word "la-dy" and over the chord Cmaj). But the notes E-C are also found in the chord C7, which can act as a V chord for a new tonal center of Fmaj. So you could modify the final chord progression in the following way:
Lyrics:              my    fair   la-dy   ...  London
Original chords:     G7     G7    Cmaj    ...   Cmaj
New chords:          G7     G7     C7     ...   Fmaj

And now the C7 chord is acting as a V chord for a new key center of F maj. In this case, you're moving up a fourth, and it would sound extremely natural--a good transition.
Alternatively, we could recognize that the final melodic notes E-C also appear in the chord Amin. So you could take the Amin and turn it into the ii chord of a ii-V-I leading to a new key center of Gmaj:
Lyrics:              my    fair    la-dy        ...  London
Original chords:     G7     G7     Cmaj         ...   Cmaj
New chords:          G7     G7     Amin    D7   ...   Gmaj

In addition to the melody, you can use harmonic patterns to modulate. For example, it's extremely common for modulations to move the tonal center up a half step. This can happen once or repeatedly, always modulating up a half step from the prior key. For example, if you're playing in the key of Cmaj, this would entail modulating up to the key of D♭maj. In the song London Bridge, this would work melodically too, because the V chord for D♭maj is A♭7, and the 3rd of an A♭7 chord is C--the same as the final melody note. Here's how it would look.
Lyrics:              my    fair    la-dy        ...  London
Original chords:     G7     G7     Cmaj         ...   Cmaj
New chords:          G7     G7     Cmaj    A♭7  ...   Dbmaj

As long as you can turn the melody into a common/shared tone between the old harmony and the new harmony, the transition will be smooth. Among these options, there is no objectively smoothest transition--it will be a matter of personal taste and familiarity. If you can keep the root the same and change only the quality (e.g., change the final chord from Cmaj to C7, with the idea of modulating up to Fmaj), then the transition will be even subtler. This tends to favor modulating up by fourths as opposed to modulating up by fifths.
Comment: In the change from C to G, Am>D9 works well, thus keeping *both* last notes.
Answer: Smoothest?  Probably F.  It's easy to 'fall into' the subdominant, with or without a C7 to grease the way.    Most interesting?   Well, the standard trick when you feel a tune has run out of interest in one key is to go up a semitone, to Db.  Again, an Ab7 linking chord (doubtless using the C note as a pivot) is optional.   Up a tone to D is also a standard trick.  Or up a minor 3rd is a familiar and pleasant modulation, that's into Eb.
Will anyone be singing the song? If C is a comfortable key vocally, going up or down more than one or two steps may become uncomfortable.


My textbox displaying data from serial port is updating too slow

Question: I'm making a C# Win forms app that reads data from an arduino over serial port, parses it and displays it in a textbox.
My problem is that the value in the textbox is always a few seconds older than the value being sent by arduino even if I slow down the arduino to send the data once per second.
I know the problem must be in my C# code because when I read the serial port using a serial monitor everything's fine.
my code:
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
    string msgType;
    string serialMsg;
    serialMsg = port.ReadLine();

    if(serialMsg.Substring(0, 1) != "#")
    {
        return;
    }

    msgType = serialMsg.Substring(1, 4);

    if(msgType == "VOLT") // recieve supply voltage reading
    {
        textBox1.Invoke((MethodInvoker)delegate { textBox1.Text = serialMsg.Substring(5, serialMsg.Length - 5); });
    }
    if (msgType == "AMPS") // recieve supply current reading
    {
        textBox2.Invoke((MethodInvoker)delegate { textBox2.Text = serialMsg.Substring(5, serialMsg.Length - 5); });
    }
    if (msgType == "LOAD") // recieve load current reading
    {
        textBox3.Invoke((MethodInvoker)delegate { textBox3.Text = serialMsg.Substring(5, serialMsg.Length - 5); });
    }
}

The messages coming from the arduino are in this format: # + TYPE + DATA
Can you tell me what's slowing it down?
Comment: It's odd to have `serialMsg = port.ReadLine();` inside an event handler method, and the event object `e` is not being used at all.
Comment: @MongZhu Usually when a specific class is created for an event object then it will contain additional properties that contain the needed information to respond to the event. I don't know which properties the `SerialDataReceivedEventArgs` contains, but was pointing out it was strange that it wasn't used in his code.
Comment: How was the timing when you used `//Console.WriteLine("amps");` ? instead of the textboxes?
Comment: @Loathing " and the event object e is not being used at all" how would you use it?
Comment: "The messages coming from the arduino are in this format: # + TYPE + DATA" is there a `"\r\n"` at the end of every Arduino message? because you use `ReadLine` (which is blocking) and will wait until it finds a newline in the received message.
Comment: @Loathing ok, I get it. Actually this object is quite useless in a lot of cases of serial port communication. At least that is my personal experience. It has this [strange enum value](https://learn.microsoft.com/en-us/dotnet/api/system.io.ports.serialdata?view=dotnet-plat-ext-3.1) which tells you a "bit/char" of information ;)
Comment: @MongZhu I looked it up, and it indeed seems like an empty class, so nothing useful. The example given on the [MSDN](https://learn.microsoft.com/en-us/dotnet/api/system.io.ports.serialport.datareceived?view=dotnet-plat-ext-3.1) page is the same format.
Comment: @MongZhu yes the message is terminated by \r
Comment: can you post also the arduino code? my guess would be that the newline character is not always sent. " yes the message is terminated by \r" always? actually this shouldn't be enough. Try using `ReadExisting()` and see whether the timing changes
Comment: @MongZhu When I just print to the console when I get the message it's fast as it should be
Comment: Then try this: `textBox2.BeginInvoke(new Action(() => textBox2.Text = serialMsg.Substring(5, serialMsg.Length - 5));`
Comment: @VojtaDegeš Do all the console output lines start with `#` ?
Comment: @MongZhu I tried to output the actual parsed data into the console instead of just Console.WriteLine("amps"); and it caused the same problem as with the textbox. I also tried to send only the VOLT message instead of all three of them and it solved all the lagging. I'll try to use ReadExisting to see what that does.
Comment: @VojtaDegeš Also, in general `BeginInvoke` shouldn't be called more than ever 100 milliseconds apart because it's an expensive call. So it could be that. If that is the case, then aggregate your messages, or skip some, and then only call `BeginInvoke`, much less frequently.
Comment: @VojtaDegeš Just FYI, you should be using `BeginInvoke` and not `Invoke`.
Comment: @VojtaDegeš: Try showing the data from serial port right after `serialMsg = port.ReadLine();`. Maybe all the next operations are taking a long time and causing the lagging. Then if it causes some difference then try doing the operations after the data is shown.
Answer: I was sending the messages from the arduino too quickly so I put a 50ms delay between them
I also used ReadExisting instead of ReadLine
This solved all the lagging
Comment: "I was sending the messages from the arduino too quickly so I put a 50ms delay". This high update rate is not really adequate for a gui display. Think about it, even if the gui would be able to handle all this data, do you expect a human observer to notice that a value has changed **200 times** in only **1** second?
Comment: You should really not be doing all your parsing, calculations, and gui in the data received event as that is where you are reading all the data.  Putting a delay in the Arduino is just a band aid to the issue at hand.  The PC has no issue receiving data that quickly, the issue is you're doing too much in your data received event.  A better solution would be to have a queue in which you put your data received string into and have a background worker popping the queue in which you do all your work in there.
Comment: @VojtaDeges: Please accept your answer if it works for you.


Two voices for a solo singer written in a sheet music

Question: I was reading the score for Mozart's insertion aria for his own opera Idomeneo "Non Temer Amato Bene", K. 490. In it, Idomeneo's son Idamante (scored for soprano; trouser role) expresses his undying love for Ilia.

In the Allegro Moderato section, the sheet music seems to show Idamante singing two voices. What should the soprano do differently here?
Comment: Excellent first question!  Welcome to Music Stack Exchange.
Comment: Thank you Dom for editing my tags to something more applicable. I'm a newcomer to this website so I'll have to get used to the ropes of things!
Answer: The notes with stems up are for singing in Italian, while the notes with the stems down are for singing in German.
Thus, in the first picture of the original posting, in Italian it would be

... while in German you should sing

In the second picture of the original posting, the Italian lyrics have only one syllable ("voi") while the German lyrics have two syllables ("sel - ber"). The notes are doubled with the slur upwards, suggesting that the slur is meant for the Italian lyrics only.
Comment: I looked into the full score (available at IMSLP), but there is no annotation regarding this. It seems to me that these are alternative ways to sing this part. Probably the lower alternative should be used if the singer can't reach the high notes.
Comment: What about this example? https://imgur.com/a/9YaR8sm It's from Beethoven's Ninth Symphony, 4th movement, near the solo Tenor finale. Isn't it more like an ossia?


how to add your dcom project to component services

Question: So, I am trying to add in a new dll to an old project (that I didn't start). It all goes well, in that I am able to add a dll and use its functions - no problem. However, when it came time to test the project, after building it and packaging the installer, i ran into i bit of a pinch.
Now I'm totally new to this, so I had to undergo a lot of googling the interwebs to learn how to package projects and dcom objects. Additional info: With regards to how this project is coded/packaged prior to my modifications, there was none. But! it did come with neat instructions regarding how to set the access permissions in the dcomcnfg (Component Services). The DCOM object was "ProjectCom.ProjectInfo".
I tried real hard to package and repackage the new project (even including a dll that the old project used but isn't used by the new one) but I could never seem to get the installation to add the ProjectCom.ProjectInfo entry in dcomcnfg >.< (I only knew of this ProjectCom.ProjectInfo because I kept a copy of the old installation package and run-tested the installations for comparison.)
In a nutshell, the question is: How do i get my own ProjectCom.ProjectInfo to show up in dcomcnfg?
Answer: Apparently, I haven't been searching long enough on google when i wrote the above question. DCOM objects are apparently automatically added to dcomcnfg.exe upon installation. However, mine just didn't show up until after the ProgramInfo.exe is run the first time.
No prob here. Move along. Move along.
Comment: Afterwards, i discovered that installers can actually include script for ActiveX exe to self register themselves.


Database Refactoring in Rails

Question: I need to refactor the data model for a Rails application. This will involve consolidating two models (DB tables) into one. What would be the right way to do it? Will it be ok to delete a model? I assume, this will break previous migrations. Should I use native SQL to do the DB migrations, or rather the ActionController methods?
Comment: I figured deleting Models would be bad after reading this: http://www.informit.com/articles/article.aspx?p=1652025 (look at the "Never Use External Code in a Migration").
Comment: ActionController methods? Sure, you can delete a model-why not? Probably an irreversible migration, but that's fine.
Answer: Don't worry about breaking previous migrations.  Use the db/schema.rb or db/development_structure.sql file for importing the schema into a new database.
Go ahead and delete the models.  I would use native sql (the sql code generated by Rails migrations can be very inefficient in some cases).

Database Refactoring in Rails


SVM RBF performance on "dissimilar" data

Question: I've been studying the performance of machine learning algorithms on "dissimilar" data (that is, prediction on new data that are not that "similar"  to the training set) and I came up with this example where SVM with a radial kernel completely fails, so I would like your opinion on this.
First I generated data from a simple cubic function, but with x restricted from -60 to 100, so the training set starts to show the cubic form but not all of it:
set.seed(100)
f <- function(x) 100*x + 100*x^2 - x^3 + rnorm(length(x), 10000, 10000)
x <- runif(2000, -60, 100)
y <- f(x)

Here is the plot of the training data:

Then I generated additional data of two kinds: (i) similar to the training data (that is, in the range of the observed data); and, (ii) "dissimilar" to the training data (that is, outside of the range of the observed data):
x2 <- runif(20, 60, 200) # dissimilar
y2 <- f(x2)

x3 <- runif(20, -60, 60) # similar
y3 <- f(x3)

The stripchart of the the data is as follows:

After that I assessed how both the polynomial and the radial kernel SVMs would perform on the dissimilar data set. As expected, the polynomial gets it right, but the radial completely misses it.
svmRadial <- train(as.data.frame(x), y,
                method = "svmRadial",
                tuneGrid = expand.grid(.sigma = c(1,5,15,20),
                                       .C = c(0.25, 0.5, 1,4,26,32,64)))

svmPoly <- train(as.data.frame(x), y, method = "svmPoly",
                 tuneGrid = expand.grid(.degree = 1:5,
                                        .scale = c(0.01,0.1, 1),
                                        .C = c(0.25, .5, 1)))

I have played with the tuning parameters, but could not find ones that would make the radial SVM get the pattern right.  So:

Is this a known difficulty with the radial SVM (predicting polynomial patterns out of the predictors range)?
Could you provide a technical explanation of the hard time SVM is having in this situation?
Also, if possible, it would be nice to point out some papers on this subject (known limitations of radial kernel SVMs with dissimilar predictors).
Answer: Typically, if you have prior knowledge (such as the polynomial form), you should choose your kernel based on that. Secondly, most learning algorithms have problems extrapolating, which is what you are doing. It's more common to look at how well test examples in the same range as the training set are predicted.
Regressing with an RBF kernel is somewhat like doing Fourier analysis (where the spectrum is linked to the kernel bandwidth), as you can see from the nature of the predictions which exhibit some periodicity. Here is an interesting paper on the subject.
I wouldn't consider your observation a limitation in general. You happen to be in a setting which perfectly matches the assumptions of the polynomial kernel, hence it outperforms RBF. This is natural.


What does it mean to evaluate $i^{786}$?

Question: In my book ,
To evaluate $i^{786}$.
They did. $i^{4*196 + 2}$
Why do we have to do it this way? I have to write in the exam in a subjective format. So want to know is this the only correct way to write it. Since if the exponent is sometimes bigger, why would anyone even think of doing it like this?
I would have simply said that
$-1^{786/2}$ since the power is 393. Therefore the answer is $-1$.
I understand it is more of a homework question but I just couldn't find the tag for it.
Comment: @user282657: note that, according to your reasoning, $$i=(i^4)^{1/4}=1^{1/4}=1.$$
Comment: Welcome to MSE! The title supports MathJax as well.
Comment: Thank you @Adola and e2-e4
Comment: Your answer is correct.
Answer: $i^n$ is periodic with period of $4$
$$i^1=i$$
$$i^2=-1$$
$$i^3=-i$$
$$i^4=1$$
So we only need to know the remainder when $786$ is divided by $4$:
So $i^{786}=i^{4*196+2}=i^2=-1$
Answer: Your answer raises a new question: How do you know that $(-1)^{393}=-1$? Well, you could argue:
$$
(-1)^{393} = (-1)^{2\times 196+1} = 1^{196}\times(-1)^1=-1
$$
This is basically doing with $-1$ what the book did with $i$. Since you're making a similar argument either way, the book's author probably decided that it's simpler to skip past $(-1)^{393}$ and operate directly on the expression $i^{786}$.
Answer: Notice that
$$ i = i$$
$$i^2 = i * i= -1$$
$$i^3 = i^2*i = -1*i = -i$$
$$i^4 = i^3*i = -i*i = -(-1) = 1$$
$$i^5 = i^4 * i = 1 * i = i$$
You can notice that for any integer k you'll have that:
$$i^{4k} = 1$$
$$i^{4k+1} = i$$
$$i^{4k+2} = -1$$
$$i^{4k+3} = -i$$
This is commonly written as $i^k = i^{k \mod 4}$
Answer: It's probably just a way to emphasize that the result will be $-1$, as
$$i^{4+2}=i^4\cdot i^2 = 1\cdot-1$$That's easier to comprehend.


realtime bending of strings to bring classical guitar in tune

Question: While talking with a friend, I mentioned that the width of a classical guitar neck is quite large, to allow a player room to slightly and subtly bend a string (or strings) by moving fingers parallel to frets to bring chords more accurately in tune while playing. Although this is arguably an advanced technique, it surely is used, particularly on held chords where this "pushing" of strings on frets will really help land a chord in better tune.
Two questions:

Any suggested pieces where unless this done, the equal temperament of the guitar is really noticeably out of tune? (I expect there are some trickster composers out there who have written music specifically to exploit this requirement for satisfactory performances).

Any link to a particular youtube clip where it is clear that the performer is doing this bending to bring chords into better tune?

I'd like to show my friend this being done, on a piece of classical guitar music.
Thanks.
— edit amendment:
Thanks for the interesting comments. I would really like a youtube clip of a competent performer playing an established work from the standard repertoire, that shows this kind of bending going on. I've done some dives down youtube rabbit holes, and found some that it looks like this is what's going on, but I'd really love to have one where it's really obvious, in case someone knows of one.
All in good fun, I'm not in an (ill-tempered) argument with anyone or anything, it's just interesting to me.
Comment: I thought this technique was only used to compensate for flawed tuning or a bad instrument, such as one with a false 12th fret for one string (I'm sure I've already done this on ukulele).
Comment: @Andy Bonner - sitars have these movable frets, as does the viola da gamba (e.g., in Bach's St Matthew Passion). It's fix-fretted instruments that are require something be done to play perfectly in tune, or at least try.
Comment: If a guitar needs this to be done to get into tune, it's surely time to change either the tuning, or said guitar!
Comment: The idea of adjusting a fretted instrument to overcome equal temperament is intriguing. I'd also be willing to bet it *is* done to compensate for the guitar having gone slightly out of tune since starting the piece (I certainly do it subconsciously on violin). When it comes to temperament adjustments, lutes do it all the time with their moveable gut frets.
Comment: @Andy Bonner - agreed, monitoring the status of the tuning of the guitar while playing a piece is a sign of an experienced performer, and is one reason why this subtle bending of notes might need to be done. And you're right, violinists and other string players make this kind of adjustment all the time as their instruments warm up during performance, or, to play in tune in string quartets. It's easiest for nonfretted strings (and trombonists) to make these adjustments, but it happens all the time in chamber music, especially.
Comment: @dekkadeci - I'm reminded of two jokes: (1) How long does it take to tune a hurdy-gurdy? (a: no-one knows), and (2) Ukulele players spend half of their time tuning, and the other half playing out of tune. … (I am allowed to tell these jokes, because I built a hurdy gurdy, and I'm one of those kind of ukulele players too!).
Answer: Perhaps the equal temperament interval that has the highest potential to sound out of tune is major third (or tenth or seventeenth...). However the top note in equal temperament sounds sharp with respect to just temperament, so in order to "fix" it one would need to lower the top note, not bend it. Trying to bend the bottom note would likely make the whole chord sound out of tune.
Classical guitars often have issues with intonation, especially at the higher frets. Part of the issue is that the bridge doesn't allow for easy adjustment, most classical guitars also don't have truss rod.
Indeed some people sometimes bend some notes in some chords, or adjust tuning to make sure the most critical chords sound well. But I would say it depends more on specific instrument.
Classical guitar is built with equal temperament in mind. Older instruments, like lutes or baroque guitars had often gut frets which you could slide along the neck to adjust intonation. But that of course meant compromises (by adjusting one note you made another out of tune), and possibly required adjustments whenever you played piece in another key.
Comment: Agreed, about the problem of those pesky sharp thirds in equal temperament - ain'a no way to bend a pitch _flat_ those 14 or so cents. But those flatted fifths could easily be adjusted wider, and probably should be.
Comment: I don't have personal experience with guitars with "wiggly" fret boards (by design!) which are built to play in a temperament other than equal. They must be cool (as are fanned fret boards, I imagine). But if you're playing one of these non-equal temperament fretted guitars, and you find yourself in a piece that modulates (even temporarily) from the sweeter keys, it must be time to do a little bending, if it helps.
Comment: @user2808134 I've only seen "wiggly" frets in electrical guitars actually, not nylon string classical ones....
Comment: Moveable frets actually allow quite nice compromises, as you can have the frets diagonally or even curved to get as many notes as close to in tune as possible.
Answer: Two things: A fixed, straight fret guitar won't really be ET anyway, because the tuning depends on more things than just the distance. Basically when you press down the string the tension changes, and depending on the diameter of the string the geometry might be a bit different.
That being said, a decent guitar will be quite well in tune.
The other thing is that with plucked instruments you do not have a fixed intonation. When the intonation of the string will depend on the amplitude, thus starting higher and dropping. As a result of this the brain cannot really detect tuning differences as well as on let's say a bowed instrument (because there never is any constant pitch).
This means that on a sufficiently well intonated instrument the difference to pure intervals are less noticeable than on other instruments.


Can't Remove Image from CCK File Field when editing node (Throbber just spins)

Question: I was able to upload an image, but the thumbnail didn't appear until I hit save on the form.  When I try to remove the image, it just sits there spinning the throbber; if I click on "Save" in the form, the image is not removed.
I think this has to do with AJAX getting caught up somewhere, but I don't know how to go about troubleshooting this.
Do you have any idea? I've tried switching the field from "Bar with progress meter" to "Throbber" and that didn't help.
Edit:
I forgot that I updated jQuery to the latest version and used some special code to prevent it from affecting the backend.  Here is the jquery_update_jquery_path() function from jquery_update.module (I modified it to fix this issue by checking for 'edit' in the uri):
<code>function jquery_update_jquery_path() {
  $curr_uri = request_uri();
  if (strpos($curr_uri, 'admin') > 0 || strpos($curr_uri, 'edit') > 0) {
  $jquery_file = array('none' => 'jquery.js', 'min' => 'jquery.min.js');
  return JQUERY_UPDATE_REPLACE_PATH .'/'. $jquery_file[variable_get('jquery_update_compression_type', 'min')];
  }
  else {
  $jquery_file = array('none' => 'jquery-1.5.2.js', 'min' => 'jquery-1.5.2.min.js');
  return JQUERY_UPDATE_REPLACE_PATH .'/'. $jquery_file[variable_get('jquery_update_compression_type', 'min')];
  }
}
</code>
Comment: I was able to delete the images by disabling JavaScript.  Hopefully this is only a temporary solution.
Answer: I was going to say it was probably permission-related (no delete permission) but if you managed by turning off javascript than its definitely not that.
Turn on firebug, enable the console & turn javascript back on.
If its an ajax error it will show up in the firebug console.
Comment: Throbber-type ajax issues are *often* a problem with the AJAX request, so the suggestion of firebug is perfect.
Answer: What version of JQuery are you running? I had an AJAX issue (was trying to rebuild derivative images for all nodes of a specific node-type) when using JQuery 1.5.1 instead of the version that is shipped with Drupal 6. Removing 1.5.1 and adding the stock version of JQuery resolved the issue.
Comment: That's totally expected as you really shouldn't use jQuery 1.5.1 or any version above 1.3.2 with Drupal 6. There's a reason jQuery Update module only goes as far as 1.3.2! :)
Comment: The OP didn't report he installed the latest version of jQuery, which is not what I would expect somebody does. If he really did that, I would expect that not being able to delete an uploaded image is the last of his problems. `;-)`
Comment: I used jQuery update with modified code that kept the old version of jQuery on any uri with admin in it, I just forgot to include an exception for edit.  So yes, thank you for reminding me that jQuery was the wrong version.


How to show that L2 norm is Lipschitz if the input domain is bounded?

Question: I guess that $||w||_2^2$ is 2B Lipschitz when $||w||<B$.
That's because the gradient $||w||_2^2$ is $2w$ and $w$ is bounded, but I can't show my claim according to the definition of the Lipschitzness. Can anybody help me formally prove my claim?
Comment: Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer.
Comment: What space are you working in? Is this just $\Bbb{R}^n$, with the Euclidean norm? Is it a Hilbert space? Or is it something more general? Are the scalars real? Complex?
Answer: If you define the norm of an element v, as $\left\|v \right\|=sup\frac{<v,x>}{\left\|x \right\|}$ then the Lipschitz continuity follows from the inequality sup(f(x)+g(x))$\leq $supf(x)+supg(x), which implies (set f+g=h)  , suph(x)-supf(x) $\leq$ sup(h(x)-f(x)).  Since $sup\frac{<v,x>}{\left\|x \right\|}-sup\frac{<w,x>}{\left\|x \right\|}\leq sup\frac{<v-w,x>}{\left\| x\right\|}=\left\|v-w \right\|$. Likewise the l.h.s is $\geq   -\left\|v-w \right\|$ and hence $\left|\left\|v \right\|-\left\| w\right\| \right|\leq \left\|v-w \right\|$ (1). Thus, with the standard definition of a norm of an element of the dual space, Lipschitz continuity always holds.In the case of a finite dimensional space and a Euclidean norm, the definition $\left\|v \right\|=\sqrt{v_{1}^{2}+...v_{n}^{2}}$ coincides with $\left\|v \right\|=sup\frac{<v,x>}{\left\|x \right\|}$ and again the L-continuity  holds! If you are interested in L-continuity of the square of the norm then by (1) above, $\left|\left\|v \right\|^{2}-\left\| w\right\|^{2} \right|\leq \left\|v-w \right\|\left|\left\| v\right\|+\left\|w \right\| \right|$ which implies that the square of the norm is L-continuous on bounded sets.
Comment: To the readers: A simpler proof of inequality (1) is available: https://math.stackexchange.com/questions/1068156/showing-that-the-magnitude-of-the-difference-of-two-vectors-is-larger-than-the-d


In form alter change the allowed value list programatically of select box defined using admin content type

Question: I have added a select list field using admin ui in a content type and I want to alter allowed value list and fill dynamically in form alter in drupal 7
Answer: I think last solution won't work because drupal has a mechanism to verify between allowed value and submitted value for field type list. Please see here for more information, https://api.drupal.org/api/drupal/modules%21field%21modules%21list%21list.module/7
I found below solution.Please replace field name with yours,
function test_form_node_gallery_item_node_form_alter(&$form, &$form_state, $form_id) {
  $options = system_region_list('commons_origins', $show = REGIONS_ALL);
  $all_fields_all = field_info_fields();
  $all_fields_all['field_region_list']['settings']['allowed_values'] = $options;
  field_update_field($all_fields_all['field_region_list']);
  $options = system_region_list('commons_origins', $show = REGIONS_ALL);
  $form['field_region_list']['und']['#options'] = $options;
}

It will work like a charm :)
Answer: After little bit googling, you can easily get answer of this question. Any how, you need to execute this with #after_build, something like following code.
function mymodule_form_alter(&$form, $form_state, $form_id) {
  $form['#after_build'][] = 'mymodule_action_after_build';
}

function mymodule_after_build($form, &$form_state) {
  $form['your_field_name']['value']['#options'] = array("Allowed options value");
  return $form;
}

More info: https://drupal.org/node/726282
Answer: You have to install Content Construction Kit (CCK) module. After installing this module you get a text field for Allowed value function in field setting of desired field. Put the function name here to get country list. Also put following function in a module.  You may have to modify query as per your requirement.  After doing all these thing you will able to get country list in that field.

function _get_country_list(){
    $country = array();
    $query = db_select('country', 'c');
    $query->fields('c', array('country_name','country_id'));
    $result = $query->execute();
    if ($result) {
        while ($row = $result->fetchObject()) {
            $country[$row->country_id] = t($row->country_name);
        }
    }
    return $country;
}