Path2D draw bug?

Question: I've been working with Path2D.Double for about a day or so now and in this post
 I asked for help regarding setting control points to allow the path to pass through specified points. I mashed together some code as a quick test bed that randomly generates points and then curves the path to those points based on the information mentioned in the above post.
Here is the runnable code, sorry it's monolithic, I wanted it to be postable so you can follow along:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.geom.Path2D;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JFrame;

public class Curver {
    public static ArrayList<Point2D> points = new ArrayList<Point2D>();
    /**
     * @param args
     */
    public static void main(String[] args) {

        final JFrame window = new JFrame();
        window.setPreferredSize(new Dimension(500,500));
        window.setLocationRelativeTo(null);

        window.addMouseListener(new MouseListener() {

            @Override
            public void mouseReleased(MouseEvent e) {
                // TODO Auto-generated method stub

            }

            @Override
            public void mousePressed(MouseEvent e) {
                // TODO Auto-generated method stub

            }

            @Override
            public void mouseExited(MouseEvent e) {
                // TODO Auto-generated method stub

            }

            @Override
            public void mouseEntered(MouseEvent e) {
                // TODO Auto-generated method stub

            }

            @Override
            public void mouseClicked(MouseEvent e) {
                new Thread(new Runnable(){
                    @Override
                    public void run() {

                        Random random = new Random();

                        while(true){

                            points.add(new Point2D.Double(random.nextInt(window.getWidth()-1)+1,random.nextInt(window.getHeight()-1)+1));
                            System.out.println(points.size());

                            try {
                                Thread.sleep(500);
                            } catch (InterruptedException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }

                        }

                    }

                }).start();
            }
        });

        window.pack();
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setVisible(true);

        int div = 7;
        int d = 4;

        Path2D.Double path = new Path2D.Double();
        Point2D currentPoint;
        double startX, startY;
        double interiorX_In, interiorY_In;
        double interiorX_Out, interiorY_Out;
        double endX, endY;

        Graphics2D g;

        while(true){

            g = (Graphics2D) window.getGraphics();
            g.setColor(Color.blue);

            for(int i = 0; i < points.size(); i++){

                currentPoint = points.get(i);
                g.fillRect((int)currentPoint.getX(), (int)currentPoint.getY(), d, d);

                if (i == 0){
                    // Don't attempt any line drawing as we don't have enough points.
                    path.moveTo(currentPoint.getX(), currentPoint.getY());
                } else if (i == 1 && points.size() > 2){
                    // draw first curve with knowledge of third point (third point is not end point)
                    startX = points.get(i-1).getX() + (currentPoint.getX() - points.get(i-1).getX()) / div; // from start
                    startY = points.get(i-1).getY() + (currentPoint.getY() - points.get(i-1).getY()) / div;

                    interiorX_In = currentPoint.getX() - (points.get(i+1).getX() - points.get(i-1).getX()) / div; // to interior
                    interiorY_In = currentPoint.getY() - (points.get(i+1).getY() - points.get(i-1).getY()) / div;

                    path.curveTo(startX, startY, interiorX_In, interiorY_In, currentPoint.getX(), currentPoint.getY());

                } else if (i == 1){ // Only 2 points in list so use a straight line until more points are available.
                    g.drawLine((int) points.get(i-1).getX(), (int) points.get(i-1).getY(), (int)currentPoint.getX(), (int)currentPoint.getY());
                } else if (i >= 1 && i < points.size()-1){ // interior to interior edge.

                    interiorX_Out = points.get(i-1).getX() + (currentPoint.getX() - points.get(i-2).getX()) / div; // from interior
                    interiorY_Out = points.get(i-1).getY() + (currentPoint.getY() - points.get(i-2).getY()) / div;

                    interiorX_In = currentPoint.getX() - (points.get(i+1).getX() - points.get(i-1).getX()) / div; // to interior
                    interiorY_In = currentPoint.getY() - (points.get(i+1).getY() - points.get(i-1).getY()) / div;

                    path.curveTo(interiorX_Out, interiorY_Out, interiorX_In, interiorY_In, currentPoint.getX(), currentPoint.getY());

                } else { // from interior point to end point.

                    interiorX_Out = points.get(i-1).getX() + (currentPoint.getX() - points.get(i-2).getX()) / div; // from interior
                    interiorY_Out = points.get(i-1).getY() + (currentPoint.getY() - points.get(i-2).getY()) / div;

                    endX = currentPoint.getX() - (currentPoint.getX() - points.get(i-1).getX()) / div; // to end
                    endY = currentPoint.getY() - (currentPoint.getY() - points.get(i-1).getY()) / div;

                    path.curveTo(interiorX_Out, interiorY_Out, endX, endY, currentPoint.getX(), currentPoint.getY());

                }

            } // end for

            g.clearRect(0, 0, window.getWidth(), window.getHeight());
            g.draw(path);
            path.reset();

            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

Just click the JFrame to start plotting random points - the console will report the number of points being plotted.

The issue I have is once I get upwards or 60-65 random points the path flickers and seems to shrink on screen and generally exhibits weird behaviour?
 As I said the code may not be perfect so could anyone give me some pointers as to how to make it less buggy.
I assume the weird behaviour comes from constructing longer and longer paths per repaint of the JFrame? Is there perhaps a way I could either draw the path as a contiguous line as I suppose the path is interpreted as a sequence of segments? Or perhaps make the path cumulative as opposed to reconstructing the whole thing for each iteration of the run loop ?
Looking forward to any advice offered - but please try to explain as I am relatively new to painting and paths etc.
Thanks in advance.

Thanks to @camickr for their post.
Here is the re-written code that works flawlessly, 3,500+ random points and not a single glitch:
> import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.geom.Path2D;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.Random;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;

public class Curver extends JFrame implements ActionListener, MouseListener{

    public Timer animationTicker = new Timer(50, this);
    public ArrayList<Point2D> points = new ArrayList<Point2D>();
    private Canvas canvas;

    public Curver(){
        this.setPreferredSize(new Dimension(500,500));
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLocationRelativeTo(null);
        this.setLayout(new BorderLayout());
        canvas = new Canvas(points);
        this.add(canvas, BorderLayout.CENTER);
        this.addMouseListener(this);
        this.pack();
        this.setVisible(true);
    }

    class Canvas extends JPanel{

        int div = 7;
        int d = 4;

        Path2D.Double path = new Path2D.Double();
        Point2D currentPoint;
        double startX, startY;
        double interiorX_In, interiorY_In;
        double interiorX_Out, interiorY_Out;
        double endX, endY;
        Graphics2D g2;
        ArrayList<Point2D> points;

        public Canvas(ArrayList<Point2D> points){
            this.setMinimumSize(new Dimension(100,100));
            this.points = points;
        }

        @Override
        public void paintComponent(Graphics g) {

            g2 = (Graphics2D) g;
            g.setColor(Color.blue);

            synchronized(points){
            for(int i = 0; i < points.size(); i++){

                currentPoint = points.get(i);
                g2.fillRect((int)currentPoint.getX(), (int)currentPoint.getY(), d, d);

                if (i == 0){
                    // Don't attempt any line drawing as we don't have enough points.
                    path.moveTo(currentPoint.getX(), currentPoint.getY());
                } else if (i == 1 && points.size() > 2){
                    // draw first curve with knowledge of third point (third point is not end point)
                    startX = points.get(i-1).getX() + (currentPoint.getX() - points.get(i-1).getX()) / div; // from start
                    startY = points.get(i-1).getY() + (currentPoint.getY() - points.get(i-1).getY()) / div;

                    interiorX_In = currentPoint.getX() - (points.get(i+1).getX() - points.get(i-1).getX()) / div; // to interior
                    interiorY_In = currentPoint.getY() - (points.get(i+1).getY() - points.get(i-1).getY()) / div;

                    path.curveTo(startX, startY, interiorX_In, interiorY_In, currentPoint.getX(), currentPoint.getY());

                } else if (i == 1){ // Only 2 points in list so use a straight line until more points are available.
                    g2.drawLine((int) points.get(i-1).getX(), (int) points.get(i-1).getY(), (int)currentPoint.getX(), (int)currentPoint.getY());
                } else if (i >= 1 && i < points.size()-1){ // interior to interior edge.

                    interiorX_Out = points.get(i-1).getX() + (currentPoint.getX() - points.get(i-2).getX()) / div; // from interior
                    interiorY_Out = points.get(i-1).getY() + (currentPoint.getY() - points.get(i-2).getY()) / div;

                    interiorX_In = currentPoint.getX() - (points.get(i+1).getX() - points.get(i-1).getX()) / div; // to interior
                    interiorY_In = currentPoint.getY() - (points.get(i+1).getY() - points.get(i-1).getY()) / div;

                    path.curveTo(interiorX_Out, interiorY_Out, interiorX_In, interiorY_In, currentPoint.getX(), currentPoint.getY());

                } else { // from interior point to end point.

                    interiorX_Out = points.get(i-1).getX() + (currentPoint.getX() - points.get(i-2).getX()) / div; // from interior
                    interiorY_Out = points.get(i-1).getY() + (currentPoint.getY() - points.get(i-2).getY()) / div;

                    endX = currentPoint.getX() - (currentPoint.getX() - points.get(i-1).getX()) / div; // to end
                    endY = currentPoint.getY() - (currentPoint.getY() - points.get(i-1).getY()) / div;

                    path.curveTo(interiorX_Out, interiorY_Out, endX, endY, currentPoint.getX(), currentPoint.getY());

                }

            } // end for

            g.clearRect(0, 0, this.getWidth(), this.getHeight());
            g2.draw(path);
            path.reset();
            }
        }
    } // end of inner class

    @Override
    public void actionPerformed(ActionEvent e) {
        this.canvas.repaint();
    }

    @Override
    public void mouseClicked(MouseEvent e) {
        new Thread(new Runnable(){
            @Override
            public void run() {
                System.out.println("Thread running");
                Random random = new Random();

                while(true){
                    synchronized(points){
                        points.add(new Point2D.Double(random.nextInt(getWidth()-1)+1,random.nextInt(getHeight()-1)+1));
                        System.out.println(points.size());
                    }
                    try {
                        Thread.sleep(60);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }

            }

        }).start();
    }

    @Override
    public void mousePressed(MouseEvent e) {}

    @Override
    public void mouseReleased(MouseEvent e) {}

    @Override
    public void mouseEntered(MouseEvent e) {}

    @Override
    public void mouseExited(MouseEvent e) {}

    public static void main(String[] args) {
        Curver curver = new Curver();
        curver.animationTicker.start();
    }
}

Comment: It might not be the main problem but it probably doesn't help that the points list is accessed from two threads without any synchronization. Try locking on the list with `synchronized (points) { ... }` while drawing and before adding points.
Comment: @Boann I understand what you are saying however this issue is repeatable without the thread in the mouse click handler - I only put it there because I was getting bored of 50 - 70 mouse clicks per debug. You will see if you move the random point logic out of the thread the problem remains.
Answer: g = (Graphics2D) window.getGraphics();

I didn't look at your code too closely but the forum recommendation is to not use the getGraphics() method to do painting.
Custom painting is done by overriding the paintComponent() method of a JPanel (or JComponent). Then you add the panel to the frame. Read the Swing tutorial for more information on custom painting.
Also, don't use "while (true)" logic. Swing will repaint as required. If you want animation of some kind then use a Swing Timer.

Path2D draw bug?


Pegar a localização do usuário sem usar GPS

Question: Olá. Estou desenvolvendo uma aplicação no android que é preciso notificar um grupo de usuários que se encontram numa determinada região. A única forma que eu conheço de pegar a localização do usuário é usando o GPS.
O problema é que para ativar/desativar o gps é preciso a aprovação do usuário, com isso, já não será possível notificar em uma determinada região.
Como que eu posso resolver este problema?, quais são as possíveis técnicas útil para esta situação?
Answer: O GPS não é o único meio para obter a localização do usuário. Ela pode ser obtida por WI-FI ou rede móvel(triangulação de antenas). No entanto, a sua precisão pode ser baixa para o que pretende.
A API para a obter a localização, em função da disponibilidade e dos requisitos indicados, usa o meio mais adequado.
Se estiver a utilizar o FusedLocationProviderClient os requisitos são indicados através de um objecto LocationRequest:
mLocationRequest = LocationRequest.create()
                .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                .setInterval(10 * 1000)        // 10 seconds, in milliseconds
                .setFastestInterval(1 * 1000); // 1 second, in milliseconds

O meio ou meios a utilizar para obter a localização são escolhidas em função do LocationRequest definido.
Um LocationRequest com uma prioridade de PRIORITY_LOW_POWER poderá não usar o GPS caso tenha disponível outra fonte que garanta a precisão requerida - cerca de 10 Km.
Assim sendo não há nada que você possa fazer. Se o usuário não permitir ligar o GPS a API não o poderá utilizar.
No entanto a localização continuará a poder ser obtida por outro meio disponível(se houver algum) mas com uma precisão menor.
Vejas estas perguntas para mais detalhe.

Como obter a localização atual do dispositivo android?
Habilitar GPS dentro da aplicação.
Gps ou triangulação de antenas - Como saber a precisão da localização?

Nota Qualquer que seja o meio utilizado a aplicação necessitará sempre da permissão ACCESS_FINE_LOCATION ou ACCESS_COARSE_LOCATION.


Zantaz's EAS exchange archive product doesn't integrate with Outlook in Windows 7

Question: I work at a place that uses Exchange with Outlook for mail, and they also use a product from Zantaz called "EAS" which does server-side archiving of old messages.  One of the artifacts of this archival is that email attachments are missing from the archived messages when viewed in Outlook.  EAS has a client tool that plugs into Outlook that enables easy retrieval of those archived messages and their attachments, but it doesn't seem to work when installed on Windows 7.  I have no direct evidence of this, other than that it simply doesn't work on my Windows 7 machine, and some of our network support staff seem to corroborate this.  The symptom is that Outlook seems to know nothing of the existence of this EAS app.  The EAS app also has a system tray icon which is there and offers some minimal functionality, but the real goodness is the Outlook integration, which I sorely miss.
So, my question is this: does anyone here know whether it's possible to coerce this EAS product into working correctly in Windows 7?
Answer: I know this thread is pretty old and the OP hasn't been back since April, but here's the answer:
EAS supports Windows 7 & Outlook 2010 as of the 6.3 release which was just a month ago.  There's a little goofiness still with 64 bit Outlook but we've seen it work on occasion.
Comment: Thanks!  I am not sure my employer has upgraded, but if not I will harass them to do so!
Answer: I had a similar problem on Vista.
when you install the client on Vista the EAS Addin is not applied to Outlook.
To get around this I manually copied the EAS Addin to the Addin folder.
This may be the same under Windows 7.
Comment: Thanks for the reply.  I am a little stuck, though, since I don't know which files are the addin.  I tried to go to the COM Addins doalog and add each of the EAS client dlls I could find, but I got error messages saying that they weren't actual outlook addins.  Can you tell me specifically what you did?
Answer: The file you're looking for is easext.ecf - just copy it to the office12/addins folder and all will be well.
Comment: I see this file is already in the Office12\ADDINS folder, but I still don't get any actual integration in outlook.
Answer: If you go to tools->Trust Center->Add Ins, and at the bottom, choose "manage: Exchange client addins, and then hit go.  Is EAS unchecked?  Also, under help->Disabled Items, is it listed there?
We often have issues where Outlook crashes, and then disabled EAS from running.


Having trouble install Python http package

Question: I am trying to install the Python http package into a virtual environment on my Mac so I can run the Simple HTTP Server but pip  complains that it can't import Request from request:
% pip install http
...
ImportError: cannot import name 'Request' from 'request' (/Users/me/.virtualenvs/base/lib/python3.7/site-packages/request/__init__.py)

I installed the request package initially but that didn't help.  Thinking that perhaps it needed requests instead, I installed that too to no avail.
Here is my virtual environment:
Package          Version
---------------- ---------
certifi          2019.9.11
chardet          3.0.4
get              2019.4.13
idna             2.8
pip              19.3
post             2019.4.13
powerline-status 2.7
psycopg2-binary  2.8.3
public           2019.4.13
query-string     2019.4.13
request          2019.4.13
requests         2.22.0
setuptools       41.1.0
urllib3          1.25.6
wheel            0.33.4

I'm running Python 3.7.4 inside a virtual environment built from virtualenv 16.6.2. on macOS Mojave.
Comment: From looking on [PyPI](https://pypi.org/project/http/#files), it seems that package hasn't been updated since Feb 11, 2012.  You might consider looking into something that has been updated more recently, such as [requests](https://pypi.org/project/requests/2.7.0/).
Answer: upgrade your pip with the below command and try again
python -m pip install –upgrade pip

If the above fails you can also try an earlier version for which it works
pip install --upgrade pip==9.0.3

The error could be because in the current pip, you have to pip install requests module first this in not taken care internally as the dependency is removed
Comment: The first thing I did after creating the virtual environment was to upgrade pip so I don't think that's the problem.
Comment: can you try with an earlier version of pip as i have mentioned
Comment: I could but it seems ridiculous to have to downgrade pip in order to install such a commonly-used package.  I'd prefer to understand (if possible) why this doesn't work with the current version of pip.  I'll try it, but I don't think we should have to do this.  But thanks for your suggestion, I'm not killing the messenger.  ;-)   UPDATE: Downgraded to pip 19.0.3 but that didn't help.  UPDATE: Oh geez, this http package is seven years old!  I'm going to look for something newer.
Answer: You should not have to install anything to run SimpleHTTPServer. http is in the standard libary.
Also note that SimpleHTTPServer is called http.server in Python 3.
Comment: Thank you, I'm glad to help :)


Subgroups of $\mathbb Z \times(\mathbb Z/n\mathbb Z)$

Question: So I am dealing with a problem from Dummit (specifically 2.1.7) and am having some issues. The  part of the problem in question is:

Prove the set of elements of the direct product $\mathbb{Z} \times (\mathbb{Z} / n \mathbb{Z})$ of infinite order together with the identity is not a subgroup of $\mathbb{Z} \times (\mathbb{Z} / n \mathbb{Z})$.

I am assuming this question is referring to addition as the binary operation for both sets. I know the proof basically involves showing that the product is not closed; however, do not all the elements of the integers have infinite order (except the identity)? In that case, the elements of infinite order together with the identity would form all of $\mathbb{Z} \times (\mathbb{Z} / n \mathbb{Z})$ would it not?
Thanks
Comment: The answer to your last question:  The element $(0,a)\in \mathbb{Z}\times\mathbb{Z}/n\mathbb{Z}$ has finite order, but is not the identity unless $a$ is.
Comment: Well this is embarrassing, I cannot believe I overlooked such a simple thing. Thanks guys.
Comment: @KFGauss Just FYI, if one of the answers settles your question satisfactorily you are encouraged to "accept" the answer. To do this, click on the grey check-mark to the left of it, which will then turn green. This rewards the user who answered your question and shows other users that the question has been answered.
Answer: Consider the elements $(1,[ 1])$ and $(-1, [ 0])$; they each have infinite order but their sum has finite order and is not the identity.
Comment: You need $n>2$ for this to work.
Comment: I see that now, thank you. I have changed it.
Answer: HINT: $\langle 1,1\rangle$ and $\langle -1,0\rangle$ both have infinite order.


What is the skeleton structure for a Drupal 7 module?

Question: What are the files necessary for building a Drupal 7 module?  What are the requirements for constructing a basic .info file? The essence of this question is to provide a skeleton for building a basic Drupal 7 module from scratch.
Comment: If you downvote the question please post a reason so it can be addressed.
Answer: Minimum files needed:
Normally, the minimum files needed for a module is the following:
sites/all/modules/{name of your module}

{your module}.info
{your module}.module

Or use the examples module:
The examples module on drupal.org provides you skeleton modules to develop custom/contrib modules. Just use that to copy and create your modules off of.
Check out the project page:

This project aims to provide high-quality, well-documented API
  examples for a broad range of Drupal core functionality.
(Interested in other, non-core examples?)
Developers can learn how to use a particular API quickly by
  experimenting with the examples, and adapt them for their own use.

Link to the git repository: http://drupalcode.org/project/examples.git/tree/refs/heads/7.x-1.x
Code from the examples module:
I've also just pasted in the code you could get from the examples module.
example.info file:
name = Examples For Developers
description = A variety of example code for you to learn from and hack upon.
package = Example modules
core = 7.x

example.module file:
<?php

/**
 * @file
 * This file serves as a stub file for the many Examples modules in the
 * @link http://drupal.org/project/examples Examples for Developers Project @endlink
 * which you can download and experiment with.
 *
 * One might say that examples.module is an example of documentation. However,
 * note that the example submodules define many doxygen groups, which may or
 * may not be a good strategy for other modules.
 */

/**
 * @defgroup examples Examples
 * @{
 * Well-documented API examples for a broad range of Drupal 7 core functionality.
 *
 * Developers can learn how to use a particular API quickly by experimenting
 * with the examples, and adapt them for their own use.
 *
 * Download the Examples for Developers Project (and participate with
 * submissions, bug reports, patches, and documentation) at
 * http://drupal.org/project/examples
 */

/**
 * Implements hook_help().
 */
function examples_help($path, $arg) {
  // re: http://drupal.org/node/767204
  // 5. We need a master group (Examples) that will be in a main
  // examples.module.
  // The examples.module should be mostly doxy comments that point to the other
  // examples.  It will also have a hook_help() explaining its purpose and how
  // to access the other examples.
}

/**
 * @} End of 'defgroup examples'.
 */

Answer: 1) Decide on a name for the module (for example: mymodule).
2) Create a folder inside sites/all/modules with your module's name.
3) Inside the folder create a mymodule.module file with a opening php tag (<?php) - the closing tag (?>) should be omitted.
4) Create a mymodule.info file (inside your module's folder) with the following 3 lines:
 name = Mymodule
 description = Description for the module
 core = 7.x

With this much you already have a Drupal 7 module that you can enable via the GUI (it doesn't do anything as long as you haven't added any functions/code inside the mymodule.module file). Note that all the mymodule instances used here should be replaced with your actual module's name and 'Description for the module' should be a proper description.


scipy.optimize.curve_fit a definite integral function with scipy.integrate.quad

Question: If I have a function that the independent variable is the upper limit of an definite integral of a mathematical model. This mathematical model has the parameters I want to do regression.
This mathematical model is nonlinear and can be complicated.

How can I solve this?
if the output of my function is then be processed, can it be curve_fit?

There is a simplified case
import scipy.optimize as sp
from scipy.integrate import quad
import numpy as np
number = 100

def f(x,a,b,c):
    return 500*a*x+b*c

def curvefit(d,a,b,c):
    return quad(f,0,d,args=(a,b,c))[0]

x_linear = np.linspace(0.001,0.006,number)
y_linear = 23.33*x_linear + 0.02*(np.random.random(number)-0.5)
parameter = sp.curve_fit(curvefit,x_linear,y_linear)

x and y _linear are number I made up.
d in curvefit() is now x_linear that is a list, and is the upper limit in quad().
The error shows ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
I know quad() requires upper limit to be float.
Comment: Welcome to Stack Overflow! You can [take the tour](http://stackoverflow.com/tour) first and learn [How to Ask a good question](http://stackoverflow.com/help/how-to-ask) and create a [Minimal, Complete, and Verifiable](http://stackoverflow.com/help/mcve) example. That makes it easier for us to help you.
Answer: The error is raised inside the function scipy.integrate.quad because d is a numpy.array and not a scalar. The function given to scipy.optimize.curve_fit take the independent variable (x_linear in your case) as first argument.
The quick and dirty fix is to modify curvefit to compute the definite integral for each value in d:
def curvefit(xs,a,b,c):
    return [quad(f,0,x,args=(a,b,c))[0] for x in xs]

Comment: Thank you so much for your answer. It reports an error of TypeError: 'numpy.float64' object is not iterable now. I have separate the codes alone and it did work well, but with the original line, scipy.optimize.curve_fit(curvefit,x_linear,y_linear), it shows this error.
Comment: Can you update the question with the code you actually run ?
Comment: Please ignore my previous comment, I made a silly mistake. It works well. Thank you!


Criando o arquivo "persistence.xml" JPA/Hibernate

Question: Gostaria de saber se existe um forma de configuração a criação(as configurações) do  persistence.xml no momento da criação do projeto.
Exemplo do aqruivo:

  <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
  <property name="hibernate.show_sql" value="true" />
  <property name="hibernate.format_sql" value="true" />

  <property name="hibernate.hbm2ddl.auto" value="create-drop" />

gostaria alterar a propriedade
<property name="hibernate.hbm2ddl.auto" value="create-drop" />

para
<property name="hibernate.hbm2ddl.auto" value="update" />

Apenas de value="create-drop" para value="update"
Comment: André, vc quer que todas as vezes que vc criar um novo projeto o valor da propriedade ``hibernate.hbm2ddl.auto`` seja ``update``?
Comment: Tiago, isso mesmo !
Answer: Pelo que entendi da sua pergunta é que se trata de automação.
Podemos automatizar o processo de criação de projetos de muitas formas, mas vou me concentrar e usar os recursos da ferramenta Maven. Assumirei que tomaremos um novo projeto do zero como modelo. A solução é bem mais ampla do que apenas a criação do arquivo de configuração do arquivo persistence.xml.
Construindo um Arquétipo [Balaji Varanasi, Sudha Belida -  2014, 49 p.]
1) Crie o projeto: seu-archetype-app-modelo
mvn archetype:generate -DarchetypeArtifactId=maven-archetype-webapp  \
-DgroupId=br.com.seu_archetype_app_modelo \
-DartifactId=seu-archetype-app-modelo \
-DgeneratePom=true \
-Dversion=1.0-SNAPSHOT

Acesse a pasta: seu-archetype-app-modelo.
2) Crie a pasta src/META-INF/ e o seu arquivo src/META-INF/persistence.xml, com as suas configurações.
Exemplo:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
    <persistence-unit name="jasper_book_chapter_4" transaction-type="JTA">
        <properties>

