Extending an Interface vs Instantiating via Anonymous Class

Question: NOTE: I am aware that this is dangerously close to many other questions. I haven't seen any, however, that do not pertain specifically to Android's OnClickListener interface. I am asking in a general sense.
I understand the difference between instantiating an interface via an anonymous class...
a la:
private final Runnable runnable = new Runnable() {
    @Override
    public void run() {
        draw();
    }

};

... and extending the interface.
public class ClassyClass implements Runnable {
    ...
    //do other cool stuff here
    ...
    @Override
    public void run() {
        draw();
    }
    ...
    //and more here
    ...

}

But, other than the obvious benefits from interfaces such as OnClickListener is there a strong advantage to either option?
I would think that extending it would be the obvious choice because you are already creating that object - no duplication of effort. Is this right?
I am asking in a general sense but, as I am currently working with Runnable, if it has sees an advantage from either option I'd love to know.
Answer: Well here is an example that shows the main differences. It's a little contrived but it's just to illustrate.
Here is an anonymous version:
class PrintBuilder {
    List<Runnable> printers = new LinkedList<>();

    List<Runnable> get() {
        return printers;
    }

    PrintBuilder add(final String line) {
        printers.add(new Runnable() {
            public void run() {
                System.out.println(line);
            }
        });

        return this;
    }
}

Here is a nested version:
class PrintBuilder {
    List<Printer> printers = new LinkedList<>();

    PrintBuilder add(String line) {
        printers.add(new Printer(line));
        return this;
    }

    List<Printer> get() {
        return printers;
    }

    static class Printer implements Runnable {
        String line;

        Printer(String line) {
            this.line = line;
        }

        public void run() {
            System.out.println(line);
        }
    }
}

So you can see the main differences are then:

An anonymous class is inner and it has an implicit reference to the enclosing instance.

In particular, in the above example, the PrintBuilder is leaked until the inner Runnable objects die. In the second example, the Runnable class is static so it doesn't have this problem.

Anonymous classes are a little bit shorter.

An anonymous class doesn't need fields and constructors because they are implicit.

Big difference in the way the code is organized.

An anonymous class is declared where it's instantiated and this can be pretty destructive to the layout of the enclosing class if the anonymous class isn't very short. On the other hand if the anonymous class is short, the functional-like syntax is nice.
Also all classes tend to grow and in my experience this can turn in to a smell when an anonymous class gets too big. Anonymous classes are also much more difficult to refactor in to a top-level class.
Comment: @BrassApparatus: it's happening because, by design, inner classes have an implicit reference to their enclosing object, to be able to access their fields and methods. Just like if you had a PrintBuilder field in the printer of the second example, and passed `this` as argument of the Printer constructor.
Comment: Awesome thank you. I appreciate the concrete pro/cons. Last question. I kinda get it and I've seen others talk about that leak (in ex 1) but could you explain specifically why its happening?
Comment: @JBNizet Gotcha, thank you. I appreciate all the help.
Comment: As @JBNizet says, it's a normal aspect of all inner classes and basically the point of them in the first place. But I have seen it turn in to a leak before, basically some menu bar items were keeping entire disposed windows alive because I forgot to detach the listeners.
Answer: The first snippet defines a class, without a name, that implements the Runnable interface (and instantiates that anonymous class). The second one defines a class, with a name, that also implements the Runnable interface.
There's no difference in terms of inheritance and interface implementation except the second class has a name and the first one doesn't.
The second snippet allows multiple classes to instantiate the Runnable implementation, whereas the first one defines a class that is only known from its enclosing class. Sometimes one is better, sometimes the other.
Answer: Both approaches are valid. Which one to use depends of your usage:

If you implement an interface inside another class, you will have access to protected and private methods of the parent class.
If you want to keep things separated and reuse the same implementation for this interface, creating a separate class is the way to go.


Java a moving animation (sprite)

Question: Hello i`ve got a problem: when i run this code i get this:

on some java forum they said i need to add Graphics2DObject.clearRect(x1, y1, x2, y2);
(where`s x1 and y1 is coordinates of the image and x2 y2 is width height of the image.) when i add it to the code i get this:

The code(with added function):
Main:
import java.awt.*;
import javax.swing.*;
public class Main {
    public static void main(String []args){
        Main b = new Main();
        b.run();
    }
    private Sprite sprite;
    private Animation a;
    private ScreenManager s;
    public double sk = 0;

    private static final DisplayMode modes1[] = {
        new DisplayMode(800, 600, 32, DisplayMode.REFRESH_RATE_UNKNOWN),
    };

    //load images and add scenes
    public void loadImages() {
        Image face1 = new ImageIcon("C:\\1.jpg").getImage();
        Image face2 = new ImageIcon("C:\\2.jpg").getImage();

        a = new Animation();
        a.addScene(face1, 50);
        a.addScene(face2, 50);

        sprite = new Sprite(a);
        sprite.setVelocityX(0.3f);
        sprite.setVelocityY(0.3f);

    }

    //main method called from main
    public void run() {
        s = new ScreenManager();
        try {
            DisplayMode dm = s.findFirstCompatibleMode(modes1);
            s.setFullScreen(dm);
            loadImages();
            movieLoop();
        }finally {
            s.restoreScreen();
        }
    }

    //play movie
    public void movieLoop() {
        long startingTime = System.currentTimeMillis();
        long cumTime = startingTime;

        while(cumTime - startingTime < 5000) {
            long timePassed = System.currentTimeMillis() - cumTime;
            cumTime += timePassed;
            update(timePassed);

            //draw and update the screen
            Graphics2D g = s.getGraphics();
            draw(g);
            g.dispose();
            s.update();

            try{
                Thread.sleep(20);
            }catch(Exception ex) {
                System.err.println("Error: " + ex);
            }
        }
    }

    // Graphics with new function
    public void draw(Graphics g) {
        g.drawImage(sprite.getImage(), Math.round(sprite.getX()), Math.round(sprite.getY()), null);
        if(sk != 1){
       g.clearRect(Math.round(sprite.getoX()),Math.round(sprite.getoY()),Math.round(sprite.getWidth()),Math.round(sprite.getHeight()));
        }else{
          sk = 1;
       }

    }

    //update sprite
    public void update(long timePassed) {
        if(sprite.getX() < 0) {
            sprite.setVelocityX(Math.abs(sprite.getVelocityX()));
        } else if (sprite.getX() + sprite.getWidth() >= s.getWidth()) {
            sprite.setVelocityX(-Math.abs(sprite.getVelocityX()));
        }

        if(sprite.getY() < 0) {
            sprite.setVelocityY(Math.abs(sprite.getVelocityY()));
        } else if (sprite.getY() + sprite.getHeight() >= s.getHeight()) {
            sprite.setVelocityY(-Math.abs(sprite.getVelocityY()));
        }

        sprite.oldX();
        sprite.oldY();
        sprite.update(timePassed);
    }

}

The sprite (movement class):
import java.awt.Image;

public class Sprite {

    private Animation a;
    private float x;
    private float y;
    private float vx;
    private float vy;
    private float ox;
    private float oy;

    //Constructor
    public Sprite(Animation a) {
        this.a = a;
    }

    // Get old x and y to delete them later

    public void oldX(){
       this.ox = x;
    }

    public void oldY(){
       this.oy = y;
    }

    public float getoX(){
       return ox;
    }
    public float getoY(){
       return oy;
    }

    //Change position
    public void update(long timePassed) {
        x += vx * timePassed;
        y += vy * timePassed;
        a.update(timePassed);
    }

    //get x position
    public float getX() {
        return x;
    }

    //get y position
    public float getY() {
        return y;
    }

    //set x position
    public void setX(float x) {
        this.x = x;
    }

    //set y position
    public void setY(float y) {
        this.y = y;
    }

    // get sprite width
    public int getWidth() {
        return a.getImage().getWidth(null);
    }

    // get sprite height
    public int getHeight() {
        return a.getImage().getHeight(null);
    }

    //get horizontal velocity
    public float getVelocityX() {
        return vx;
    }

    //get vertical velocity
    public float getVelocityY() {
        return vy;
    }

    //set horizontal velocity
    public void setVelocityX(float vx) {
        this.vx = vx;
    }

    //set vertical velocity
    public void setVelocityY(float vy) {
        this.vy = vy;
    }

    //get sprite/image
    public Image getImage() {
        return a.getImage();
    }
}

Screen manager class:
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.BufferStrategy;
import javax.swing.JFrame;

public class ScreenManager {

    private GraphicsDevice vc;

    //Constructor // give vc access to monitor screen
    public ScreenManager() {
        GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment();
        vc = e.getDefaultScreenDevice();
    }

    //get all compatible DM's
    public DisplayMode[] getCompatibleDisplayModes() {
        return vc.getDisplayModes();
    }

    //compares DM passed in to vc and see if they match
    public DisplayMode findFirstCompatibleMode(DisplayMode modes[]) {
        DisplayMode goodModes[] = vc.getDisplayModes();

        for(int x = 0; x <modes.length; x++){
            for(int y = 0; y < goodModes.length; y++){
                if(displayModesMatch(modes[x], goodModes[y])) {
                    return modes[x];
                }
            }
        }
        return null;
    }

    //get current DM
    public DisplayMode getCurrentDisplayMode() {
        return vc.getDisplayMode();
    }

    //checks if two modes match each other
    public boolean displayModesMatch(DisplayMode m1, DisplayMode m2) {
        if(m1.getWidth() != m2.getWidth() || m1.getHeight() != m2.getHeight()) {
            return false;
        }

        if(m1.getBitDepth() != DisplayMode.BIT_DEPTH_MULTI && m2.getBitDepth() != DisplayMode.BIT_DEPTH_MULTI && m1.getBitDepth() != m2.getBitDepth()) {
            return false;
        }

        if(m1.getRefreshRate() != DisplayMode.REFRESH_RATE_UNKNOWN && m2.getRefreshRate() != DisplayMode.REFRESH_RATE_UNKNOWN && m1.getRefreshRate() != m2.getRefreshRate()) {
            return false;
        }

        return true;
    }

    //make frame full screen
    public void setFullScreen(DisplayMode dm) {
        JFrame f = new JFrame();
        f.setUndecorated(true);
        f.setIgnoreRepaint(true);
        f.setResizable(false);
        vc.setFullScreenWindow(f);

        if(dm != null && vc.isDisplayChangeSupported()) {
            try{
                vc.setDisplayMode(dm);
            }catch(Exception e) {System.out.println("");}
        }
        f.createBufferStrategy(2);

    }

    //we will set Graphics object = to this
    public Graphics2D getGraphics() {
        Window w = vc.getFullScreenWindow();
        if(w != null) {
            BufferStrategy s = w.getBufferStrategy();
            return (Graphics2D)s.getDrawGraphics();
        }
        else {
            return null;
        }
    }

    //updates display
    public void update() {
        Window w = vc.getFullScreenWindow();
        if(w != null) {
            BufferStrategy s = w.getBufferStrategy();
            if(!s.contentsLost()) {
                s.show();
            }
        }
    }