            <property name="hibernate.dialect"
                     value="org.hibernate.dialect.MySQL5InnoDBDialect" />
            <property name="hibernate.show_sql" value="true" />
            <property name="hibernate.format_sql" value="true" />

            <property name="hibernate.hbm2ddl.auto" value="update" />
        </properties>
    </persistence-unit>
</persistence>

3) Modifique o arquico pom.xml conforme sua necessidade. No exemplo aqui, definiremos o plugin: tomcat7-maven-plugin e a dependencia: Servlet 3.0.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>br.com.seu_archetype_app_modelo</groupId>
  <artifactId>seu-archetype-app-modelo</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>seu-archetype-app-modelo Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
     <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.0.1</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <build>
    <finalName>seu-archetype-app-modelo</finalName>
    <plugins>
      <plugin>
        <groupId>org.apache.tomcat.maven</groupId>
        <artifactId>tomcat7-maven-plugin</artifactId>
        <version>2.2</version>
      </plugin>
    </plugins>
  </build>
</project>

4) Crie as pastas test/java e test/resources na pasta src similar a estrutura da pasta src/main.
5) Criar o package br.com.seu_archetype_app_modelo.web.servlet (tem que ser o mesmo pacote do comando acima -DgroupId=br.com.seu_archetype_app_modelo) na pasta src/main/java.
Execute o seguinte comando:
$mkdir -p br/com/seu_archetype_app_modelo/web/servlet

NOTA 1: criar a mesma estrutura de pacotes na pasta src/test/java.
6) Criar o arquivo: AppStatusServlet.java no pacote: br.com.seu_archetype_app_modelo.web.servlet;
package br.com.seu_archetype_app_modelo.web.servlet;

import javax.servlet.annotation.WebServlet;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

@WebServlet("/status")
public class AppStatusServlet extends HttpServlet {
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws IOException {

    PrintWriter writer = response.getWriter();
    writer.println("OK");
    response.setStatus(response.SC_OK);

  }
}

Aqui neste passo já temos o projeto modelo pronto. Volte para pasta: seu-archetype-app-modelo.
7) Execute o comando:
mvn archetype:create-from-project

Após terminar o comando acima, será criada a seu-archetype-app-modelo/target/generated-sources/archetype.
8) Em qualquer outra pasta fora da seu-archetype-app-modelo, crie uma pasta seu-appweb-archetype, execute o comando:
$cd ~/projetos && mkdir seu-appweb-archetype

9) Copie seu-archetype-app-modelo/target/generated-sources/archetype para  ~/projetos/seu-appweb-archetype, execute o comanto:
$cp -Rf seu-archetype-app-modelo/target/generated-sources/archetype/ ~/projetos/seu-appweb-archetype

Depois de copiar, devemos remover a pasta: ~/projetos/seu-appweb-archetype/target.
10) Devemos editar o arquivo: ~/projetos/seu-appweb-archetype/src/main/resources/archetype-resources/pom.xml. Substituir "seu-archetype-app-modelo" para ${artifactId}.
11) Devemos editar o arquivo: ~/projetos/seu-appweb-archetype/src/main/resources/archetype-resources/src/main/java/AppStatusServlet.java. Subestituir "package ${package};" para "package ${package}.web.servlet;".
Pronto! Para finalizar! Acesse a pasta  ~/projetos/seu-appweb-archetype e execute:
mvn clean install

Usando o Archetype
No nosso caso o Archetype se encontra em ~/projetos/seu-appweb-archetype, então devemos acessar ~/projetos e executar o comando:
mvn archetype:generate -DarchetypeCatalog=local \
-DgroupId=br.com.nome_novo_projeto \
-DartifactId=nome-novo-projeto \
-Dversion=1.0-SNAPSHOT

Vai te solicitar que escolhar uma opção:
Choose archetype:
1: local -> br.com.seu_archetype_app_modelo:seu-archetype-app-modelo-archetype (seu-archetype-app-modelo-archetype)
Choose a number or apply filter (format: [groupId:]artifactId, case sensitive contains): :

Apenas digite 1
Execute os comandos:
cd nome-novo-projeto && mvn tomcat7:run

E depois acesso o link: http://localhost:8080/nome-novo-projeto/status

NOTA 2: Agora, temos o projeto Modelo: seu-archetype-app-modelo que foi criado com base no maven-archetype-webapp.
NOTA 3: Qualquer melhoria do projeto modelo (seu-archetype-app-modelo), devemos repetir os passos 7-11.
NOTA 4: Podes melhor a solução criando um script shell com os comandos, mas preferi realizar os passos manualmente para demosntrar melhor o funcionamento do uso de  Archetype do maven.