    //returns full screen window
    public Window getFullScreenWindow() {
        return vc.getFullScreenWindow();
    }

    //get width
    public int getWidth() {
        Window w = vc.getFullScreenWindow();
        if(w != null) {
            return w.getWidth();
        }
        else {
            return 0;
        }
    }

    //get height
    public int getHeight() {
        Window w = vc.getFullScreenWindow();
        if(w != null) {
            return w.getHeight();
        }
        else {
            return 0;
        }
    }

    //get out of full screen
    public void restoreScreen(){
        Window w = vc.getFullScreenWindow();
        if(w != null) {
            w.dispose();
            vc.setFullScreenWindow(null);
        }
    }

    //create image compatible with monitor
    public BufferedImage createCompatibleImage(int w, int h, int t) {
        Window win = vc.getFullScreenWindow();
        if(win != null) {
            GraphicsConfiguration gc = win.getGraphicsConfiguration();
            return gc.createCompatibleImage(w, h, t);
        }
        return null;
    }

}/////////END///////////

Animation class
import java.util.ArrayList;
import java.awt.Image;

public class Animation {

    private ArrayList scenes;
    private int sceneIndex;
    private long movieTime;
    private long totalTime;

    //Constructor
    public Animation() {
        scenes = new ArrayList();
        totalTime = 0;
        start();
    }

    //add scenes to the array list and set time for each scene
    public synchronized void addScene(Image i, long t) {
        totalTime += t;
        scenes.add(new Onescene(i, totalTime));
    }

    //start animation from beginning
    public synchronized void start() {
        movieTime = 0;
        sceneIndex = 0;
    }

    //change scenes
    public synchronized void update(long timePassed) {

        if(scenes.size() > 1 ) {
            movieTime += timePassed;

            if(movieTime >= totalTime) {
                movieTime = 0;
                sceneIndex = 0;
            }
            while(movieTime > getScene(sceneIndex).endTime) {
                sceneIndex++;
            }
        }
    }

    //get animations current scene
    public synchronized Image getImage() {

        if(scenes.size() == 0) {
            return null;
        }

        else {
            return getScene(sceneIndex).pic;
        }
    }

    //get scene
    private Onescene getScene(int x) {
        return (Onescene)scenes.get(x);
    }

    /////PRIVAT INNER CLASS/////
    private class Onescene{
        Image pic;
        long endTime;

        public Onescene(Image pic, long endTime) {
            this.pic = pic;
            this.endTime = endTime;
        }
    }

}////END/////

EDIT:
Could someone try running this code ?
Maybe You'll find the mistakes I made...
Answer: clearRect goes before drawImage.
Comment: Maybe try changing your methods.
1. Call cover() method on all sprites (this will clearRect in current position)
2. Update sprite positions
3. Draw (current position)
Comment: Instead of "if(sk != 1)" it should be "if(sk==1)"
Comment: Nope, the problem is still like in picture 1.
Comment: how to use it correctly? cover(g)? and write it in movieLoop() or in Main.class update method?
Answer: I also had a problem with this and you need a "do while loop" in stead of while loop
like this:
do{
        Graphics2D g = s.getGraphics();
        long timePassed = System.currentTimeMillis() - cumTime;
        cumTime += timePassed;
        update(timePassed);

        //draw and update
        draw(g);
        g.dispose();
        s.update();

        try{
            Thread.sleep(20);
        }catch(Exception ex){
            System.out.println("Can't sleep :(");
        }
    }
    while(cumTime - startingTime < 20000); //the Time

And the clearRect must be ABOVE the drawImage
Answer: Your loop looks a bit incorrect
       Graphics2D g = s.getGraphics();
      while(cumTime - startingTime < 5000) {
        long timePassed = System.currentTimeMillis() - cumTime;
        cumTime += timePassed;
        update(timePassed);

        //draw and update the screen
        draw(g);
        g.dispose();
        s.update();

        try{
            Thread.sleep(20);
        }catch(Exception ex) {
            System.err.println("Error: " + ex);
        }
    }
}

also try this for your draw method.
// Graphics with new function
public void draw(Graphics g) {
    g.clearRect(0,0,800,600);
    g.drawImage(sprite.getImage(), Math.round(sprite.getX()), Math.round(sprite.getY()), null);
}

Comment: Avoid clearing the entire screen if possible, its acceptable if you have a couple sprites (or a complicated environment), but it makes me sad.
Comment: Ah yes, ClickerMonkey is correct. I was under the impression the OP was going to render something complicated.

Java a moving animation (sprite)


If I change a router's subnet mask to one that includes the old one, will the hosts with the old configuration still work?

Question: Currently I have a router that is addressed as 10.2.1.1 on a 10.2.1.0/24 network. All of my hosts have default gateway 10.2.1.1 with mask 255.255.255.0.
I want to know: if I change my router to 10.2.0.0/16 will the hosts that have subnet mask corresponding to /24 still work in the interim (before I reconfigure)?
EDIT: If it is not possible, what is the best way to transition from a smaller subnet to a larger subnet, assuming these are all Windows hosts behind a pfSense device?
EDIT 1: For clarification, I will keep the router address as 10.2.1.1, just make the subnet bigger (/16 instead of /24).
Comment: "change my router to 10.2.0.0/16" needs little clarification. Did you mean to keep IP address 10.2.1.1 on your router and just change subnet mask to 255.255.0.0? If that is the case, hosts with /24 should work in the interim (unless your network has more to it than you have shared with us)
Comment: See this similar question asking about a similar change.  http://serverfault.com/questions/360528/changing-netmask-from-24-to-16-on-a-windows-2003-domain
Answer: It would work somewhat.  It depends on how you define work.  If you change the netmask on you router, so that instead of having 10.2.1.1/24 it will have 10.2.1.1/16 then:
A host with a 10.2.1.0/24 address could still reach any system with an address between 10.2.1.0-10.2.1.255 with a mask of /24 or /16.   The systems would simply use arp resolution and connect directly to the each other.  Since from the perspective of both systems they will each be on their local network.
A host with a 10.2.1.0/24 would be able to connect to any host outside of the 10.2.0.0/16 network.  It would ARP for the gateway address and connect through the via your router.
The only thing they couldn't reach is hosts on 10.2.0.0/16, but not in the 10.2.1.0/24 range.  The host with an address in 10.2.1.0/24 would try to connect via the router, but a host on that subnet, but outside of 10.2.1.0/24 would try to connect directly.  Even this can be mitigated, on some routers using something called proxy-arp.  You basically have to convince the router to reply to ARP requests on behalf of a system with a 10.2.1.0/24 when the request came from a system not within that subnet.
The key point here is that will work somewhat, but you must fix the netmask on all your systems fixed to the new subnet before you start assigning address space from the other portion of the network.
Answer: There are a few potential issues.

Hosts with the narrower netmask will send packets to the router that they should have sent directly to another host. Depending on the router and it's configuration it may or may not forward the packets back out over the same interface they came in.
The broadcast address will be different. This may screw up some stuff that relies on "Lan discovery" techniques.
Hosts with the narrower subnet mask may ignore arp requests from "out of subnet" requesters. This may lead to failure to deliver packets from hosts with the wider mask to hosts with the narrower mask.

Whether these potential issues become actual issues depends very much on your environment. The only way to know for sure is to test.


Is this what is meant by quadratic equation , function?

Question: It says in my textbook that :

Let $f(x) - g(x) = 0$. Then, let this equation be $h(x)$.
If $h(x)$ is a quadratic Q.F, then $h(x) = 0$ is a quadratic equation.

I need to ask some questions regarding this statement i.e.
$1)$ When I say $f(x)-g(x) = 0$. So, is this statement an equation? And $f(x) - g(x)$ is a function until there is no equal to sign?
$2)$ Why did we equate  $f(x)-g(x)$  to $h(x)$ and then call $h(x)$ as a quadratic function?
$3)$ When I say $h(x) = 0$ is a quadratic equation, there is still a function ${ h(x) }$ which we wrote. Shouldn't we write the value of $h(x)$ (Let it be for example $2x^2 +x+4$) and then call it a quadratic equation?
Answer: That is a strange phrasing to me.
I would say let $f(x)-g(x)$ be $h(x)$. If $h(x)$ is a quadratic function, then $h(x)=0$ is a quadratic equation.

Yes, it is an equation.  $f(x)-g(x)$ is a function of $x$.

We don't just call it a quadratic function, we have to verify that.

When we mention quadratic equation, we should see the equal sign somewhere.
Comment: So , there is no significance of writing f(x) - g(x) = h(x) and then call it a Q.F . You see , what I mean is that it is not Sth universal right.
Comment: Also , why didn't you write h(x) = 0 but wrote q(x) = 0?
Comment: I typed wrongly, I meant to type $h(x)=0$.
Comment: 1st comment ? . . .
Comment: For example, for $f(x)=x^3+x^2$ and $g(x)=x^3$, then $h(x)=f(x)-g(x)$ is a quadratic function. I don't think it is significant.
Comment: Ohk. Thanks a lot for helping me out.Hope you have a great day.
Answer: $1)$ $f(x)-g(x)=0$ is an equation. $ f(x)-g(x)$ is a function.
$2)$ $h(x)$ being equal to an equation makes no sense. If your book says instead that $h(x) =f(x)-g(x)$, then $h(x)$ is really no quadratic function. It is the zero function. The degree of a quadratic is $2$, whereas the degree of the zero function is undefined. I believe this answers $(3)$ as well.


Probability of more than one, but no more than three?

Question: I am having trouble wrapping my head around the following problem... Hope someone can enlighten me.
On the motherboard of a device there are 20 different processors of which 5 of them are faulty. We know that there is 1 or more faults on the motherboard. In an attempt to find the error, we select 4 random processors for testing.
What is the probability that more than 1 of the processors is faulty, but no more than 3?
Solution tldr: Given the suggestion per BruceET, using the hypergeometric probability distribution, I figured the probability as follows.
$\frac{\binom 5 2 \binom {15}2}{\binom {20}4} + \frac{\binom 53 \binom {15}1}{\binom {20}4} = 0.2477\ \ \ $which checks with the problem's reference values.
Comment: Also, don't get discouraged by the downvote. I downvoted the question and voted to close it because at the moment, it is not up to site standards (you have shown no work you did on your own). If you edit your question so that you show what you tried and how far you got, I will not only remove the downvote, I will add an upvote.
Comment: Hi and welcome to the site! Since this is a site that encourages and helps with learning, it is best if you show your own ideas and efforts in solving the question. Can you edit your question to add your thoughts and ideas about it?
Comment: @5xum I see. Mainly I was looking for suggestions and interpretations to the question and generally how to proceed, not necessarily solutions. Should I avoid this type of question in the future?
Comment: What's an "error"? Does it refer to a faulty processor? I'm confused because you explicitly wrote that "there are 1 or more errors on the motherboard". But that's redundant since it's mentioned that 5 processors are faulty.
Comment: Error and faulty should be the same. Edited the question now
Comment: The question is asking for the probability that exactly two or exactly three of the four randomly selected processors are faulty given that five of the twenty processors are faulty.
Comment: @N.F.Taussig But which one, or is it the sum of both?
Answer: I think sampling of processors is without replacement, so this would be
a hypergeometric distribution instead of a binomial. Thus one of the two
terms is as follows:
$$P(X = 2) = \frac{{5 \choose 2}{15 \choose 2}}{{20 \choose 4}}.$$
In R statistical software, the answer (total of two terms as in the
comment of @N.F.Taussig) is computed as:
<code>sum(dhyper(2:3,  5, 15,  4))
## 0.247678
</code>


Cython compilation error with simple inheritance - object has no attribute

Question: I am trying to wrap a simple C++ class that uses shared pointers and a very simple inheritance. I have a class Point that is a base class and SphericalPoint is it's child class. I have a vector of shared pointers of Points. I want the vector to hold the child class objects in it i.e. Spherical Points. There can be many child classes of Point and Spherical Point is only shown here for representation. When I do this I get the following compilation error -
 point.pyx:18:13: Object of type 'shared_ptr[Point]' has no attribute 'setCoordinate1'

Error compiling Cython file:

    point = shared_ptr[Point](new SphericalPoint())
    cdef double latitude, longitude
    latitude = 0.
    longitude = 0.
    point.setCoordinate1(latitude)
    point.setCoordinate2(longitude)

  point.pyx:19:13: Object of type 'shared_ptr[Point]' has no attribute 'setCoordinate2'

Initially when googling for this I thought the cause of the problem maybe because I do not have the keyword public in the Cython code but when I do add the keyword public I get a whole bunch of other errors. In the following link Wrapping C++ with Cython there is no example that shows public in the .pxd file.
Here is a MVCE that reproduces the problem. How can I fix this error ? Cython version is 0.29.7
Point.h
class Point {
   private:
     double coordinate1,coordinate2;
   public:
     virtual double  getCoordinate1();
     virtual double  getCoordinate2();
     virtual void    setCoordinate1(double coordinate1);
     virtual void    setCoordinate2(double coordinate2);
   };

class SphericalPoint : public Point
   {
     private:
         double longitude,latitude;
     public:
         double getCoordinate1();
         double getCoordinate2();
         void   setCoordinate1(double latitude);
         void   setCoordinate2(double longitude);
    };

and this is my point.pxd file
cdef extern from "Point.h":
    cdef cppclass Point:
       Point() except +
       double getCoordinate1()
       double getCoordinate2()
       void setCoordinate1(double coordinate1)
       void setCoordinate2(double coordinate2)

   cdef cppclass SphericalPoint(Point):
      SphericalPoint() except +
      double getCoordinate1()
      double getCoordinate2()
      void setCoordinate1(double coordinate1)
      void setCoordinate2(double coordinate2)

And my point.pyx file
 from libcpp.memory cimport shared_ptr
 from libcpp.vector cimport vector

 from point cimport Point

 cdef class PyA:

     cdef vector[shared_ptr[Point]]* points

     def __cinit__(self):
        self.points = new vector[shared_ptr[Point]]()

     def buildPoints(self):

        cdef shared_ptr[Point] point
        point = shared_ptr[Point](new SphericalPoint())
        cdef double latitude, longitude
        point.setCoordinate1(latitude)
        point.setCoordinate2(longitude)

UPDATE
I just moved the instantiation of the child classes to it's own separate method because it is not really part of cinit. But I still get the same compilation errors. I am also wondering whether the instantiation of the subclass SphericalPoint is the cause of the problem i.e.
  point = shared_ptr[Point](new SphericalPoint())

Is this the recommended way ?
Answer: Cython can work this out for regular pointer types and generate c++ code with ->, however it isn't able to work this out for types that implement a pointer interface with operator overloading.
Instead you should use cython.operator.dereference.
from cython.operator cimport dereference

# ...

dereference(point).setCoordinate1(instance)

Comment: Thank you that works !! I had one other question in this context . Is the new operator the recommended way to instantiate new objects in Cython? Generally in C++ (most SO answers recommend this) not to use new. Any comments ?
Comment: In Cython you often can't initialise things on the stack because they're default allocated at the start of the function (to get Python scoping rules). In this case `new` is often the best solution.
Comment: Excellent thanks. A privilege to learn from you. Upvoted and accepted.


400 Bad Request in python web browser

Question: I'm new in Python and I'm trying to open a .txt file from a website.
My code is :
import socket
mysocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysocket.connect(('data.pr4e.org', 80))
cmd = 'GET http://data.pr4e.org/romeo.txt HTTP/1.0\n\n'.encode()
mysocket.send(cmd)

while True:
    data = mysocket.recv(512)
    if (len(data)<1):
        break
    print(data.decode())
mysocket.close()