Referência:
[Gonçalves, Antonio -  2013], Apress, © 2013, Beginning Java EE 7 (Expert Voice in Java).
[Juneau, Josh -  2013], Apress, © 2013, Java EE 7 Recipes: A problem-Solution Approach – Proven Solutions for Java Enterprise Edition 7 Developement.
[Michal Cmil et al -  2014], Copyright © 2014 Packt Publishing, Java EE 7 Development with WildFly: Leverage the power of the WildFly application server from JBoss to develop modern Java EE 7 applications.
[Tim O'Brien et al -  2010], Copyright © 2010 Sonatype, Inc., The Maven Cookbook: A Sonatype Open Book Mountain View, CA.
[Balaji Varanasi, Sudha Belida -  2014], Copyright © 2014 by Balaji Varanasi and Sudha Belida, Introducing Maven

Criando o arquivo “persistence.xml” JPA/Hibernate


How do I find the source of the pointer error

Question: #include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "splitter.h"

#define FOUR_K 4096

SplitResult split_join(int argc, char *argv[])
{
    SplitResult rs = E_NO_ACTION;

    if (argc < 7)
    {
        return rs;
    }

    char* spiltOrJoin = argv[1];
    char* isSpiltOrJoin = spiltOrJoin;

    if (strcmp(isSpiltOrJoin, "-s") != 0 && strcmp(isSpiltOrJoin, "-j") != 0)
    {
        return rs;
    }

    if (strcmp(isSpiltOrJoin, "-s") == 0)
    {
        int smallChunkSize = atoi(argv[2]);

        const char* inputFileName = argv[6];
        const char* outputFilePrefix = argv[4];

        FILE* input = fopen(inputFileName, "rb");
        if (input != NULL)
        {
            fseek(input, 0, SEEK_END);
            long fileSize = ftell(input);
            fseek(input, 0, SEEK_SET);

            int numChunks = (fileSize + smallChunkSize - 1) / smallChunkSize;

            char buffer[FOUR_K];

            int numOfPiecesOfChunk = smallChunkSize / sizeof(buffer);

            for (int i = 0; i < numChunks; i++)
            {
                char outputFileName[256];
                snprintf(outputFileName, sizeof(outputFileName), "%s%s%d", outputFilePrefix, "000", i + 1);
                FILE* output = fopen(outputFileName, "wb");

                if (output == NULL)
                {
                    rs = E_BAD_DESTINATION;
                    fclose(input);
                    return rs;
                }

                char* chunkBuffer = (char*)malloc(FOUR_K);

                if (chunkBuffer == NULL)
                {
                    rs = E_NO_MEMORY;
                    fclose(input);
                    fclose(output);
                    return rs;
                }

                if (numOfPiecesOfChunk > 0)
                {
                    for (int j = 0; j < numOfPiecesOfChunk; j++)
                    {
                        size_t bytesRead = fread(chunkBuffer, 1, sizeof(buffer), input);
                        fwrite(chunkBuffer, 1, bytesRead, output);
                    }

                    int remainingBytesOfChunk = smallChunkSize - (sizeof(chunkBuffer) * numOfPiecesOfChunk);
                    size_t bytesRead = fread(chunkBuffer, 1, remainingBytesOfChunk, input);
                    fwrite(chunkBuffer, 1, bytesRead, output);
                }
                else
                {
                    size_t bytesRead = fread(chunkBuffer, 1, smallChunkSize, input);
                    fwrite(chunkBuffer, 1, bytesRead, output);
                }

                fclose(output); //Problem statement

                FILE* checkInput = fopen(outputFileName, "rb");

                if (checkInput == NULL)
                {
                    rs = E_BAD_DESTINATION;
                    free(chunkBuffer);
                    fclose(input);
                    return rs;
                }

                fseek(checkInput, 0, SEEK_END);
                long fileSize = ftell(checkInput);
                fseek(checkInput, 0, SEEK_SET);

                if (fileSize <= 0)
                {
                    rs = E_SMALL_SIZE;
                    free(chunkBuffer);
                    fclose(input);
                    fclose(checkInput);
                    return rs;
                }

                fclose(checkInput);

                free(chunkBuffer);
            }

            fclose(input);
            rs = E_SPLIT_SUCCESS;
        }
        else
        {
            rs = E_BAD_SOURCE;
            return rs;
        }
    }
    else
    {
        char* outputFile = argv[3];
        char* title = outputFile;
        int numOfFiles = argc - 5;
        FILE* output = fopen(title, "wb");

        if (output != NULL)
        {
            for (int i = 0; i < numOfFiles; i++)
            {
                FILE* chunkFile = fopen(argv[i + 5], "rb");

                if (chunkFile == NULL)
                {
                    rs = E_BAD_SOURCE;
                    return rs;
                }

                fseek(chunkFile, 0, SEEK_END);
                long fileSize = ftell(chunkFile);
                int sizeOfFile = (int)fileSize;
                fseek(chunkFile, 0, SEEK_SET);

                int numOfFilePieces = 0;

                char* buffer = (char*)malloc(FOUR_K);

                if (buffer == NULL)
                {
                    rs = E_NO_MEMORY;
                    fclose(chunkFile);
                    fclose(output);
                    return rs;
                }

                if (sizeOfFile > sizeof(buffer))
                {
                    numOfFilePieces = sizeOfFile / sizeof(buffer);
                }

                if (chunkFile != NULL) {
                    if (numOfFilePieces > 0)
                    {
                        for (int i = 0; i < numOfFilePieces; i++)
                        {
                            size_t bytesRead = fread(buffer, 1, sizeof(buffer), chunkFile);
                            fwrite(buffer, 1, bytesRead, output);
                        }

                        int remainingBytesOfChunk = sizeOfFile - (sizeof(buffer) * numOfFilePieces);
                        size_t bytesRead = fread(buffer, 1, remainingBytesOfChunk, chunkFile);
                        fwrite(buffer, 1, bytesRead, output);
                    }
                    else
                    {
                        size_t bytesRead = fread(buffer, 1, sizeOfFile, chunkFile);
                        fwrite(buffer, 1, bytesRead, output);
                    }

                    fclose(chunkFile);
                }

                free(buffer);
            }

            rs = E_JOIN_SUCCESS;

            fclose(output);
        }
        else if (output == NULL)
        {
            rs = E_BAD_DESTINATION;
            return rs;
        }
    }

    return rs;
}

I'm trying to write a C program that separates a file into smaller files and then joins smaller files into bigger ones. When I try and run the program, I get a munmap_chunk(): invalid pointer error that caused the line fclose(output)(indicated by problem statement). Why is this happening?
At first I thought that the malloc was causing issues with some variables having the same name but it wasn't.
Comment: @TedLyngmo Ah, perhaps I confused it with `char* chunkBuffer = (char*)malloc(FOUR_K);` So this `int remainingBytesOfChunk = smallChunkSize - (sizeof(chunkBuffer) * numOfPiecesOfChunk);` is probably incorrect. That's likely the line I originally intended to copy and instead grabbed the one a few lines above it.
Comment: As for how to find the source of memory corruption AddressSanitizer often works wonders.
Comment: @RetiredNinja Oh, I didn't get that far :-)
Comment: @user12645705  If you want debugging help, you need to provide us with code that we can compile. Please read about how to create a [mre].
Comment: `sizeof(buffer)` is the size of a pointer, probably 8, not the size of the allocation it points to. Try replacing everywhere you use that with `FOUR_K`.
Comment: @RetiredNinja `buffer` is a `char[FOUR_K]` so `sizeof(buffer)` is the same as `FOUR_K`.
Comment: see e.g. https://airbus-seclab.github.io/c-compiler-security/ for compiler options related to warnings and sanitizers
Comment: @TedLyngmo Looked again and found `char* buffer = (char*)malloc(FOUR_K);` and several uses of `sizeof(buffer)` in the bottom half of the code. This code would be better with no `malloc` at all.
Comment: `split_join` is an absurdly long function (196 lines!), and ironically you should split it up into a few smaller functions - which will help with debugging, as you can focus on making sure each individual function works as expected in isolation. Additionally note that using `ftell` to determine the the "size" of a file is unwise - see [here](https://stackoverflow.com/a/49122325/2505965). Use platform specific system calls (e.g., [`stat`](https://pubs.opengroup.org/onlinepubs/009696799/basedefs/sys/stat.h.html)) instead.
Answer: The "split" part of this code is 100 lines long (without comments). It's no wonder there's an invisible bug (pointed out by @RetiredNinja). Too much code and too many variables! Why does buffer[FOUR_K] sit unused while another buffer (chunkBuffer) is allocated off the heap? This makes no sense.
Below is an untested rewrite of the "split" part of the function. The "join" part is silly when cat would do the job.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stat.h> // new
#include "splitter.h"

SplitResult splitOne( FILE *ifp, size_t smallChunkSize, int idx, char *prefix ) {
    FILE *ofp = NULL;
    size_t want = smallChunkSize; // size of each output file

    char ofn[256];
    snprintf( ofn, sizeof(ofn), "%s%06d", prefix, idx );
    if( ( ofp = fopen( ofn, "wb" ) ) == NULL ) // start a new file
        return E_BAD_DESTINATION;

    while( want ) { // while batch incomplete
        char buf[FOUR_K];

        // the minimum of buffer size or remaining in batch
        size_t maxToRead = min( sizeof buf, want );
        size_t got = fread( buf, 1, maxToRead, ifp );
        // Should test for unexpected EOF
        // N.B. Last read of source likely to be < expected.

        fwrite( buf, 1, got, ofp ); // obvious

        want -= got; // reduce count remaining for this batch
    }
    fclose( ofp );

    return E_SPLIT_SUCCESS;
}

SplitResult split( int argc, char *argv[] ) {
    int smallChunkSize = atoi(argv[2]);
    char *ifn = argv[6];
    char *prefix = argv[4];

    if ( ( ifp = fopen( ifn, "rb" ) ) == NULL)
        return E_BAD_SOURCE;

    // Correct way to get a file's byte count
    struct stat finfo;
    if( fstat( fileno( ifp ), &finfo ) != 0 ) {
        fclose( ifp );
        return E_BAD_SOURCE;
    }

    int i = 1; // for unique output filenames
    size_t remain = finfo.st_size; // remain in source file
    SplitResult rs = E_NO_ACTION; // a default initial value

    while( remain // while source file not exhausted
    && ( rs = splitOne( ifp, smallChunkSize, i++, prefix ) ) == E_SPLIT_SUCCESS ) // want a batch of this size
        remain -= smallChunkSize; // shrink remaining in source file

    fclose( ifp );

    return rs;
}

SplitResult split_join( int argc, char *argv[] ) {
    if (argc < 7)
        return E_NO_ACTION;

    if( strcmp( split_join, "-s" ) == 0 ) return split( argc, argv );

    if( strcmp( split_join, "-j" ) == 0 ) return join( argc, argv ); // not done

    return E_NO_ACTION;
}

Each function in the call stack does its thing in preparation for calling the next function. Don't try to do everything in one monolith function.
(Please note: no dynamic allocation that can fail.)


Detecting multivariate outliers with Minimum covariance discriminant and mahalanobis distance

Question: I've read in some papers (such as this)  and CrossValidated questions (such as this, that people are using mahalanobis distance based on robust estimations of location and scatter using minimum covariance determinant method.
Usually, they run the fastMCD algorithm to obtain estimates for location and scatter, center the data using this robust estimate and calculate the mahalanobis distance, then they compare the distances to the chi2 distribution, and whatever would be unlikely under the chi2 is treated as an outlier.
However, if I follow the approach outlined in e.g. this answer or this sklearn tutorial, it would seem that if my robust location estimate is not equal to the sample mean, then the centered data won't be zero mean, in which case the comparison to chi2 distribution won't work, because all my observations will have distance centered around, say, 185.
Is my understanding correct, or am I missing something? If I am right, what would then be the right approach?
Comment: The comparison to chi-squared is a (very rough) approximate rule of thumb in the first place.  If you are concerned about its application in a particular setting, experiment!
Answer: Robust estimators are meant to work with populations that have some "good" data and a certain percentage of outliers. They are meant to be influenced very little or not at all by outliers.
Let's say you have a certain big enough proportion of observations from the multivariate normal distribution, and otherwise outliers. The mean will then be affected by the outliers; and to the extent that the MCD location estimator ignores the outliers, it will estimate the theoretical mean of the normal distribution in fact better than the arithmetic mean. The key here is that the "correct reference" for outlier detection is the mean of the non-outliers, not the overall mean! The MCD estimator estimates the former, the arithmetic mean the latter. If indeed the non-outliers are normal, and if indeed the outliers are placed so that the MCD can ignore them, the $\chi^2$-approximation will be fine for the non-outliers, and better for MCD than for the arithmetic mean.
If there are no outliers or the outliers are elliptically distributed, the MCD estimates the same location as the arithmetic mean, so they will be approximately the same, and $\chi^2$ will still be alright, even though the MCD will be somewhat less precise. The $\chi^2$-approximation will be slightly worse for clean normal data, but may be better than for the arithmetic mean if there are outliers, even if elliptically distributed. If the underlying distribution isn't normal and not even normal plus outliers, $\chi^2$ will be in trouble regardless of whether you use the arithmetic mean or the MCD.
Note though that the normal model can be seen as a calibration device for outlier identification rather than as an "assumption", which means that using the $\chi^2$ for outlier identification doesn't necessary require that normality holds (at least for the non-outliers), but rather that what it means to be "outlying" is defined relative to the normal distribution, the underlying truth being normal or not.


How would you prove that there is only a finite number of these primes?

Question: For the purpose of this question you can assume/consider number $1$ to be a prime number, but the final result should not depend on that, that is, that there is only a finite number of primes like the one I found.
I was trying by pure guesswork and help from Wolfram Alpha to find as large as I can a prime number such that the process of removing digit by digit gives us again prime numbers.
I found not so large a prime that does the job.
It is $12373$. If we remove rightmost $3$ we obtain $1237$, a prime. Then removal of $2$ gives us $137$, a prime. Then removal of $3$ gives us $17$, a prime, and finally, removal of $1$ gives us $7$, a prime.
It is so natural to expect that there is a finite number of primes like $12373$, because, it is to be expected that after some number of removals we will hit a multiple of $3$, for example.
And, the larger the prime from which we start, larger are the chances to obtain a composite number after some number of steps because the number of steps to arrive at a single-digit prime for larger primes is larger.
I also believe that the number of such primes is "so small" that all of them can be found with the help of a computer.

How would you prove that there is only a finite number of such primes (like $12373$)?

EDIT: With the help of Barry (in his comment under a deleted answer) we now know that these are called deletable primes. On this linked page it is written that it is conjectured that there are an infinite number of such primes, while I conjectured here that there are only finitely many.
Comment: See http://primes.utm.edu/glossary/xpage/DeletablePrime.html -- where it's said there are conjecturally *infinitely* many such primes.
Comment: I've tried this a bit and I found that 6166531357234211 satisfies this propriety.
Comment: @Rohan, that's not a duplicate, because the condition there is that deleting *any* digit leaves a prime.
Comment: It seems extremely difficult. At first glance, much harder than some problems that are still open.
Comment: Just a note: your number $12373$ has another sequence of primes. First remove the $2$ and you obtain $1373$. Then remove the first $3$ obtaining $173$. Now, no matter which number you remove you get a prime number. If you didn't remove the number $1$ in the previous step, remove it now (otherwise remove one of the two numbers) and you will end up with a prime number.
Comment: Possible duplicate of [Deleting any digit yields a prime... is there a name for this?](https://math.stackexchange.com/questions/33094/deleting-any-digit-yields-a-prime-is-there-a-name-for-this). See the first answer.
Comment: @BarryCipra Then what does this question deal with, sir?
Comment: A "deletable" prime is one where deleting *some* digit leaves a deletable prime.
Answer: Take two bags of numbers.  At the start, $A$ is empty and $B$ contains $2,3,5$ and $7$.
Repeat the following procedure:
Take a number, $p$, out of $B$ and put it in $A$.  Then try all the possible ways to add one digit to $p$; and put all the primes you get into $B$.
It is likely to continue forever.  The chance a number $N$ is prime, is around $\dfrac1{\ln N}$.  The number of ways to add a digit is around $10\log_{10}N=(10\log_{10}e)\ln N$, so the average number of primes you put into bag $B$ for each $p$ you take out is $10\log_{10}e\approx 4.34$
Comment: Vepir shows a greater increase than that.   Most of the candidates end in 1,3,7 or 9, so are more likely than most numbers to be prime.
Answer: Consider the following construction:
We can go in reverse, and start constructing such examples by starting with a number, and inserting digits into it. If we get a prime, we can continue to add more digits. If not, we can try to add the digit at another place.
Edit: If we are also considering leading zeroes that get erased after truncating the first digit, we get few extra examples that weren't included in the previous construction.
I've found all of the examples for first few digit cases ;

Or to be more specific, if we look at such numbers with
  $d=2,3,4,5,6\dots$ digits, we have:
$$20   ,118   ,734 ,4679, 31722\dots$$
such prime numbers among $d$ digit numbers.

It would seem that this sequence would continue growing implying that there are infinitely many such prime numbers. But this does not need to be the case.
You can see the lists of all examples split into lists based on their length (digits) :
$d = 2$
[11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 97]
$d = 3$
[101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 229, 233, 239, 241, 263, 269, 271, 283, 293, 307, 311, 313, 317, 331, 337, 347, 353, 359, 367, 373, 379, 383, 397, 401, 419, 421, 431, 433, 439, 443, 457, 461, 463, 467, 479, 487, 491, 503, 509, 523, 541, 547, 563, 569, 571, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 733, 739, 743, 751, 761, 769, 773, 797, 811, 823, 829, 839, 853, 859, 863, 883, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 997]
$d = 4$
[1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091, 1093, 1097, 1103, 1109, 1123, 1151, 1153, 1163, 1181, 1193, 1201, 1213, 1217, 1223, 1229, 1231, 1237, 1249, 1277, 1279, 1283, 1291, 1297, 1301, 1303, 1307, 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399, 1409, 1427, 1429, 1433, 1439, 1451, 1459, 1481, 1487, 1489, 1493, 1499, 1511, 1523, 1531, 1549, 1567, 1571, 1579, 1597, 1601, 1607, 1609, 1613, 1619, 1627, 1637, 1657, 1663, 1667, 1693, 1697, 1699, 1709, 1723, 1733, 1753, 1759, 1783, 1789, 1801, 1811, 1823, 1831, 1861, 1867, 1871, 1873, 1879, 1901, 1907, 1913, 1931, 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997, 1999, 2003, 2011, 2017, 2029, 2039, 2053, 2063, 2069, 2083, 2111, 2113, 2129, 2131, 2137, 2141, 2161, 2179, 2203, 2213, 2237, 2239, 2243, 2269, 2273, 2293, 2297, 2309, 2311, 2333, 2339, 2341, 2347, 2371, 2383, 2389, 2393, 2399, 2411, 2417, 2423, 2441, 2467, 2503, 2539, 2593, 2609, 2617, 2633, 2647, 2659, 2663, 2671, 2677, 2683, 2689, 2693, 2699, 2711, 2713, 2719, 2729, 2731, 2741, 2791, 2797, 2803, 2833, 2837, 2843, 2903, 2939, 2953, 2963, 2969, 2971, 3001, 3011, 3019, 3023, 3037, 3041, 3061, 3067, 3079, 3083, 3109, 3119, 3121, 3137, 3163, 3167, 3181, 3187, 3191, 3217, 3229, 3253, 3259, 3271, 3301, 3307, 3313, 3319, 3331, 3347, 3359, 3361, 3371, 3373, 3391, 3407, 3413, 3433, 3457, 3461, 3463, 3467, 3491, 3511, 3517, 3529, 3533, 3539, 3541, 3547, 3559, 3571, 3583, 3593, 3607, 3613, 3617, 3631, 3637, 3643, 3659, 3671, 3673, 3677, 3691, 3697, 3701, 3709, 3719, 3733, 3739, 3761, 3767, 3769, 3779, 3793, 3797, 3803, 3823, 3833, 3847, 3853, 3863, 3907, 3911, 3917, 3919, 3929, 3931, 3947, 3967, 4001, 4003, 4007, 4013, 4019, 4021, 4051, 4057, 4073, 4079, 4091, 4127, 4129, 4133, 4139, 4157, 4159, 4201, 4211, 4217, 4219, 4229, 4231, 4241, 4243, 4261, 4271, 4283, 4337, 4339, 4349, 4357, 4363, 4373, 4391, 4397, 4421, 4423, 4457, 4463, 4483, 4493, 4507, 4517, 4519, 4523, 4547, 4561, 4567, 4591, 4597, 4603, 4621, 4637, 4639, 4643, 4651, 4657, 4663, 4673, 4679, 4691, 4721, 4729, 4733, 4751, 4759, 4787, 4789, 4793, 4799, 4801, 4817, 4831, 4861, 4871, 4877, 4919, 4931, 4933, 4937, 4943, 4951, 4957, 4967, 4987, 5003, 5009, 5011, 5023, 5039, 5059, 5099, 5101, 5107, 5113, 5147, 5167, 5171, 5179, 5197, 5209, 5231, 5233, 5237, 5273, 5303, 5309, 5323, 5347, 5393, 5399, 5407, 5413, 5417, 5419, 5431, 5437, 5441, 5443, 5471, 5477, 5479, 5503, 5563, 5569, 5623, 5639, 5641, 5647, 5653, 5659, 5669, 5683, 5689, 5693, 5701, 5711, 5717, 5741, 5743, 5791, 5839, 5869, 5903, 5923, 5939, 5953, 6007, 6011, 6029, 6037, 6043, 6047, 6053, 6067, 6073, 6079, 6091, 6101, 6113, 6131, 6133, 6143, 6151, 6163, 6173, 6197, 6199, 6211, 6217, 6229, 6247, 6263, 6269, 6271, 6277, 6301, 6311, 6317, 6337, 6343, 6353, 6359, 6361, 6367, 6373, 6379, 6397, 6421, 6427, 6451, 6473, 6481, 6491, 6529, 6547, 6553, 6563, 6569, 6571, 6577, 6599, 6607, 6619, 6653, 6659, 6661, 6673, 6691, 6701, 6703, 6709, 6719, 6733, 6737, 6761, 6763, 6779, 6791, 6793, 6803, 6823, 6829, 6833, 6841, 6863, 6883, 6907, 6911, 6917, 6947, 6959, 6961, 6967, 6971, 6977, 6983, 6991, 6997, 7001, 7013, 7019, 7039, 7043, 7069, 7079, 7103, 7109, 7127, 7129, 7151, 7159, 7193, 7211, 7219, 7229, 7243, 7283, 7297, 7307, 7309, 7331, 7333, 7349, 7351, 7369, 7393, 7433, 7451, 7457, 7487, 7517, 7523, 7541, 7547, 7561, 7573, 7591, 7607, 7621, 7639, 7643, 7649, 7669, 7673, 7681, 7691, 7699, 7703, 7723, 7753, 7793, 7823, 7829, 7853, 7873, 7883, 7901, 7907, 7919, 7927, 7933, 7937, 7951, 8011, 8017, 8039, 8053, 8059, 8101, 8111, 8117, 8123, 8161, 8167, 8171, 8179, 8191, 8209, 8219, 8231, 8233, 8237, 8243, 8263, 8269, 8273, 8291, 8293, 8297, 8311, 8317, 8329, 8353, 8363, 8369, 8389, 8419, 8423, 8429, 8431, 8443, 8461, 8467, 8513, 8537, 8539, 8543, 8563, 8573, 8597, 8599, 8623, 8629, 8641, 8647, 8663, 8677, 8693, 8719, 8753, 8761, 8783, 8803, 8831, 8837, 8839, 8863, 8893, 8923, 8929, 8941, 8963, 8971, 9001, 9007, 9011, 9013, 9029, 9041, 9043, 9059, 9067, 9103, 9109, 9127, 9137, 9151, 9157, 9161, 9173, 9181, 9199, 9209, 9239, 9241, 9277, 9283, 9293, 9311, 9319, 9337, 9341, 9371, 9377, 9397, 9413, 9419, 9421, 9431, 9433, 9437, 9439, 9461, 9463, 9467, 9473, 9479, 9491, 9497, 9511, 9533, 9539, 9547, 9601, 9613, 9619, 9629, 9631, 9643, 9661, 9677, 9679, 9697, 9719, 9721, 9733, 9739, 9743, 9767, 9769, 9781, 9787, 9791, 9803, 9811, 9829, 9833, 9839, 9859, 9871, 9883, 9907, 9929, 9941, 9967, 9973]
I can upload lists for $d\ge5$ if you want.

This does not answer your question as for an actual proof (disproof), this is still an open problem as Barry Cipra wrote in the comments.
Michael in his answer provides a reasoning of why this conjecture is likely to be true.
Comment: It occurs to me your procedure might miss some deletable primes.  E.g., suppose $a0bc$ is prime with $bc$ deletable, but $abc$, $a0c$, and $a0b$ are *not* prime.  Then you won't be able to construct $a0bc$, unless you (temporarily) consider $0bc$ to be a three-digit prime. And even if there's no such four-digit example, there could conceivably be one with more digits.
Comment: Another observation: because the OP here is allowing $1$ as a starting point, the list here includes primes such as $109$ that are not in the sequence of deletable primes at http://oeis.org/A080608 -- but it's possible the two lists *do* agree beyond some number of digits.
Comment: Nice work, thank you. Now I do not know which side to choose, that there are finitely or infinitely many of them.
Comment: I ja sam iz Hrvatske. Haha. :)
Comment: @AntoinePalAdeen Haven't noticed. Svijet je malen :)
Comment: Are you a student at PMF?
Comment: You don't need to choose any side, thats most honest approach until either side is actually proven.
Comment: @AntoinePalAdeen Just started first year at Department of Mathematics. (You?) I think we should move this conversation to a chat if it is to continue. :)
Comment: Move it if you want to move it, it depends do you want or not.
Comment: @Sil But suppose that I want to prove either finiteness or infiniteness. Then my beliefs about which "side" is right are important.
Comment: I do not know how to move it. @Vepir
Comment: @BarryCipra Oh, yes, you are right. We need to also include the invisible leading $0$'s if you consider that case. Then, for $d=4$, we missed: $5011,3041,3061,9013,2017,8017,3019,3023,6029,9043,2053,4073,9059,3001,9001,2003,4003,4007$ . And looks like $2017$ is there too, coincidence? I'll edit my post with those examples also, thanks for noticing.


como transformar uma saída dput em um data.frame novamente no R?

Question: Eu tenho um data.frame e gostaria de armazena-lo no formato texto dentro do meu docx. Verifiquei que a função dput pode fazer isso muito bem. Porém gostaria de saber como faço para converter essa saída do dput novamente em um data.frame legivel pelo R.
Veja o meu exemplo para o data.frame saude:

aplicando o dput à suade
dput(saude)

minha saída é:

structure(list(Diastolic_BP_mmHg = c(0.93, -0.43, 0.58, 0.19,
-2.05, -0.43, 1.39, -0.7, 0.81, -0.31), Sistolic_BP_mmHg = c(0.82,
-0.05, 0.46, 0.82, -1.98, -0.37, 1.21, -1.19, 0.62, -0.33), Peso_Kg = c(0.21,
1.43, 1.28, -0.55, 0.06, -0.85, -1.46, -0.39, -0.85, 1.12), Altura_cm = c(0.36,
1.6, 0.36, -0.57, 0.51, -1.19, -0.88, -0.73, -0.88, 1.44)), class = c("tbl_df",  "tbl", "data.frame"), row.names = c(NA, -10L))

Como eu poderia converter essa saída novamente no data.frame acima?
Comment: Veja `?dget`. Para recriar o df da pergunta basta atribuir o valor do comando a uma variável, que passa a ser o nome do objeto (um df).
Answer: Eu encontrei a resposta muito simples em: https://lhmet.github.io/adar-ebook/exportando-e-recuperando-objetos-do-r-no-formato-textual.html
basta somente atribuir uma variável ao texto de saída:
saude_df<-structure(list(Diastolic_BP_mmHg = c(0.93, -0.43, 0.58, 0.19, -2.05, -0.43, 1.39, -0.7, 0.81, -0.31), Sistolic_BP_mmHg = c(0.82, -0.05, 0.46, 0.82, -1.98, -0.37, 1.21, -1.19, 0.62, -0.33), Peso_Kg = c(0.21, 1.43, 1.28, -0.55, 0.06, -0.85, -1.46, -0.39, -0.85, 1.12), Altura_cm = c(0.36, 1.6, 0.36, -0.57, 0.51, -1.19, -0.88, -0.73, -0.88, 1.44)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -10L))

saude_df
Desta forma o texto volta a organizar as informações de forma inteleigível.


Proving that $\exists t \in \mathbb R: ||t u|| = d(0,K)$

Question: Let's consider $\mathbb R^n$ with the usual inner product $\cdot$, norm $||\cdot||$ and distance $d(\cdot,\cdot)$ induced by that inner product.
If $X \subseteq \mathbb R^n$ and $a \in \mathbb R^n$ we can define $d(a,X) := \inf \{d(a,x) : x \in X\}$.
Let $K$ be a Hyperplane, meaning that $\exists p \in \mathbb R^n$, and $\exists S \leq \mathbb R^n$ with $\dim S = n - 1$ such that:
$$K = \{p\}  + S$$
Let $u \in \mathbb R^n$ such that $u$ spans $S^\perp$, so $\{u\}$ is a basis of $S^\perp$.
Then:
$$\exists t \in \mathbb R: ||t u|| = d(0,K)$$

I came up with this by observing some specific cases in $\Bbb R^2$ and $\Bbb R^3$ and this was my attempt of generalizing. It's easy to intuitively understand why this is true in $\Bbb R^2$ and $\Bbb R^3$ but I'm not being able to prove this for any $\Bbb R^n$. So my questions are:

Is this even true for $\Bbb R^n$?
If so, how can I prove this?
Answer: Well, $d(0,K) \le \|p\|$ since certainly $p \in K$. Therefore we can take the infimum over $K \cap \overline{B}(0,p)$ without changing anything:
$$d(0,K) = \inf\{\|x\|:x \in K\} = \inf\{\|x\|:x \in K \cap \overline{B}(0,p)\}$$
and the latter is an infimum of a continuous function over a compact set so it is attained. Hence let $x_0 \in K \cap \overline{B}(0,p)$ be such that $d(0,K) = \|x_0\|$.
Now if we define $t := \frac{\|x_0\|}{\|u\|} \in \Bbb{R}$ then
$$\|tu\| = t\|u\| = \frac{\|x_0\|}{\|u\|}\|u\| = \|x_0\| = d(0,K).$$
Comment: @EduardoMagalhães Sure, here is a different proof. Notice that we can always write $K = q+S$ for some $q \in S^\perp$. Indeed, let $S = \{v\}^\perp$ where $v \in \Bbb{R}^n$ is a unit vector. Then $$K = p+S = \underbrace{\langle p,v\rangle v}_{\perp S} + \underbrace{(p-\langle p,v\rangle v)}_{\perp v \implies \in S} + S = q+S $$
with $q := \langle p,v\rangle v$. Now by Pythagoras we have $$d(0,K)^2 = \inf\{\|q+x\|^2 : x \in S\} = \inf\{\|q\|^2 + \|x\|^2 : x \in S\} = \|q\|^2$$
since $0 \in S$. Therefore $d(0,K) = \|q\|$ so we can set $t := \frac{\|q\|}{\|u\|}$.
Comment: Nice proof, loved how you used topology to solve this problem. but I was trying to find one that only uses linear algebra concepts.


Remove url .php extension and parameters of get request?

Question: My URL is:
https://example.com/detail.php?id=56&subcat=11

I need like this:
https://example.com/detail/56/11

Using .htaccess file i am not able to remove the parameter names (id, subcat) and question mark(?). I have removed only .PHP extension.
Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

## don't touch /forum URIs
RewriteRule ^forums/ - [L,NC]

RewriteCond %{THE_REQUEST} \s/+products(?:\.php)?\?id=([0-9]+) [NC]
RewriteRule ^ products/%1? [R,L]

RewriteRule ^products/([0-9]+)/?$ products.php?id=$1 [L,QSA]

## hide .php extension snippet
# To externally redirect /dir/foo.php to /dir/foo
RewriteCond %{THE_REQUEST} \s([^.]+)\.php [NC]
RewriteRule ^ %1 [R,L]

# To internally forward /dir/foo to /dir/foo.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+?)/?$ $1.php [L]

Thank you.
Comment: This has nothing to do with JS or jQuery. It's an Apache/htaccess configuration issue, so I've re-tagged it for you
Comment: you want to turn the first URL into the second one?
Comment: Possible duplicate of [Simple mod rewrite query string but still failed](https://stackoverflow.com/questions/36109639/simple-mod-rewrite-query-string-but-still-failed)
Answer: Just place the following into your .htaccess file (and make sure that mod_rewrite is enabled):
RewriteEngine on
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^([^.]+)$ $1.php [NC,L]
RewriteRule ^index.php/([^/]+)/?([^/]*) /index.php?id=$1&subcat=$2 [NC]

Answer: This is a bit complex problem. You won't achive it only by .htaccess. You have to parse variables from url to array and make it accessible from php code. In this link in section 'Using php' there is some example how to do this.
Because you don't want to use "normal" link, we have to handle requests for pages and manually parse them. First define in you htaccess redirect:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?path=$1 [NC,L,QSA]

Then create index.php which will handle redirects.
// your available sites
$sites = [ 'detail' ];

$path = $_GET['path'];
$params = explode( "/", $path );
$site = array_shift($params);

if( in_array( $site, $sites ) ){
    include($site.".php");
}

Now in detail.php you can use $params and you get array with you values. So our http://example.com/detail/56/1 goes like http://example.com/index.php?path=detail/56/1. With this aproach we will write our logic in details.php and we can use $params, which equals Array ( [0] => 56 [1] => 1 ).
Your link could be more readable in code if you change it to /detail/id/56/subcat/11. Just add this before check in_array
$x = [];
for( $i=0; $i<count($params); $i+=2 )
    $x[$params[$i]] = $params[$i+1];
$params = $x;

This is only simple example of idea. Better use some framework with that routing, like symphony.
Answer: you can use following .htaccess sample file
Note : replace filename1 and filename2 with your php file names
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(filename1.*)$ filename1.php?path=$1 [NC,L,QSA]
RewriteRule ^(filename2.*)$ filename2.php?path=$1 [NC,L,QSA]


PHP: get only part of a match from a regular expression

Question: I'm trying to get some URL's from a webpage using PHP regular expressions.
I'm doing this:
preg_match_all('/"r"><a href="http:.*?"/i',$Rec_Data, $stuff );

This works in returning the url's however I also get code I don't want:
"r"><a href="http://www.cbsnews.com/stories/2002/12/03/politics/main531460.shtml"

I can't get rid of the "r" and the "a" tag. I need it so I don't match URL's I don't want. How do I get only the part that is matched by ".*?" ?
Comment: possible duplicate of [Extract all urls Href php](http://stackoverflow.com/questions/5262682/extract-all-urls-href-php)
Comment: possible duplicate of [Regular Expression for grabbing the href attribute of an a element](http://stackoverflow.com/questions/3820666/regular-expression-for-grabbing-the-href-attribute-of-an-a-element/3820783#3820783)
Comment: possible duplicate of [preg_match all a href](http://stackoverflow.com/questions/1519696/preg-match-all-a-href)
Answer: Use a capturing group and use the second element in the result:
preg_match_all('/"r"><a href="(http:.*?)"/i',$Rec_Data, $stuff );

See it working online: ideone
Also, you might want to consider using an HTML parser to parse HTML, instead of a regular expression.
Comment: @SrgHartman: What do you mean by "doesn't work"? I posted a link to an online demo where you can see that it works...
Comment: @MarkByers: my bad, it actually works. However I get two arrays. That looks like a waste of resources. Is it possible to get the regex engine to return only the match I want?


How to define the multiplier range for variance test based outliers detection algorithm?

Question: I have a variance test based outliers detection algorithm. The algorithm is exposed with a visual application where the user can configure its parameters namely the multiplier.
The question is what is the range of values for the algorithm multiplier?
the algorithm basically is calculating the mean and standard deviation (sigma) of the data set and then comparing the dataset elements to the upper and lower bounds to flag an element as an outlier or not.
multiplier <- 2.3;
upper_bound <- mean + multiplier * sigma;
lower_bound <- mean - multiplier * sigma;

the evolution of the two functions upper_bound (red) and lower_bound(blue) with the multiplier values is as follows:

But this graph doesn't give any clue on what range to define. Do you have any idea how to define this range?
Comment: Do you know anything about the shape of the distribution of the $Y$-values?
Comment: actually, I don't have this luxury. The application should work for any distribution.
Comment: Then you might go with Chebychev's inequality (the finite sample version) http://en.wikipedia.org/wiki/Chebyshev%27s_inequality It gives bounds for the probability to deviate more than $k$ standard deviations from the mean. If you know mean and standard deviation, you can derive the range based on this
Answer: To find the outliers, you cannot use the distance of an observation to a model through a rule such as:
$$\frac{|\hat{\mu}-x_i|}{\times \hat{\sigma}},\;i=1,\ldots,n$$
if your estimates of $(\hat{\mu},\hat{\sigma})$ are the classical ones (the usual mean/standard deviation) because the fitting procedure you use to obtain them is itself liable to being pulled towards the outliers (this is called the masking effect).
One simple way to reliably detect outliers however is to use the general idea you suggested (distance from fit) but replacing the classical estimators by robust ones much less susceptible to be swayed by outliers. Below I present a general illustration of the idea. If you give more information about your specific problem I can append my answer to address the particulars of your situation.
An illustration: consider the following 20 observations
drawn from a $\mathcal{N}(0,1)$ (rounded to the second
digit):
x<-c(-2.21,-1.84,-.95,-.91,-.36,-.19,-.11,-.1,.18,
.3,.31,.43,.51,.64,.67,.72,1.22,1.35,8.1,17.6)

(the last two really ought to be .81 and 1.76 but have
 been accidentally misstyped).
Using a outlier detection rule based on comparing the statistic
$$\frac{|x_i-\text{ave}(x_i)|}{\text{sd}(x_i)}$$
to the quantiles of a normal distribution would never
lead you to suspect that 8.1 is an outlier, leading you
to estimate the $\text{sd}$ of the 'trimmed' series to be
 2 (for comparison the raw, e.g. untrimmed, estimate of
 $\text{sd}$ is  4.35).
Had you used a robust statistic instead:
$$\frac{|x_i-\text{med}(x_i)|}{\text{mad}(x_i)}$$
and comparing the resulting robust $z$-scores to the
choosen quantiles of a candidate distribution (typically the
standard normal if you can assume the $x_i$'s to be
symetrically distributed) you would have correctly
 the last two observations as outliers (and correctly
estimated the $\text{sd}$ of the trimmed series to be
0.96).
Comment: In my case, I cannot assume that my distribution is normal or is not, and the outlier detection should work for all cases. In fact, I only have an idea about what data set to run the outlier detection on just after the user interaction. The variance test was the most general idea that doesn't require me to have previous knowledge of the distribution of my data. What I understand from your explanation is that I should replace comparing the distance with comparing the statistic, is that what you mean? and what is "med" and "mad"
Comment: med is median and mad is the median absolute deviation. Even then, you will find the the quantile of the normal are tilted to the conservative side (for symmetric distributions)


c# create system tray application that remains in tray after application closed

Question:  private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
    {
        ShowInTaskbar = true;
        this.WindowState = FormWindowState.Normal;

    }

//Its not working to show my application icon in tray on application Exit.
Comment: So you want the icon to stay there in the tray even after application closed. fine how you are closing the application?
Comment: Yes, and i am using the Application.Exit ();
Comment: try to close the forms instead so that your Icon will stay there in the tray
Comment: So what i will use instead of Application.Exit()  ?
Comment: What do you expect to happen when the user clicks the icon after your application has exited? Your application isn't running, so there is nobody to respond to the click.
Comment: You seem to misunderstand how other applications work. Either you keep the application running or you create a seconds (hidden) application that provides the tray icon. See RasmusW answer for the first approach.
Answer: When you exit the application, the tray icon goes away.
Also, when you close the last window, the application exits.
You want to minimize and hide the main window instead of exiting. You can do this with Hide(); somewhere in your Windows Forms code. Then, when the user wants to show the form, just run form.Show().
Comment: As I said: When you exit the application, the icon goes away - there is no longer a running process. You can make a _different_ application which acts like a launcher of sorts. But then that application needs to run.
Comment: Nope, i want that my application icon will stay in the tray even i closed the application.


Remove directory from a Git repository, and from history, without deleting it from the local filesystem

Question: I'm still learning Git, and I did a dumb thing by adding a directory full of many large files to my repo. Now, I would like to remove the directory from Git. I know how to use gitignore, and i know how to remove a file from git but not from the local filesystem but I'd like to take the directory (and its contents) out of the history of the repository as well. I see a few similar questions about this on here, but none of them seem specific to my situation. In particular, I would like to keep the directory untouched on my local filesystem.
I should note that, as a new repository, I have yet to share this with other users, so I'm unconcerned with anything that relates to other users at this point.
Comment: There are already questions (with answers) on Stack Overflow about how to remove history from Git repositories, you could check those out and adapt them to your situation. Screw it, digging for canonicals takes too long, I'll just answer this, and maybe someone can mark it as a duplicate later.
Comment: The answer to [this question](http://stackoverflow.com/questions/21230090/remove-a-deleted-folder-form-git-history) for example: will it work for a directory that has been removed but not deleted?
Comment: How many commits ago did you add this directory?
Comment: The directory was added 4 commits ago but some of the files were moved into that directory previous to that.
Comment: Did you want to completely erase the history of those files from before they ere moved into the directory too, or just all of their history afterwards?
Comment: The files are all quite large so I think the best strategy would be to completely erase the history of the files, even before they entered the directory.
Comment: I would handle this by first removing the history of that directory, and then removing the history of the files from before they were moved to that directory. Are they binary files?
Comment: yes, nearly all of them are binary files of various types.
Comment: Right, I guess you've now discovered that Git isn't really designed for versioning large, frequently changing binaries, right?
Comment: Yes, unfortunately I seem to be learning that the hard way and I hope the answer to this question will help me to ammend my ways :)
Comment: Please consider upvoting my answer as well if you found it helpful.
Answer: There are several ways to remove file and directory history from Git:

git reset with an appropriate mode (hard, soft, mixed, etc).
Interactive rebasing.
Using git filter-branch.

There could possibly be more methods (I would need to think more about it). Which one you use depends on your situation.
Assuming that you added the directory to your Git history in the last, say, 15 commits, you could just use an interactive rebase. See

Official Linux Kernel documentation for git rebase
Pro Git § 6.4 Git Tools - Rewriting History

If the directory was added many many commits ago (like more than 100), than git filter-branch would probably be a better option that will run faster and be more convenient to use than an interactive rebase over a hundred or more commits.
Make sure to make a copy of the directory and its contents and save it temporarily outside of the Git project directory, before attempting to remove it from the repository history. Then move the directory back afterwards.


Banjo 5th string as a melody note

Question: I'm looking Wildwood Flower in Wayne Erbsen's Clawhammer Banjo for the Complete Ignoramus.
On line one, he specifies that the G in the first line be played with the thumb on the 5th string. This is what the tablature looks like from the book:

Why not play that melody note on the 1st string (at the 5th fret)?
Comment: I should note that it *does* sound better this way when I play it, but I'm a beginner and I would assume that has more to do with my technique.
Answer: The open 5th string sounds better because it can ring out while you play the next notes. That string acts as a drone (note that the piece is in G major). If you played that note on the 5th fret of the 1st string, the note would end immediately because the next note would be on the same string. Also note that if you played that G on the 1st string, your left hand would need to move much more than if you play the melody as suggested.

Banjo 5th string as a melody note


Does the order of entries/record types matter in NSD/BIND zone config files?

Question: I'm trying to streamline the addition of DNS records to an NSD install. It looks like it uses the same syntax as BIND so this question may be relevant to either.
It seems like the convention I'm seeing in the current zone file is to separate the SOA, MX, NS, A, CNAME, TXT  records into their own stanzas in the zone configuration file, in our case with a semicolon separating one stanza from the next.
I believe this is just for aesthetics and the only real requirement is that the SOA is the first record, the order after that shouldn't matter.
I'm wondering if anyone else has can validate that assumption
Comment: That is a really good question which would make for a wonderful little test. I'm interested in both bind and windows dns test results for this. As soon as I get some time I'll set it up and post the results, if nobody beats me to it that is.
Answer: The order of the resource records (after the mandatory entries) never appeared to functionally matter in any of the dns:es I have come across. When there is a dependency, such as a cname record linking to an a record, this is solved through separating resolution into two queries: one recieving the cname and the other recieving the a record.
As bind and nsd loads the entire zone files into memory at startup, the order does not seem to matter for the resolution performance either.
However, zone file size is a factor both for time to fully load and for query response time:
https://www.icann.org/en/about/staff/security/ssr/root-zone-augementation-analysis-17sep09-en.pdf
Comment: Ditto here, I tried both ways with NSD and it works with either. Thanks!
Answer: IIRC  RFC 1033 one of the older DNS RFC's (the DNS Wikipedia page has a nice list) states that a SOA record denotes the start of a new zone, but that order of the records in a zone doesn't need to be preserved.
So it's mostly aesthetics and convention. Although tooling may depend on those conventions.
Comment: That's what I'm thinking, According to: http://www.zytrax.com/books/dns/ch8/

The $TTL directive should be present and appear before the first RR (RFC 2308 implemented in BIND 9).
The first Resource Record must be the SOA (Start of Authority) record.

Though I haven't read through those RFCs yet to see if they say anything else
Comment: I'm thinking that whilst there isn't a functional difference, there might well be a performance penalty for placing a record late rather than early in a large zone file. It was a while since I worked with bind and can't remember how the caching works, i.e. if it loads the whole zone into ram or if it caches by request like windows. For windows dns I'm quite sure it doesn't load everything into ram or the cache would serve no function.
Comment: I doubt bind is written that badly. They likely use a - or are written by programmable challenged people - sort of hashtable / dictionary structure, and do not do a linear search.
Comment: @TomTom I think that's probably correct and that the text file format is parsed and translated into a binary record format


$|n^\alpha \sin n| \to \infty$ for some $\alpha$?

Question: Does there exist $\alpha>0$ such that $\lim\limits_{n \to \infty} |n^\alpha \sin n| = \infty$ ?
Comment: What are your thoughts?
Comment: It is considered good practice to say what you have tried doing so far, and this will let people help you and give relevant answers.
Answer: $|n^\alpha sinn|=n^\alpha |sinn|$. Since $lim|sinn|$ has many closure points, (the set of closure points is the segment [0,1]), the sequence $|n^\alpha sinn|$ diverges too. But it does not tend to infinity! It has many closure points. So there is no such $\alpha$ to fill in that equation.
Comment: The question states: Does there exist $\alpha >0$.
Comment: Oops, you're right...hehe. Anyway, in the first line I think you mean that the sequence $\;\{\sin n\}\;$ has many closure points. This though must be proven, and perhaps the OP's doubt is this.


Simulating the outcome of X number of random trials

Question: Let's say I want to flip a coin a billion times and count how many heads I get. But I don't have time to actually flip a coin a billion times.
Assuming I have a random number generator than can generate a number between 0 and 1, is there a technique I can use to simulate the outcome of 1 billion random coin tosses, such that it's statistically equivalent to actually doing a billion random coin tosses?
I have been thinking about this a lot and Googling, but haven't come up with a solution. It feels to me like we could plot a curve like this (please forgive my horrible sketch):

Where x is the chance of getting fewer than f(x) heads.
So when x is 0 (0% chance), f(x) is also 0. There's a 0% chance of getting fewer than 0 heads.
When x is 0.5 (50% chance), f(x) is half a billion. There's a 50% chance of getting fewer than half a billion heads.
When x is 1 (100% chance), f(x) is a billion (or a billion and one, I suppose). There's a 100% chance of getting fewer than a billion heads.
Moving right from 0 or left from 1, f(x) very quickly goes to very close to half a billion. This reflects how it would be extraordinarily unlikely to get, say, 400 million or 600 million heads.
My thinking is that if I had a correct equation for f(x), then I could generate a random number between 0 and 1, calculate f(x), and that would be the number of heads from my one billion "trials".
Would this concept actually work and is there a known approach (even if completely different from what I'm thinking) for solving this problem?
Comment: Hi @aurast, hint - check out the binomial distribution https://en.m.wikipedia.org/wiki/Binomial_distribution. In particular, the probability mass function (PMF).
Answer: What you apparently have in mind is known as the inverse transform sampling method. This is based on the cumulative distribution function (cdf) of the distribution you want to generate. This is what you call f, and in a graph as a standard the potential outcomes would be on the x- and the cdf values on the y-axis. You did it the other way round, which isn't much of a problem; I just say this because you may want to compare this with Binomial cdf graphs you may find somewhere. The distribution you need is a Binomial with parameters "one Billion" (number of trials) and 0.5 (success probability for each trial). I haven't thought about whether you will run into numerical problems evaluating this for $n=10^9$; in that case there should be approximations.
Comment: R falls back to inverse sampling when the number of trials is large, so I guess it should work at least to some degree https://github.com/wch/r-source/blob/79298c499218846d14500255efd622b5021c10ec/src/nmath/rbinom.c#L70
Comment: At https://stats.stackexchange.com/a/608790/919 I show how to generate samples of size $10^{30}$ or larger and at https://stats.stackexchange.com/a/606853/919, a sample of size $10^{100}$ is shown.  The ideas applied to these more complicated problems translate directly to this Binomial sampling problem.
Comment: This does look like what I need. Appreciated!
Answer: The distribution is Binomial, which is discrete.  Using the generic function s given at What is the statistical distribution of the number of times a number i would appear after M trials of a poisson distribution? for drawing random values from any discrete distribution, we can sample such a large number of coin flips extremely efficiently.
As an example, the implementation rBinomial (given below) will repeat this experiment of flipping a coin one billion times as often as you like.  For instance, the call rBinomial(1e20, 1e9) repeats this experiment $10^{20}$ times but takes only two seconds to execute.  Because it returns almost a quarter million distinct values, which can take a long time to plot, I have plotted a random sample of a thousand of these values showing how many times each value was the result of the experiment:

Of course this is identical to the rounded values of a Normal distribution: but the point is that the exact probabilities (in double precision floating point, of course) were used.  Moreover, if you tried to use the Normal approximation in this instance it would fail, because the software simply cannot generate $10^{20}$ values in reasonable time.
The short answer to the question of flipping a coin one billion times, then, is obtained by computing
rBinomial(1, 1e9)

This takes a half second (not bad for a billion flips!) and returns a random value such as

500015061

The arguments to rBinomial are

n is the number of times to replicate the coin-flipping experiment.
N is the number of times to flip the coin in each experiment.
p is the chance of heads on each flip.
Z.max helps limit the storage used by the algorithm.  It is a Z-score. By default it's effectively no limit at all (because the binomial probability associated with larger Z-scores is vanishingly small).
k.max determines when to resort to a Normal approximation.  When the range of likely values exceeds k.max, the values will be found by rounding Normal variates.  This will work only when n is sufficiently small (less than $10^8$ or so is practicable).

Its output is a two-column array of values and their counts.  All counts are positive and (therefore) the values are not necessarily consecutive. For example, one possible output of rBinomial(5, 10) is
     Value Count
[1,]     2     1
[2,]     5     2
[3,]     6     2

This documents five repetitions of ten coin flips.  In one case there were two heads, in two cases there were five heads, and in two cases there were six heads.
rBinomial <- function(n, N, p = 1/2, Z.max = 8, k.max = 1e6) {
  Z <- min(Z.max, -qnorm(1e-3 / N)) # (No need to look beyond this z-score)
  mu <- p * N
  sigma <- exp((log(p) + log(1 - p) + log(N)) / 2)
  x.0 <- max(0, floor(mu - Z*sigma))
  x.1 <- min(N, ceiling(mu + Z*sigma))
  if (x.1 - x.0 >= k.max) {
    warning("Normal approximation employed.")
    round(rnorm(n, mu, sigma)) # Use Normal approximation
  } else {
    x <- seq(x.0, x.1, by = 1)
    probs <- dbinom(x, N, p)
    X <- cbind(Value = x, Count = s(n, probs))
    i <- X[, 2] > 0
    X[i, , drop = FALSE]
  }
}
#
# Flip a coin one billion (1e9) times.
#
system.time(x <- rBinomial(1, 1e9))
#
# Repeat this process 1e20 (100,000,000,000,000,000,000) times.
#
system.time(x <- rBinomial(1e20, 1e9)) # Around 2 seconds on a 2021 workstation
#
# Sketch the results.  The output is an array with 'Value' and 'Count' columns
# tallying all 1e20 experimental results.
#
j <- sample.int(nrow(x), 1e3)
plot(x[j, ], type = "h")

The function s referenced in this code can be found at https://stats.stackexchange.com/a/606853/919.
Answer: Define a random variable $X$, such that $X=0$ if the coin is landing with a head, or $X=1$ if the coin is landing with a tail. Suppose you want to simulate the cases with probability $p$ for $X=0$.
Use a random number generator to generate i.i.d. uniformly distributed numbers between $0$ and $1$, denoted by $S$.
Then, quantize $S$ to $X$, that is, corresponding to each $S$, output $X=0$ if $S
p$.
In rare case if $S=p$ exactly, simply convert $S$ to $X=0$ and $X=1$ alternately for fairness.
Then, each value of $X$ represents the result of flipping a coin.
Comment: The point of the question is to generate *huge* samples.  Replacing one "billion" with $10^{30},$ for instance, shows this approach won't work.


Show local image by JavaScript (mobile camera)

Question: This is my code for showing a image from user local machine, but it sometimes doesn't work for the first time. Specially when (on mobile) user take a picture from camera.
It almost always doesn't work for the first time that user select his image.

I use Image() to get the width and height of image for aspectRatio of resizable.

    <meta charset="UTF-8">
    <title>Upload Image</title>

    <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

Select Image

Comment: Any alerts in console? Which browsers are you testing with on Mobile?
Comment: @Twisty There is not alert in console. I'm using Chrome, but any other browser doesn't work!
Comment: Initial testing, plus found some code that needed some optimization: https://jsfiddle.net/Twisty/188x0w0u/ - for mobile testing, use: https://jsfiddle.net/Twisty/188x0w0u/show/
Answer: Did some intitial testing via FireFox on desktop and Chrome on Android. Both work properly to display the image:
Working Example: https://jsfiddle.net/Twisty/188x0w0u - for mobile testing, use: https://jsfiddle.net/Twisty/188x0w0u/show
JavaScript
$(function() {
  function upload(file) {
    var fr = new FileReader();

    fr.onload = function(event) {
      var src = event.target.result;
      var img = new Image();

      img.onload = function() {
        $('.select-img').remove();
        $('#image').css('display', 'block').attr('src', src).resizable({
          aspectRatio: this.width / this.height
        });
      };
      img.src = src;
    };

    fr.readAsDataURL(file);
  }

  $('.select-img').click(function() {
    var fileInput = $("<input>", {
      type: "file",
      accept: "image/*"
    });
    fileInput.trigger('click');

    fileInput.on('change', function(ev) {
      upload(ev.target.files[0]);
    });

    return false;
  });
});

Minor switches to code to make better use of jQuery. this worked in both capturing a photo from camera and selecting photo from documents on the mobile device.
Resizing fails, and for me this was expected. Add Touch punch:
https://cdnjs.cloudflare.com/ajax/libs/jqueryui-touch-punch/0.2.3/jquery.ui.touch-punch.min.js
New Test: https://jsfiddle.net/Twisty/188x0w0u/2/
Mobile: https://jsfiddle.net/Twisty/188x0w0u/2/show/
Now the .resizable() works on mobile too.
Comment: It doesn't work on mobile when I take a picture from front camera (selfie)!!
Comment: @M.Mohammadi I was unable to replicate the issue. Please describe the exacte details to replicate the issue, include phone and browser you are using for testing.
Comment: I am using Galaxy S8+ and Chrome 62.0.3202.84; but my clients (all of them) has the same problem! It just happens by using front camera.
Comment: I tested using Samsung Galaxy S8+ with Chrome and the front facing camera without issue. Please describe how I can replicate the issue.


Integral Domain

Question: I'm working on this question:

Let $F$ be a (commutative) field. Show that the ring $F[x]$ of polynomials with coefficients from F has no zero-divisors. In other words, if $P(x)$ and $Q(x)$ are polynomials in $f[x]$, then $P(x)Q(x)$ cannot be the zero polynomial unless either $P(x)$ or $Q(x)$ is the zero polynomial.

I let $P(x)$ and $Q(x)$ be such polynomials in $F[x]$ such that $$P(x) =   a_0x^n + a_1x^{n-1} + ... + a_{n-1}x + a_n$$ and $$Q(x) = b_0x^m + b_1x^{m-1} + ... + b_{m-1}x + b_m$$
Then we have that $$P(x)Q(x) = a_0b_0x^{n+m} + a_0b_1x^{n+m-2}+...$$
I was thinking to split this into $2$ cases, one where I let $a_0 = 0$ and the second where $b_0 = 0$ Is this the right approach?
Comment: Look at the coefficient of the highest order term of $P(x)Q(x)$. Since $F$ is a field, $F$ is an integral domain.
Comment: @Dave Is this just by pure inspection?
Comment: @i8Σπ_821 Yeah, it looks like you are over-thinking it.
Comment: @Mike Yeah now that you mention it, you're right.
Answer: Taking two nonzero polynomials $P$ and $Q$ such that $\deg P = n$ and $\deg Q = m$, we have
$$P(x) = a_0x^n + \dotsb \qquad Q(x) = b_0x^m + \dotsb$$
where $a_0$ and $b_0$ are nonzero. Since $F$ is a field, the product $a_0b_0$ cannot be zero, so the product $PQ$ will be a degree $n+m$ polynomial with leading term $a_0b_0$, so it's not the zero polynomial.
Comment: Ah now it's clear. Yeah I was just over-thinking the problem.

Integral Domain