and I get the message :
Bad Request-Your browser sent a request that this server could not understand.
I can read the .txt file with urllib but I didn't get why it doesn't work in this way.
Comment: Welcome to SO! The URI (the part of the HTTP command following "GET") should be relative to the server. If you change `cmd` to `'GET /romeo.txt HTTP/1.0\n\n'` you should find your code works. Please don't be concerned if this question gets closed - that simply indicate that answers are unlikely to add anything of value to the site content.
Comment: Does this answer your question? [Getting a 400 Bad Request Error Using Socket in Python 3](https://stackoverflow.com/questions/44773601/getting-a-400-bad-request-error-using-socket-in-python-3)
Comment: Thanks, but I get still the same error
Comment: cmd = 'GET http://data.pr4e.org/romeo.txt HTTP/1.0\r\n\r\n'.encode()   Try \r\n \r\n instead of \n\n  The request/status line and headers must all end with  (that is, a carriage return followed by a line feed).
Comment: see also here https://stackoverflow.com/questions/44773601/getting-a-400-bad-request-error-using-socket-in-python-3?rq=1
Answer: Can you just use requests?
# python -m pip install —user requests
import requests
r = requests.get('http://data.pr4e.org/romeo.txt')

print(r.text)

Or
from urllib import request

r = request.urlopen('http://data.pr4e.org/romeo.txt')
text = b''
for line in r:
    text+=line
print(text)

Finally a working socket
import socket

uri = 'data.pr4e.org'
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.connect((uri, 80))
    cmd = f'GET /romeo.txt HTTP/1.0\r\nHost: {uri}\r\n\r\n'.encode()
    s.send(cmd)

    while True:
        data = s.recv(512)
        if (len(data)<1):
            break
        print(data.decode())

Comment: Yes, I can do it with also urllib, I just want to know where the problem is because it is an example from a python course
Comment: Oh, let me try using sockets
Comment: I added a socket example just for completeness
Answer: The problem is with \n\n in your request.
"The request/status line and headers must all end with CR LF (that is, a carriage return followed by a line feed)."
You need to use \r\n
Change your line to this:
cmd = 'GET data.pr4e.org/romeo.txt HTTP/1.0\r\n\r\n'.encode()

Same answer here:
Getting a 400 Bad Request Error Using Socket in Python 3

400 Bad Request in python web browser


Limit of integral in $\mathbb R^2$

Question: I am trying to prove the following but even if it seems easy I am not sure how to start:
Let $R$ be a rectangle in the plane and $f\colon R\rightarrow {\mathbb{R}}$ a continuous non-negative function. Then the following holds:
$$\left(\iint_R f^n\right)^{\dfrac{1}{n}} \rightarrow \sup  \left(f(x)\right)\text{ as }n\longrightarrow \infty.$$
Any hints will help. Thank you
Answer: Can you prove that the sequence $n\to (\int_{R} f^n)^{\frac{1}{n}}$ is bounded by $\sup_{x\in R} f(x)$ for all natural numbers $\mathbb{N}$?
The other direction is to show that for each $\epsilon > 0$, there exists $N$ sufficiently large such that $(\int_{R} f^n)^{\frac{1}{n}} > \sup_{x\in R} f(x) - \epsilon$ for all $n\geq N$.
Hint: Define $A_{\epsilon}=\{x\in R:f(x)>\sup_{x\in R} f(x) - \epsilon\}$. What can you say about $(\int_{A_{\epsilon}} f^n)^{\frac{1}{n}}$ for sufficiently large $n$?
Hope this helps!
Comment: The second part is unclear how to prove.
Comment: Dear @WhatsMyName (it is funny to address you this way!), I have added a hint. Does that help? I would be very happy to elaborate further if you are still stuck after thinking about the hint.
Comment: But if f has values less than 1 can we conclude the second part? Also since f is continuous I guess the sup f(x)= Max?
Comment: Dear @WhatsMyName, yes the key point (as you may see if you follow my hint) is that for any positive number $c$ (whether less than $1$ or not), $\lim_{n\to\infty} c^\frac{1}{n}=1$. I believe this limit value is the main reason the result is true. Also, if the rectangle $R$ is a closed (hence, compact) rectangle, then $\sup_{x\in R} f(x)=\max_{x\in R} f(x)$; this would not necessarily be true if $R$ were an open rectangle. (However, the result is independent of whether or not $R$ is an open or closed rectangle and is also, in fact, independent of $R$ being a rectangle - $R$ could be anything.)
Comment: Now it is clear indeed. thank you
Comment: @WhatsMyName Great! So, you know how to prove the result in full generality via the hint?
Comment: yes, I was a bit confused with the fact that we are in R^2 but I see that this won't affect much.

Limit of integral in $\mathbb R^2$


Angular UI-Router: Multiple URLs to single state

Question: I have started using angular's ui-router, and I am trying to figure out how to have multiple URLS refer to a single state. For example:
/orgs/12354/overview
//retyrns the same pages as
/org/overview

My $state provider is currently set with something like this, and its unclear to my how to slip in the alias '/org/overview' route such that it properly inherits from the 'org' parent.
.state('org', {
  abstract: true,
  url: '/orgs/:orgID',
  templateUrl: '/client/navigation/main.html'
})
.state('org.overview', {
  url: '/overview',
  templateUrl: '/client/overview/overview.html',
  controller: 'OverviewCtrl'

})

Answer: This can be achieved using when(). Suppose this is the state you want to point to with multiple urls.
.state('app.home',
  {
    url: '/home',
    templateUrl: 'home.html',
    controller: 'homeCtrl'
  })

In config() you can use when() as follows:
angular.module('myApp', [])
   .config($urlRouterProvider){
       $urlRouterProvider.when(/homepage, ['$state','$match', function ($state, $match) {
          $state.go('app.home');
 }]);
}

Likewise you can add multiple urls pointing to same state.
Comment: This solution won't work if you want to have a URL like /orderOverview of a state 'orderOverview' and because of a different context you want to have another URL like /orderHistory which should point to the same state 'orderOverview' BUT keep the entered/used URL in your address bar.
Comment: Your solution would cause a changed URL.
Answer: I think you only need to define substates without an url like below.
.state('org', {
  abstract: true,
  url: '/orgs/:orgID',
  templateUrl: '/client/navigation/main.html'
})
.state('org.1', {
  templateUrl: '/client/overview/one.html',
  controller: 'OverviewCtrl'
})
.state('org.2', {
  templateUrl: '/client/overview/two.html',
  controller: 'OverviewCtrl'
})
.state('org.3', {
  templateUrl: '/client/overview/three.html',
  controller: 'OverviewCtrl'
})

Comment: how would this know that "/overview" was a valid route, since its not part of the /orgs path?
Comment: I haven't tested this, but you should be able to put the controller in the abstract state, because it's the same across all of the children, right?
Answer: Firstly, an abstract state doesn't return a view.
Also, since you're trying to use the plural orgs for the list view, and the singular org for the item view, you can't use appended routes, which is the default behavior.
.state('org', {
  url: '/orgs',
  templateUrl: '/client/navigation/main.html'
})
.state('org.overview', {
  url: '^/org/:orgID/overview'
  templateUrl: '/client/overview/overview.html',
  controller: 'OverviewCtrl'
})


Table not rendered using ajax_render in ctools modal window

Question: This is a continuation from this question,where I'm wanting to display a form for searching Apache Solr and displaying the results with a pager. I've modified my approach to have the search run from the page function if there are values in the form. As I have it now, the search is run and results are returned just fine, but for some reason I can't get the table to render when I pass a render array through ajax_render().  Here's the relevant code:
/**
 * Page callback for imgsearch modal popup window.
 */
function imgsearch_page($ajax, $id, $a, $b) {
  if ($ajax) {
    //Load the modal library and add the modal javascript.
    ctools_include('ajax');
    ctools_include('modal');

    $form_state = array(
      'ajax' => TRUE,
      'title' => t('Image Search Form'),
      'next_field_id' => $id,
    );

    // Use ctools to generate ajax instructions for the browser to create
    // a form in a modal popup.
    $search_form = ctools_modal_form_wrapper('imgsearch_form', $form_state);
    if ($search_form[0]) {
      $output = $search_form;
    }
    else {
      $build['search_form'] = $search_form;
    }
    // If the form has been submitted, there may be additional instructions
    // such as dismissing the modal popup.
    if (!empty($form_state['ajax_commands'])) {
      $output = $form_state['ajax_commands'];
    }

    if($form_state['values']['search_terms'] != '') {
      // See apachesolr_saved_searches_get_results() in ozmosys project for code to run solr search.
      $results = nb_image_search_search($form_state['values']);

      if (is_array($results['images']) && count($results['images'] > 0)) {
        $next_field_id = $form_state['next_field_id'];
        // Create object to store file and target field info. To be stored in ctools cache.
        $file_info = new stdClass();
        // Generate the field name.  field_images is a multivalue field collection, so we just need the next available option
        // in the $field_images['und'] array. The second number (for field_image) will always be 0 since it
        // is a single value field.
        $file_info->fieldname['url'] = '#edit-field-images-und-' . $next_field_id . '-field-image-und-0-imgsearch-file-url';
        $file_info->fieldname['person'] = '#edit-field-images-und-' . $next_field_id . '-field-person-und-0-value';
        $file_info->fieldname['organization'] = '#edit-field-images-und-' . $next_field_id . '-field-organization-und-0-value';
        $file_info->fieldname['year'] = '#edit-field-images-und-' . $next_field_id . '-field-year-und-0-value';

        $file_info->fids = array();

        // Theme the results as a table.
        $header = array(t('Image'), t('File Name'), t('Add to field'));
        $rows = array();
        foreach ($results['images'] as $image) {
          // Create image style derivative for each image.
          $imagestyle = array(
            'style_name' => 'thumbnail',
            'path' => $image['filepath'] . $image['filename'],
            'width' => '',
            'height' => '',
            'alt' => '',
            'title' => $image['filename'],
          );
          $styled_image = theme('image_style', $imagestyle);
          $fid = $image['fid'];

          $rows[] = array(
            'image' => $styled_image,
            'name' => $image['filename'],
            'add' => ctools_ajax_text_button("select", "imgsearch/nojs/imgadd/" . $fid . '/' . $next_field_id, t('Select')),
          );

          $file_info->fids[$fid] = $image['filename'];

          // Cache values for Person, Organization, and Year if they exist.
          foreach (array('person', 'organization', 'year') as $field) {
            if (isset($image[$field])) {
              $file_info->meta[$fid][$field] = $image[$field];
            }
          }
        }
        //Cache image name in ctools object cache so it can be used later in nb_image_search_image_add()
        ctools_include('object-cache');
        ctools_object_cache_set('imgsearch', 'imgsearch_' . $next_field_id, $file_info);

        // Create a render array ($build) which will be themed as a table with a
        // pager.
        $build['imgsearch_table'] = array(
          '#theme' => 'table',
          '#header' => $header,
          '#rows' => $rows,
          '#empty' => t('There were no matching results found'),
        );

        // Attach the pager theme.
      /*pager_default_initialize($results['total_found'], $results['rows']);
        $build['imgsearch_pager'] = array('#theme' => 'pager'); */

      }
      else {
        $build['no_results'] = array(
          'markup' => '
No images found
',
        );
      }
    }

    if (!$output) {
      $output = $build;
    }

    // Return the ajax instructions to the browser via ajax_render().
    print ajax_render($output);
    drupal_exit();
  }
  else {
    return drupal_get_form('imgsearch_form', $id);
  }
}

What happens is that if the search has been run, the search form is in $build as the $form array, and the second array in $build is imgsearch_table, which is a render array with #theme, #rows, and #header. However, I can't get the table to be rendered or displayed anywhere. I've been banging my head on this for way too long. What do I have to do to get my table to be rendered in my modal window, along with the form?
Answer: I finally got the table to render fine every time. Updated code:
function imgsearch_page($ajax, $id, $a, $b) {
  if ($ajax) {
    //Load the modal library and add the modal javascript.
    ctools_include('ajax');
    ctools_include('modal');

    $form_state = array(
      'ajax' => TRUE,
      'title' => t('Image Search Form'),
      'next_field_id' => $id,
    );

    // Use ctools to generate ajax instructions for the browser to create
    // a form in a modal popup.
    $search_form = ctools_modal_form_wrapper('imgsearch_form', $form_state);

    if (($form_state['executed'] && $form_state['ajax']) || isset($_GET['page'])) {
      // If the form has been submitted, there may be additional instructions
      // such as dismissing the modal popup.
      if (!empty($form_state['ajax_commands'])) {
        $output = $form_state['ajax_commands'];
      }

      if ($form_state['values']['search_terms'] != '' || isset($_GET['search_terms'])) {
        $page_num = isset($_GET['page']) ? $_GET['page'] : 0;
        // See apachesolr_saved_searches_get_results() in ozmosys project for code to run solr search.
        if ($_GET['search_terms']) {
          $form_state['values']['search_terms'] = $_GET['search_terms'];
        }
        $results = nb_image_search_search($form_state['values'], $page_num);

        if (is_array($results['images']) && count($results['images'] > 0)) {
          $next_field_id = $form_state['next_field_id'];
          // Create object to store file and target field info. To be stored in ctools cache.
          $file_info = new stdClass();
          // Generate the field name.  field_images is a multivalue field collection, so we just need the next available option
          // in the $field_images['und'] array. The second number (for field_image) will always be 0 since it
          // is a single value field.
          $file_info->fieldname['url'] = '#edit-field-images-und-' . $next_field_id . '-field-image-und-0-imgsearch-file-url';
          $file_info->fieldname['person'] = '#edit-field-images-und-' . $next_field_id . '-field-person-und-0-value';
          $file_info->fieldname['organization'] = '#edit-field-images-und-' . $next_field_id . '-field-organization-und-0-value';
          $file_info->fieldname['year'] = '#edit-field-images-und-' . $next_field_id . '-field-year-und-0-value';

          $file_info->fids = array();

          // Theme the results as a table.
          $header = array(t('Image'), t('File Name'), t('Add to field'));
          $rows = array();
          foreach ($results['images'] as $image) {
            // Create image style derivative for each image.
            $imagestyle = array(
              'style_name' => 'thumbnail',
              'path' => $image['filepath'] . $image['filename'],
              'width' => '',
              'height' => '',
              'alt' => '',
              'title' => $image['filename'],
            );
            $styled_image = theme('image_style', $imagestyle);
            $fid = $image['fid'];

            $rows[] = array(
              'image' => $styled_image,
              'name' => $image['filename'],
              'add' => ctools_ajax_text_button("select", "imgsearch/nojs/imgadd/" . $fid . '/' . $next_field_id, t('Select')),
            );

            $file_info->fids[$fid] = $image['filename'];

            // Cache values for Person, Organization, and Year if they exist.
            foreach (array('person', 'organization', 'year') as $field) {
              if (isset($image[$field])) {
                $file_info->meta[$fid][$field] = $image[$field];
              }
            }
          }
          //Cache image name in ctools object cache so it can be used later in nb_image_search_image_add()
          ctools_include('object-cache');
          ctools_object_cache_set('imgsearch', 'imgsearch_' . $next_field_id, $file_info);

          // Create a render array ($build) which will be themed as a table with a
          // pager.
          $build['search_form'] = isset($search_form[0]) ? drupal_build_form('imgsearch_form', $form_state) : $search_form;
          $build['imgsearch_table'] = array(
            '#theme' => 'table',
            '#header' => $header,
            '#rows' => $rows,
            '#empty' => t('There were no matching results found'),
          );

          // Attach the pager theme.
          $pager = pager_default_initialize($results['total_found'], $results['rows']);
          $build['imgsearch_pager'] = array(
            '#theme' => 'pager',
            '#parameters' => array(
              'search_terms' => $form_state['values']['search_terms'],
              //TODO: add params for Person, Organization, and Year.
              ),
          );

          $form_state['values']['title'] = t('Search Results');
          $output = ctools_modal_form_render($form_state['values'], $build);

          print ajax_render($output);
          drupal_exit();
        }
        else {
          $build['no_results'] = array(
            'markup' => '
No images found
',
          );
        }
      }
    }
    elseif (!isset($output)) {
      $output = ctools_modal_form_wrapper('imgsearch_form', $form_state);
      // Return the ajax instructions to the browser via ajax_render().
      print ajax_render($output);
      drupal_exit();
    }
  }
  else {
    return drupal_get_form('imgsearch_form', $id);
  }
}

To be honest, I didn't really change anything in regards to the table generation, so I'm suspecting another change I made fixed it.


What is this weird "e" time signature?

Question: I'm looking at a piano arrangement of Right Behind You by Mike Morasky.
The time signature looks like a weird "e", what does this mean?
Comment: What do you mean when you say "E time signature"? The time signature is normal. It is "C" which is the same thing as 4/4.  The phrase "Weapon reskins" doesn't make any sense in relation to time signature. Conclusion: You need to elaborate so one can understand the question.
Comment: Why are people downvoting this. It does look like an e to a large extent, it's a valid question. With text-based searching being the only real alternative out there, if you don't happen to know the symbol, calling it what it visually looks like to you is the right thing to do.
Comment: @ElementsInSpace I wonder whether that edit was too generous in trying to make sense of this question, and whether it was asked in good faith. The puzzling sentence "Weapon reskins in tf2 have always seemed like a strange case to me" was deleted, but when I googled "team fortress 2 weapon reskins" I found a Youtube video in which that sentence is the first words spoken.
Comment: @AndyBonner Maybe.  I deleted that sentence because I couldn't make any sense of it, and it seemed like it was put there by accident — but as you point out, it's actually some kind of meme.  I think my edit turned this into reasonable question (even if it's probably a duplicate).
Comment: You have to look more carefully. That's not an "E", it's a "C": the "tail" of the upper end of the "C" is a circle. Zoom in the page, and you'll [clearly see it](https://i.stack.imgur.com/G64VL.png). While some programs or copyists may not be as accurate as they should, proper notation requires that any symbol should be carefully placed in order to avoid confusion. For example, dots of dotted notes are **always** placed above (not within) the line whenever their related note is within a staff/ledger line. See [common time](//en.wikipedia.org/wiki/Time_signature#common_time).
Comment: Do these answer your question? [Why was the common time symbol created?](https://music.stackexchange.com/q/95538) [What made 4/4 time the most common time signature?](https://music.stackexchange.com/q/89648) [What time signature uses a C and a backwards C?](https://music.stackexchange.com/q/77020)
Comment: I'm so sorry about this, apparently slightly younger me had no idea what he was talking about and thought tf2 was funny. I apologize
Answer: That e symbol is actually more similar to a c, and is known as common time. It is equivalent to 4/4 time.
There is also a similar symbol, which consists of the same c-like symbol but with a vertical line cutting through it:

This one is known as cut time and is equivalent to 2/2 time.
Check the other answers for a more thorough explanation of the origin of these symbols, their meanings and historical context.
Comment: As noted in another answer, these symbols are commonly referred to as "common time" and "cut time" in English, but they do not actually stand for those phrases as they were in use for quite some time before the phrases came into use -- and are used equally by musicians whose native languages do not use words starting with "C" to denote these symbols or the meters they represent.
Comment: @phoog That is what I meant to say, though the wording indeed is not very good. I'll change the wording
Comment: @phoog - I guess cut time is o.k. as there is a cut vertically through the C. Rather than the C standing for cut.
Comment: @Tim of course it's _o.k._; it's just not the origin of the sign.  That is, it's not that there was a thing called "cut time" that led people to start using slashes.  To say "stands for" implies cause and effect that doesn't exist.  "Known as" is rather more accurate (and I have added an upvote accordingly).  The example image here is also helpful in that the teardrop or whatever that's called at the beginning of the C curve isn't touching the middle line of the staff, so is rather clearer than the example in the question.
Answer: Basically the "C"-like symbol means 4/4 today.  The origin is a lot more murky and less known (even someone like me who studied music theory as a music major in college didn't know it until today), leading to a common error thinking that the symbol has meant "Common time" (4/4) from the very beginning, although that is the meaning in the past few centuries (not sure since when, but at least since the mid-18th century).
What follows is taken from this article to explain the origin of the symbol.  Wikipedia concurs with more details and more technical explanation.

In the 13-17th centuries, people considered music in triple time (that is, with three beats in the bar), to be "perfect", (something to do with the Holy Trinity – the number three has religious connections!) Perfection was represented by a complete circle, so music in triple time had a full circle as the "time signature" (the correct term for these signs is actually "mensuration sign").
In contrast, music with 2 or 4 beats in the bar was considered "imperfect", and was represented by a semi-circle – which happens to also look a lot like a C!
There were four basic time signatures. "Perfectum" means there were three main beats in the bar, and "Imperfectum" means two. When the beat is subdivided into three, it was called "prolatio maior" (shown by a dot), and if it is subdivided into two, it is "prolatio minor". Here are the four old time signatures, with their modern equivalents:

Here's what the C time signature used to look like in a manuscript (notice that barlines didn't exist yet!)

Over time music evolved, and "C" was considered to represent four beats in the bar, rather than two. Mensural rhythms got so complicated that almost nobody could understand them, and the modern "fraction-style" time signatures were invented. But "C" was a convenient and quick symbol, and continued to be used widely.

Please see the article linked above for more details about origin of "C" with a vertical line, which today means "Cut time" (2/2).
Comment: The signs were developed in the late 1200s.
The slash could be applied to the full circle as well as to the broken circle (a.k.a. "C").  It means "twice as fast"; that the unit of time was not the semibreve but the breve, hence "alla breve." You can also find C-slash meaning 4/2 as late as Brahms, possibly later, which is less surprising of you take into account the fact that these symbols were used for three or four centuries before bar lines began to be used to delineate measures of uniform length.
Comment: Surely the dots in two oft hose time sigs would be right where the middle line is, so obscured?
Comment: @Tim I think "seldom hose signatures" would be more accurate, don't you?  (Sorry, couldn't resist.)  More seriously, the dots tend to be rather larger in diameter than the width of the staff line; the mensuration sign isn't necessarily centered on a staff line (so the dot could be in a space); and, in my experience at least, these signs are fairly rare (I believe they're more common in periods with which I am less experienced, namely the 14th century and earlier).
Comment: @Tim I was just looking at [Cantiones quae ab argumento sacrae vocantur](https://imslp.org/wiki/Cantiones_quae_ab_argumento_sacrae_vocantur_(Tallis,_Thomas)), a collection of sacred pieces in Latin published by Thomas Tallis and William Byrd in 1575 while they had their monopoly on music printing.  It is a set of part books printed from movable type.  The solution there is to interrupt the staff line inside the circle or half circle when there is a dot inside.
Comment: @phoog - interesting - many thanks! If the staves were hand-written, it would be easy (and they probably were), but starting with printed staves, not so. No Tippex in those days...
Comment: @Tim they are not hand written; the edition was set using movable type.  So the piece that has the mensuration sign is cast without that staff line.  With engraved music it should also be possible, if more difficult, as you can use a flat punch to remove engraved lines as far as I understand.  But of course it's easier just to use a fat dot.
Answer: That's not an "e", it is an incomplete circle indicating "imperfect time" or time based on 2 strong beats.  This is in contrast to a complete circle indicating "perfect time" or time based on 3 strong beats, perfect like the holy trinity.
That's the historical origin of the sign.  It has become more of a stylized "c" over time.  Some people now will claim that "c" stands for "common time", but of course this is nonsensical since musical notation is not of English origin.  It is more likely that the "common time" moniker derives as a mnemonic from interpreting what has become more or less looking like a "c".
Cut time ("alla breve") is the other sign that survived from the mensural meter symbols.  All other meters are these days specified as numeric fractions, or sometimes as simple numbers like a 3 instead of 3/1, notation that was still common in early baroque times but has not survived for much longer than that.

What is this weird “e” time signature?


Compare two String with MySQL

Question: I wan't to compare two strings in a SQL request so I can retrieve the best match, the aim is to propose to an operator the best zip code possible.
For example, in France, we have Integer Zip code, so I made an easy request :
SELECT *
FROM myTable
ORDER BY abs(zip_code - 75000)

This request returns first the data closest of Paris.
Unfortunatelly, United Kingdom have zip code like AB421RS, so my request can't do it.
I see in SQL Server a function 'Difference' : http://www.java2s.com/Code/SQLServer/String-Functions/DIFFERENCEworkoutwhenonestringsoundssimilartoanotherstring.htm
But I use MySQL..
Is there anyone who have a good idea to do the trick in one simple request ?
PS : the Levenshtein Distance will not do it, as I really wan't to compare string like if they were number. ABCDEF have to be closer to AWXYZ than to ZBCDEF.
Answer: Ok, I have to stop asking question and find answer just after !!
For the community, here is what I will do :
select *
from myTable
order by abs(ascii(substring(zip_code,1,1)) - ascii(substring('AAAAA',1,1))) asc,
         abs(ascii(substring(zip_code,2,1)) - ascii(substring('AAAAA',2,1))) asc,
         abs(ascii(substring(zip_code,3,1)) - ascii(substring('AAAAA',3,1))) asc,
         abs(ascii(substring(zip_code,4,1)) - ascii(substring('AAAAA',4,1))) asc,
         abs(ascii(substring(zip_code,5,1)) - ascii(substring('AAAAA',5,1))) asc

Compare two String with MySQL


>150Million records insert select query canceled after 12 hours AWS RDS

Question: I have a AWS RDS t2.micro storing over 150 million records in a table from which i need to make a select insert query to another table, the purpose of this select query is to make a percentage calculation into second table.
I tested this query in a testing db with less than 100 rows(same t2.micro) and it ran correctly.
I think the query is being canceled because of the t2.micro capabilities.
I'm considering upgrading the RDS from t2.micro to r6g.large, but im not sure if this will solve my problem, any suggestions?
Comment: Suggest you consider some kind of timeout setting. Google found this page as a starting point https://aws.amazon.com/blogs/database/best-practices-for-configuring-parameters-for-amazon-rds-for-mysql-part-3-parameters-related-to-security-operational-manageability-and-connectivity-timeout/
Comment: Let's look at the query -- 12 hours is far more than makes sense, even for 150M rows.  Maybe there is a simple fix to make it faster.
Comment: This is the question to improve the query, on mysql 8.x https://dba.stackexchange.com/questions/289231/select-insert-query-optimization-on-large-volume
Answer: Why don't you try it? M6g.large costs $3.60/day - you'll hardly get broke on that. Also you can use a bigger instance for inserting the records and downsize when done.
Beside that check out the Monitoring tab in the RDS console and see if anything happened at around the time your query failed. You may want to enable 'T2 Unlimited' to prevent running out of CPU credits.
Hope that helps :)


Fixed Effects Gravity Model for forecasting..with time constant variables Stata

Question: I have a large panel data set of global trade flows and I would like to create a model for forecasting between two specific country pairs. I am just having trouble figuring out how to go about it in Stata using fixed effects and yet still accounting for the individual effects.
I found this research paper and would essentially like to recreate the process explained on p.299: http://ageconsearch.umn.edu/bitstream/43996/2/martinez.pdf

A problem we faced with FEM is that we cannot directly estimate
  variables that do not change over time because the inherent
  transformation wipes out such variables. However, these variables can
  be easily estimated in a second step, running another regression with
  the individual effects as the dependent variable and distance and
  dummies as explanatory variables

I can easily estimate xtreg with trade volume regressed on gdp/gdp per capita, but what are the steps I then take to estimate the individual effects (dist, island, etc) in Stata?
Note: I assume they are using FE OLS, but because my data contains many 0 trade flows, is it possible to apply this method to an xtpoisson instead?
Answer: What they do in the paper is that they estimate their gravity model, say equation 5.2, using the fixed effects estimator and they estimate the fixed effects directly to use them later in equation 6. You can do this with the predict command after xtreg. In Stata this would be:
xtreg IX lYi lYj lNi lNj lD  lIi lIj Pij1 - Pijh
predict IE, u

In the fixed effects regression all the time-invariant variables drop out as the authors stated. The predict command then gives you the individual effects $\text{IE}$ which they use in equation 6.
With regards to your note I'm not sure if the same procedure applies to xtpoisson given that the interpretation of the estimated fixed effects changes. For this have a look at a similar question on the Statalist with the corresponding answer by Maarten Buis. He is also active on CV so if you're lucky he can provide you with guidance on this. Otherwise I would guess that Martinez-Zarzoso and Nowak-Lehmann had the same problem with the many zeros (I suppose their data is similar to yours given the similarity of the application) and yet the had their reasons to stick to linear models.
I hope this helps.
Comment: Thanks! However, they most likely didn't have a 0 problem due to the limited regions they explored and aggregation compared to the global industry level BACI-CEPII data I am using.


Unable to save content language configuration

Question: My Drupal 8 website is multilingual and has many entity type bundles for nodes, taxonomy terms, paragraphs, media et cetera. This leads to a content language settings form (admin/config/regional/content-language) with more than thousand translatable-checkboxes.
Currently I'm not able to save this form. In the first place the form seemed to be successful submitted but changes have not been saved. This was caused by insufficient php setting value for max_input_vars, which could be solved by setting it to 6000. Now I'm struggling with a timeout. After submitting the form the request fails after some minutes.
Here are the php settings of my Drupal VM:
php_version: "5.6"
php_memory_limit: "1024M"
php_realpath_cache_size: "1024K"
php_opcache_enabled_in_ini: true
php_opcache_memory_consumption: "192"
php_opcache_max_accelerated_files: 4096
php_max_input_vars: "6000"
php_max_execution_time: "720"
php_post_max_size: '64M'

How can I get around this issue? Which resource bottleneck could cause this?
Comment: How many input fields do you have on that page? With `document.querySelectorAll('input').length` on the Dev-Tools you will get an info about that. I have a multilingual site too with about 40 bundles. But I have more fields on the permissions settings page. On the content language configuration page I have only 454 input fields, on the permissions settings page there are 2316 input fields. The only change I made was to increase the `max_input_vars` to 2500.
Comment: @RWAM: Currently there are 148 bundles listed with 1622 checkboxes. It's I quite complex website. The permission settings page is also very large but you can decrease the number of input fields by setting permissions on each role separately.
Comment: What's your value for the php setting `max_input_time`? Otherwise you can test to increase other settings. In my environment I use the following values: `realpath_cache_size: 4096K`, `post_max_size: 128M`, `opcache.max_accelerated_files: 10000`.
Comment: How can you get around this issue? If you are desperate, you could hack core and remove array keys from `$entity_types` in the first line of buildForm() in core/modules/language/src/Form/ContentLanguageSettingsForm.php.
Comment: @RWAM: `max_input_time` is set to `60`. I will test your suggested values and report back.
Comment: @4k4: No, I'm not that desperate – at least not yet.
Comment: Then you could file an issue to make this possible in UI, selecting the entity types before the form is displayed.
Comment: @RWAM: None of your suggested values made any noticeable difference.
Comment: I could finally save the form without a timeout by updating PHP on my VM to 7.1. But it still does take a very long time.
Answer: I tried the max_input_vars fix and that didnt work (i have alot of custom entities on the page and was hoping this would work).
I had to check the entity, pretend it was called MyCustomEntity in 'Custom language settings' at the top... but also scroll down to the individual MyCustomEntity settings further down on the page, and also check that checkbox. When I saved, now it worked
Answer: Today I had to struggle again with this problem and could solve it by disabling Xdebug. So to sum up this could help:

increase memory_limit and max_execution_time
update to latest PHP version (at least 7.1)
make sure Xdebug is not enabled when saving the settings form (e.g. via browser extension or general xdebug settings on server/vm)


Change colour of ckeditor show blocks border

Question: The ckeditor editor window for the site content areas has a blue background to match the website so that the client sees a true representation of the website while adding content.
When "show blocks" is selected the blocks border displayed is barely visible on the blue background.
Therefore, where can the colour of the show blocks border be changed to a darker colour?
Answer: CKEDITOR.replace( 'textarea_id', {
    uiColor: '#14B8C4'
});
Update :-
Check the sample url:ckeditor
Answer: Unfortunately, color of border displayed for blocks isn't customizable. CSS that styles them is generated by JS. You can find it here http://dev.ckeditor.com/browser/CKEditor/trunk/_source/plugins/showblocks/plugin.js#L28
I guess that you're using compiled version of CKEditor, so source is minified. You'll have to open ckeditor.js file and find this fragment and change it manually.
Or you can try to clone CKEditor 4 (new version that will be release next Tuesday), change this value here https://github.com/ckeditor/ckeditor-dev/blob/master/plugins/showblocks/plugin.js#L48 and then compile your build of CKEditor (you can find instructions here https://github.com/ckeditor/ckeditor-dev). But to do this you'd need Mac or Linux, because build script is written in Bash.
Comment: Thanks for the reply. Took some time but found the fragment in ckeditor.js for the borders and successfully changed to black.
The text at the top left for each block is shown by png images and the text is grey so will have to change text colour to black in all the png files
Comment: This all works well now. Both the black show blocks border and the black html tags in the new png images show up well on the blue background.


About a reference collecting the main properties of the modulus and the argument of $f$

Question: Let $f$ be an analytic function in the whole complex plane. We can write $f$ in its polar form: $$f(z)=ρ(z)exp(iθ(z))$$
My question is about a reference collecting the main properties of the modulus and the argument of $f$.
Answer: Actually, it is not clear how to write $f$ is polar form globally. The function $\theta$ is undefined at the zeros of $f$, and does not have a single-values continuous branch around them. The most basic properties of these functions are:

$\rho$ is subharmonic on $\mathbb C$, and harmonic on $\mathbb C\setminus f^{-1}(0)$.
$\theta$ is  harmonic on simply-connected subdomains of $\mathbb C\setminus f^{-1}(0)$.

As for references:

Potential Theory in the Complex Plane by Ransford covers the fundamental properties of harmonic and subharmonic functions, relating them to holomorphic functions.
Any book on entire functions  considers the global behavior of $\rho$ in detail (sometimes, in excruciating detail). For example, entire functions by R.P. Boas or  Introduction to the theory of entire functions by A.S.B. Holland.
For the devotees of the subject,  Subharmonic functions Vol II by  Hayman can be recommended, but this is definitely not a first reading.  I  think these books don't spend much time on $\theta$ because it's not a globally defined function.
There is also Harmonic function theory (Axler, Bourdon, Wade) if you are specifically interested in harmonic functions.

As far as I know, nobody ever wrote a book to  "collect the main properties of the modulus and the argument"; generally speaking, this is not what mathematicians do.


ClamAV not installed. ClamAV is already installed

Question: Re-Edit:
After lots of Googling, lots of tracing, lots of tinkering with the nginx.conf & /vhosts -
It came down to an error message saying ClamAV was not up to date.
Running clamscan told me clamscan was not installed.
Trying to install clamscan told me it was already installed. e_e
So, looks like I'm gonna be wiping this server, soon.
Much thanks to everyone that gave their insight.
If anyone knows a legitimate how or why such a thing can happen, I'd be happy to know...
Edit:
I solved this by restarting the server. e_e
If I am not mistaken, this would implicate php-fpm -- right?
However, now that nginx is online and responding to the config changes I make -- I'm getting 403 forbidden and 502 bad gateway on things I had never gotten before. (ISPConfig and PhpMyAdmin, respectively)
Error log says :
[error] 9150#0: *7 open() "[...]/ispconfig/[..]/phpmyadmin" failed (13: Permission denied),

One link suggests increasing the buffer size - which I tried, does not work --
And the other things I found seemed to be irrelevant ---
Thanks again !

To make a long story short, this all started when I was trying to make an nginx config to add a password to a site. No big deal - I've done it before, no sweat --
However, the configuration was not working with no good reason as to why ---
Well, long story short, after many failed attempts, I finally commented out the line:
include sites-enabled/* ;

in nginx.conf
Only for the surprise that everything still works ---
After making sure Apache wasn't running (it isn't even installed, anymore!) -
I Googled around to see if I could find anything about a config cache on Nginx - but no dice.
So, I've come to you good people, here -- to see if you can lend me any insight on why everything still works against my best intentions of breaking it
Strangely enough, nginx continued to work even after running
sudo service nginx stop
* Stopping nginx nginx

and
sudo cat /var/log/nginx/error.log

didn't yield anything useful, aside from the "[emerg] bind() to 0.0.0.0:80 failed"
Which it seems I've always gotten - and has never caused problems, before...
Comment: It sounds like nginx isn't _stopping_ for some reason. You should investigate that, and/or kill it manually before restarting.
Comment: It gave me the * Stopping nginx  --- Is there a case where that may not actually be the case?
Answer: Have you restarted nginx to apply changes?
sudo service nginx restart

Can you try stopping nginx and check that all processes are stopped, before restarting it:
sudo service nginx stop
ps aux|grep nginx # should display no nginx process
sudo service nginx start

If you have "[emerg] bind() to 0.0.0.0:80" in logs, check which process is listening to port 80 netstat -anlp|grep 80 and stop it/ or kill it.
Comment: `reload` is the better option generally since it won't stop an already running nginx instance if the config is faulty. A restart however will stop the running nginx before starting it again so its possible a faulty config file will prevent it from starting. In this case though it sounds like it isn't running at all so a restart is the correct choice.
Comment: @Kyle agree regarding reload, in this case a process is running on port 80 so I think the better is to stop all, checking that all processes are stopped master&workers, then restart nginx to have a clean instance, after the reload should work as expected
Comment: Yes... I was even going back and forth between reload and restart --
Comment: Under further inspection, tripwire and clamav both went MIA-- . So -- some hackery must be at work, here.


norm of a quadratic form

Question: Suppose that $q$ is a quadratic form on $\mathbb{R}^n$, $q(x)=(x,Ax)$ say (or $q(x)=x^TAx$ if you prefer that notation).  Then one could consider the quantity
$$
\sup\{ \left|q(x)\right| : \left\| x \right\| \leq 1 \}.
$$
Is this an interesting quantity? In particular when the norm is the $p$-norm for $p \neq 2$?
Comment: Note that $\sup \{ |q(x)|: \| x \| \le 1 \} = \sup \{ |q(x): \| x \| =1 \}$ by applying linearity: $q(\lambda x)=\lambda^2 q(X)$, so $q(x) = \|x\|^2 q(x/\|x\|)$.
Answer: It is, indeed.  You can state the problem as that of maximizing the quadratic form $x^TAx$ subject to the constraint $x^Tx=1$.  It is well known that the maximum you seek is exactly the maximum eigenvalue of $A$ and the $x$ attaining this maximum is the eigenvector associated to this eigenvalue.  Thus, the quantity you are asking about is just the maximum eigenvalue's norm.
More generally, given $A$ symmetric (no loss of generality here) and $B$ positive definite, you can prove that
$$max \{x^TAx\;\;\colon\;\; x^TBx=1\}$$
is the maximum eigenvalue of $B^{-1}A$ at $x$ the corresponding eigenvector.
Comment: As I read the question, the OP was more interested in the case of the $p$-norm with $p\neq 2$. Can you say anything in this case?

norm of a quadratic form


polr not matching contingency table results

Question: I am trying to tie the odds ratio from a 2x2 cross classification table to the intercepts of a logistic regression on those 2 variables. I have a cross classification table that produces 2 odds ratios and the results of a logistic regression of PLACE3 ~ VIOL should produce intecepts should match the odds ratio of the contingency table. i.e. Odds ratio = exp(intercepts)  BUT the POLR package is not producing the correct intercepts.
Here is the data.  In the logistic regression PLACE3 is the outcome and VIOl is the independent variable.   You can see the PLACE3 vs. VIOL contingency table below and the logistic regression of PLACE3 ~ VIOL.  The odds ratios in the contingency table 1.79 and 3.1 are correct but the polr function seems off. Any thoughts on why  exp(summary(m)$zeta) does not produce 1.79 and 3.1?
For reference this is from Lemeshow's Applied Logisitic Regression book page 274.
library(data.table)
aps <- fread('http://www.umass.edu/statdata/statdata/data/aps.dat')
colnames(aps) = c("ID","PLACE","PLACE3","AGE","RACE","GENDER","NEURO","EMOT","DANGER","ELOPE","LOS","BEHAV","CUSTD",
                    "VIOL")
head(aps)

Here is  a cross classification table of PLACE3 vs. VIOl variables
table(aps$PLACE3,aps$VIOL)
      0   1
  0  80 179
  1  26 104
  2  15 104

using PLACE3 = 0 as the reference the 2 odds ratios from the contingency table are
(104*80)/(179*26)  #1.79
(104*80)/(179*15)  #3.10

These odds ratios should be the same as exponentiating the slope coefficients  from
a logistic model  PLACE3 ~ VIOL which is below
aps$constant = rep(1,dim(aps)[1])
m <- polr(as.factor(PLACE3) ~ constant + as.factor(VIOL), data = aps, Hess=TRUE,model=TRUE,method = c("logistic"))
summary(m)

> summary(m)
Call:
polr(formula = as.factor(PLACE3) ~ constant + as.factor(VIOL),
    data = aps, Hess = TRUE, model = TRUE, method = c("logistic"))

Coefficients:
                  Value Std. Error t value
as.factor(VIOL)1 0.8454     0.2112   4.003

Intercepts:
    Value  Std. Error t value
0|1 0.6869 0.1884     3.6464
1|2 1.8608 0.2032     9.1557

Residual Deviance: 1031.75
AIC: 1037.75

But you can see the exponentiation of the zeta vector is not 1.79 and 3.10
exp(summary(m)$zeta)

> exp(summary(m)$zeta)
     0|1      1|2
1.987495 6.429049

Comment: Why do you think those odds ratios are appropriate for a proportional odds model? Also you are ignoring the coefficient for VIOL. Also you do not need to add a constant and as you can see polr ignored it.
Comment: I am not sure what you mean when you say appropriate. For a single dichotomous independent variable the odds ratio calculated manually should match that of the logistic regression.  I am not doing model fitting or anything here. Just pure mechanics. I see that the polr does not include the constant even though one  is provided. Can you advise how to make polr recognize the constant?  i have constant + factor(VIOL).
Answer: The relevant odds ratios for a proportional model are (80 * (104 + 104)) / ((26 + 15) * 179) and ((80 + 26) * 104) / ((179 + 104) * 15) so whatever model you are trying to fit here it is not the proportional odds model.
The documentation for polr is perhaps a little sparse so you might want to look at something like the article by Bender and Benner here entitled "Calculating ordinal regression models in SAS and S-Plus". Despite the title it is relevant for R and also more generally.
But as I mention whatever you are trying to do the proportional odds model does not seem to be what you want.
Are you by any chance wanting to model the other way round?

glm(VIOL ~ PLACE3, family = binomial, data = aps)


How to recover? Suspended google Adwords account

Question: Account was suspended on 23 jan (saying i have done Misrepresentation)
after follow ups,
23 feb they sent email saying (suspicious behaviour in the payment activity of this or your other AdWords accounts)
later they sent email saying (We've confirmed that your account is in violation of our AdWords policies)
further more saying (Please avoid creating additional AdWords accounts, as they will be subjected to the same suspension).
Can some one advise what to do? the point is our card is in use with multiple accounts.
Answer: Google are pretty thorough with their investigations, so if something is in violation, then it probably is! Have you tried contacting your account management team? I believe all accounts are assigned to an account management team, and then assigned to teams based on spend limits. Visit this link for contact numbers.
Your best bet is to give AdWords support a call and provide your account IDs and find out who your account manager is, and then query the violation with them and try to get them remove the suspension.
You could try opening a new account with new card details if its a payment issue, but your domain will match from an existing account so Google will figure this out pretty quickly, therefore its best to resolve any violations directly with Google rather than trying to beat around the system.
I would recommend creating a manager account and then adding accounts under the manager account, this way all accounts can use one billing method as opposed to setting the same billing in individual accounts.
Comment: Last email they sent and said no one can help any further, the violation is that our company card have been in use on multiple account.


How do you deal with longer right hand middle finger when playing classical guitar?

Question: My right hand technique is quite poor, and middle finger keeps touching the string below.
Should I find the ideal amount of curvature of middle finger? Or is there another way?
Comment: If possible, add a picture. That often leads to specific suggestions.
Comment: As it stands, there's not enough information to give useful answers to this. i tried, but may be well off the mark. Please edit so we have a lot more to go on. String below?? Which one is that?, for example.
Answer: Often, touching the string below (apoyando), is actually an oft used technique in classical guitar playing! Pluck the string concerned, upwards, and let the same finger come to rest on the lower pitched string next to it. Tirando is the other, where a string is plucked, and the plucking finger touches nothing else until it's deployed again.
Actually, a very quick Google found an absolute myriad of texts and videos on 'how to play classical guitar with the right hand', with many ideas available. Have a look!
As far as solutions are concerned, there could be many little things that make this happen. Angle(s) of guitar, how it's held when you play, curvature of fingers, position of hand over the strings, etc., etc.
A start point is to not anchor the hand either with the pinky on the body, or the thumb on the 6th string. Try to anchor it with the forearm on the body, so at least it doesn't wave around. Of course curl fingers at the same time, and this will even out their length differences somewhat.
In reality, I could write a book on what's possibly going wrong, and that's inappropriate here! Suffice to say - find a teacher, who will be able in a very short time (even one or two lessons) to rectify the problem - you maybe won't need more than that. But asking complete strangers with no pics/video and very little other information makes this impossible to answer to anyone's satisfaction!
Comment: This seems like a lot of words that don't contain a real answer. And there are real answers to this. The only thing valuable here is "find a teacher" which imho goes in a comment, not in an answer. Oh and the part about not anchoring with the thumb is kinda wrong in many situations. Or at least isn't not always right and in my experience poor advice to give to someone learning.
Comment: @Tim since finger curvature was mentioned I just thought the issue might be touching the B string before the G because the middle finger is longer. As we know from experience we have to curve our fingers different amounts to make contact with a single string but this is a learned skill. As with a lot of first time posters, there has been no comment or clarification regarding their issue so far.
Comment: @ToddWilcox  - given the sparse information in the question, i was trying to be as helpful as I could. Yes, of course there are real answers to this. Whether they're actually relevant to OP is another matter. And, anchoring (or not) with the thumb - opinion. I'm trying, other answers please!
Comment: An alternate approach that wouldn't get my downvote would be to wait until the question is clear to you before attempting to answer. Also this answer reads like it was written by someone who doesn't know a lot about classical guitar technique, which further suggests just refraining from answering entirely. And there's some points here that I'm pretty sure are simply wrong. So to me it's more harmful than helpful. Anchoring is only an opinion as much as any refined and sound and universally used technique is. Maybe a few pros don't do it but that's no reason to say not to.
Comment: @ToddWilcox - seems you know a lot more, so  a superior answer is awaited.
Comment: Since they are talking about a longer middle finger I believe by "below" the OP means the string physically below, as in the higher string. Clarification should be provided by the asker.
Comment: @JohnBelzaguy - since plucking on classicals is usually towards the next string down in pitch (pluck string 3, end up touching string 4) my answer is based on that. But we know what assumptions do... Ah, I assumed finger touching the adjacent string *before* the proper pluck. Your assumption also?
Comment: @JohnBelzaguy - the  middle finger often gets used to play the 2nd string, (no, not always, sometimes!) so that throws even more confusion! Now, I vtc until better info. is forthcoming.
Comment: @Tim I actually meant to say the B might get touched inadvertently when trying to play the G string.


show archive block on every page containing certain content type

Question: I have created one archive block using views for a content type. It holds the list of all the contents grouped year+month wise.

Now I want to display it on the left sidebar of all the pages having
  this content type.

Using Block configuration of this archive block I have displayed it on certain pages, but I can't set it to appear on all the pages of type node/*, because all nodes do not contain that very content type.
Please help if anyone knows the solution to it .
Comment: Do you insist it needs to be a block? Or something that may look like one would be OK too?
Comment: PS Could we remove version from title? You can do it pretty much the same way in all major versions.
Comment: @Mołot: No, it's not necessary.
Comment: I gave you an answer for directly what you asked, but I think using [Viewfield](https://drupal.org/project/viewfield) module might be cleaner solution in your case.
Answer: If you are using Drupal 7, you can go to Home » Administration » Structure » Blocks, and hit configure next to block you need:

In the Visibility settings section use Content types tab. In Drupal 8 it looked similar and probably will not change significantly.

The same functionality was backported to 5 and 6 by Block Node Visibility module.
If you don't want to install above module, and you're using Drupal 6, use Pages tab, and select last radio button "Pages on which this PHP code returns TRUE", and use code like:
<code><?php
// valid node id in view mode
if ( arg(0) == 'node' AND is_numeric(arg(1)) AND arg(2) == FALSE ) {

    $node = node_load(arg(1)); // cached

    if ( $node->type == 'insert type you want' ) {
        return TRUE;
    }
}

return FALSE;
?>
</code>
Code sample by bluesherpa from Drupal.org.


How to create the equivalent of a spreadsheet?

Question: I don't want to start with too many unnecessary details on this one. I've got a stack of codes. Weekly more codes are added. On occasion these codes will be 'used' by other systems. These other systems are not Drupal sites.
I'm not sure how else to describe this, but all I want is the equivalent of a spreadsheet in Drupal: It should be possible to add rows, and delete rows of data on a single page, instead of creating a new node for every single code. I just want a table where I can add and delete codes, something like this, a CRUD table.
My current solution is this:

Build a table (my_codes (id, code) )
Create a CRUD for the table so someone can manually enter in new codes (one by one)
Create a REST for the crud so these other systems can use these codes (codes/list, codes/add, codes/delete)

However, the main site is in Drupal, and only certain users should be able to add codes.
What is the simplest way to achieve this goal?
I could do all this work in a block, but I'd prefer to just install a Drupal module. If I can achive #1 and #2 with a module, then I should be able to do #3 myself. Note that last time I looked at CCK it did not have a "table" option.
Comment: In this case I think the details are necessary.
Comment: Have you looked into the Taxonomy module yet? I haven't spent much time with it, but you could be able to use it and CCK together to come up with something.
Comment: the simplest way is  to make a basic content type with a title and a body and give permission access to that. No additional module is needed. If this is not wht you are looking for then you need to give more details
Answer: The TableField or the Slickgrid modules may help here.
Answer: The Drupal model is that you can have an Entity representing a DB table, and then you display entities however you please. So if Drupal is to be the front end for managing the database of codes, then other systems can still use the DB without having to know how to resolve attached fields.
Views gives you tables which you can sort. Inline editing would be something you'd have to add.. A search brings me to this project: http://drupal.org/project/jeditable Representing functions as icons (trash for delete, etc) could be a formatter, or a form alter in the theming.
And voila: You've made Excel in Drupal. :-)
Answer: The Views Bulk Operations module could come in handy for you. It gives you a chance to add actions to a views table.
The Drupal standard security mechanism should be enough for you to make sure only a specific group of people have permission to create new data. You can define any number of roles and give them the permission to create your new content type.
To give a 3rd party system easy access to your Drupal data, you could use views and present your data as RSS feeds. You could also use views to get the node data as CVS files.
You might have to code a little bit for the Views Bulk Operation actions. Everything else should be possible with Drupal core and Views.


serialize Map with key and value as case class using circe

Question: Below is the simplified code that has a Map with key and value as case class.
Key and value object are successfully serialized with circe.
But facing challenge to serialize Map[CaseClassKey, CaseClassValue] with circe.
<code>//////case classes and common vals starts here//////

case class Person(personId : Int, phoneNumber : Int)

case class Item(name : String)
case class Basket(items : List[Item], bills : Map[Int, Int])

def createBasketInstance() : Basket = {
    val milk = Item("milk")
    val coffee = Item("coffee")

    val bills = Map(1 -> 20, 2 -> 75)
    Basket( List(milk, coffee), bills )
}

val basket = createBasketInstance()
val person = Person(1, 987654)

//////case classes and common vals ends here//////

import io.circe._
import io.circe.generic.semiauto._
import io.circe.syntax._
import io.circe.parser._

//Serializing Person instance that is used as Key in Map
{
    implicit val personCodec :Codec[Person] = deriveCodec[Person]
    val jsonString = person.asJson.spaces2
    println(jsonString)

}

println("-" * 50)

//Serializing Basket instance that is used as Value in Map
{
    implicit val itemCodec :Codec[Item] = deriveCodec[Item]
    implicit val basketCodec :Codec[Basket] = deriveCodec[Basket]
    val jsonString = basket.asJson.spaces2
    println(jsonString)
}

println("-" * 50)

//Serializing Map[Person, Basket]
//TODO : not able to make it work
{
    implicit val itemCodec :Codec[Item] = deriveCodec[Item]
    implicit val basketCodec :Codec[Basket] = deriveCodec[Basket]

    val map = Map(person -> basket)

    //TODO : How to make below lines work

    //val jsonString = map.asJson.spaces2
    //println(jsonString)
}
</code>
scalafiddle link : https://scalafiddle.io/sf/SkZNa1L/2
Note : Looking to just serialize and deserialize data (Map[Person, Basket]) correctly. How json looks is not really important in this particular case.
Comment: How do you want that JSON to look? Field names in JSON have to be strings.
Comment: @mogli How it looks is very important because you need to understand how your serialization format works to design the best way to serialize it. Is like thinking it doesn't matter how a database works because I only want to save data there without worrying about how to transform your data into tables / documents / graphs or whatever you are using.
Comment: @Thilo : Looking to just serialize and deserialize data (Map[Person, Basket]) correctly. How json looks is not really important in this particular case.
Answer: Strictly speaking, you are trying to create an invalid json.
Json map structure isn't an arbitrary map, it's an object structure where keys are property names.
https://www.json.org/json-en.html
See also Can we make object as key in map when using JSON?
Update:
I suggest a slight change to your model to get the job done.
Instead of Map use array of objects, each having two properties: key and value
Something like this:
<code>case class Entry(key: Person, value: Basket)

</code>
So you can replace Map[Person, Basket] with Seq[Entry], and convert it back to Map if needed.


Broken formatting while displaying both start and end date

Question: I added Event content type in D7 and I have there Event Start date. I setup this field to collect an End day + it is collecting time and have option to check "All Day Event".
What I have in the exit when I created new Event is something like:

Frida2013, 20-Sunda2013, 22, Frida2013, 20-Sunda2013, 22eptember Frida2013, 20-Sunda2013, 22, 2013 - h:ia(All day)-(All day)

When I go to Manage Display tab, I can set there for Event Date to display only Start Day for example and then this broken formatting disappears. But I need to be able to display both Start and End date.
Any suggestions appreciated.
Thanks.
Answer: Juts found a solution. Please create custom formatting like this:
D, F d, Y (h:ia)

Key here is to wrap time in parentheses

(h:ia)

after that trick formatting is fixed and looks something like:

Sat, September 21, 2013 (All day) to Mon, September 30, 2013 (All day)


What is the meaning of $\frac{d}{dx}+x$ in $(\frac{d}{dx}+x)y=0$?

Question: I believe I understand the meaning of the infinitesimals $dx$ and $dy$. I understand that $dx/dy$ is the ratio of an infinitely small change in $x$ to an infinitly small change in $y$. However, I can not imagine what $(\frac{d}{dx} +x)y=0$ is trying to say.
If it says $\frac{d}{dx}y$ I understand that this would be the notation for the derivative of $y$. However, $\frac{d}{dx}$ is not paired with any real number of which it would be sensible to take the derivative, it is all by itself.  What is interesting is that the professor takes the statement $(\frac{d}{dx} +x)y$ and multiplies out $y$, making $\frac{dy}{dx}+xy$ which is a statement that I can make sense of. However, I can not understand how this was a legal move.
Here is a timestamped link to the video in which the problem pops up.
Comment: It's a legal move simply by definition: $dy/dx + xy$ is simply what $(d/dx + x)y$ _means_. (The meaning of $d/dx$ is the operation of differentiation.)
Comment: $\frac d{dx}$ is in this context an algebraic symbol like any normal letter. Distribution works like it normal, and it is associative. It commutes with itself (obviously) and with $\frac d{dy}$, but not with $x$ or $y$. When you have finally removed all brackets, you may begin to interpret it as a differentiation.
Comment: Yes. Well, actually it's adding the operator of differentiation to the operator "multiply by $x$. Whether "$d/dx+x$" makes sense by itself depends on what sort of sense you want to make of it - it's a perfectly respectable operator...
Comment: Take a look [at this post](http://math.stackexchange.com/questions/21199/is-frac-textrmdy-textrmdx-not-a-ratio) which is my favorite! In fact, $\frac{d}{dx}[\,]+x \cdot [\,]$ is just an operator. :)
Comment: @DavidC.Ullrich

So what $\frac{d}{dx} +x$ is telling me to do is to add the operation of differentiation to the real number x? Is the result a number/variable, or does $\frac{d}{dx} +x$ only make sense when paired with another number/variable?
Comment: The easiest interpretation here, I think, is the operator theory one.
Answer: Another way to write this is $y'(x) + xy(x)= 0$.
What you are supposed to do is very likely to solve the thus given differential equation. That is determine a function $f(x)$ such that $f'(x) +  x f(x) = 0$.
Or it just may be the assertion that a (certain) function is $y(x)$ has that property. In a formal sense it is not all that different from, say, $y^2 + y x= 0$, which is also a equation involving $y$ and $x$ and some operations on these functions. The sole difference is that here you have the additional operation "take derivative."
Answer: The symbols $d/dx$ and $x$ should both be interpreted as linear operators acting on a vector space that the unknown function $y$ belongs to. The sum of linear operators is well-defined and that is exactly how the $y$ ends up between or outside the brackets. The first operator acts by differentiation and the second one by pointwise multiplication.
Comment: Depends on the approach. I had it in advanced calculus but differential equations, especially partial ones, are a strong motivator.
Comment: I have not yet taken linear algebra or whatever subject is required to understand vector spaces. However, I do now understand that I was wrongly thinking about the statement as a sum of two numbers, when in reality I should have considered it as the sum of two operators.
Comment: On a side note, in what subject is operator theory usually covered? Calc2, differential equations? Or was I supposed to cover it in some earlier subject from high school?


Is static private IP excluded from AWS VPC DHCP pool?

Question: I have legacy app that has to have 3 static private ip addresses.
I use 192.168.10.0/24 for private subnet and 192.168.10.100 , 192.168.10.101 , 192.168.10.102 as IPs that are manually assigned to EC2 with that app.
My question is: are those IPs excluded from AWS VPC DHCP pool?
If new instances launched in the same subnet could they get those IPs from DHCP and be in a conflict with existing instances?
Answer: The answer is "no". I have this issue too (Google brings me here).
While the IPs that are attributed by the DHCP service are not reusable, if you have manually assigned a secondary IP to an instance, this IP is not excluded from the DHCP pool.
However, you can reassign the secondary IP to another instance.


Should the same scaling strategy be applied to both the target class and explanatory features?

Question: I'm working with a dataset where the dependent variable is continuos (sale price of houses) and there a couple dozen features I'm using to predict the sale price using a linear regression model. These features include binary dummy variables, categorical, and continuous variables - all on different scales.
The dependent variable (sale price) is skewed, so I've instead created a new feature that is log(salePrice) so the distribution is centered. My question is, I had planned on using SckiKit-Learn's StadardScaler class on the explanatory features. Does it make sense to use two different preprocessing techniques, or should I simply use the log of all the explanatory features like I do with the dependent variable?
Answer: Threre is no reason to require that the predictor variables should be transformed in the same way as the $Y$-variable.  Depending on the nature of the variables, such a requirement make not even make sense! Like, as in your case, some of the explanatory variables are dummys---does not make much sense to transform dummys.  Scale differences between the $Y$-variable and predictors are taken care of by the estimation algorithm.
For more information on reasons to transform---or to not transform, see the excelent answers: Why not log-transform all variables that are not of main interest?
Pitfalls to avoid when transforming data?
An answer to an almost identical question:  Analysing log and square-root transformed variables