text:
Q: Plotting Heatmap with geom_raster in ggmap I have a data frame containing longitude, latitude and a intensity variable (var1.pred).

I would like to plot a smooth filled contour plot on a ggmap map. I have done it using a geom_tile plot but it doesn't look smooth. I have decreased the tile sizes but the plot takes up to much storage. What I want to do is use geom_raster to plot a nice clean contour plot over the map object.
Using the bellow code I have done it using ggplot:
raster <- ggplot(idw.output, aes(x = lon, y = lat, z = var1.pred))+
geom_raster(aes(fill = var1.pred), alpha = 0.5) +
scale_fill_gradient(low = "white", high = "blue")+
geom_contour(colour = "white", binwidth = 1) +
labs(fill = "Frequency", title = "Frequency per area", x = 'Longitude', y = 'Latitude')
raster

This returns the plot:

However I cannot work out how to combine this with a ggmap object. I have tried various things such as:
ggmap(fr) + #fr is a map from get_map
ggplot(idw.output, aes(x = lon, y = lat, z = var1.pred))+
geom_raster(aes(fill = var1.pred), alpha = 0.5) +
scale_fill_gradient(low = "white", high = "blue")+
geom_contour(colour = "white", binwidth = 1) +
labs(fill = "Frequency", title = "Frequency per area", x = 'Longitude', y = 'Latitude')

But I get the error:
Error: Don't know how to add o to a plot
I know the issue has something to do with combining a ggplot and ggmap object but I cannot work out how to get it to work. Any help would be appreciated.
Thanks,
Robin

A: Without a reproducible example, it is impossible to test your code, but it is likely that you can move the ggplot call to the base_layer argument so that you can keep adding geoms.
ggmap(fr, base_layer = ggplot(idw.output, aes(x = lon, y = lat, z = var1.pred))) +
    geom_raster(aes(fill = var1.pred), alpha = 0.5) +
    scale_fill_gradient(low = "white", high = "blue")+
    geom_contour(colour = "white", binwidth = 1) +
    labs(fill = "Frequency", title = "Frequency per area", x = 'Longitude', y = 'Latitude')


text:
Q: Why do .bat scripts get locked after execution in Windows 7? Ever since I moved to Windows 7, whenever I am am developing a .bat script I have exactly one chance to get it right. As soon as I execute the script, it becomes locked by an unknown process even if the execution appears to have completed, and I have to force quit explorer or restart to be able to edit the .bat file again.
For example, if I create a .bat file,
@echo off
@start prog\ConsolePortable\ConsolePortable.exe

then realize after executing it that I needed to change some aspect of the script,
@echo off
@cd prog\ConsolePortable
@start ConsolePortable.exe

Then I will not be able to save my changes. For example, in gvim I get the message, "'console.bat' is read-only (add ! to override)," and then when I try to override, I get the message, "E212: Can't open file for writing."
Surely there must be some way of scripting without requiring ProcessExplorer on every computer I use. How does one find the process of a .bat file to stop it, anyway? I tried ProcessExplorer and BSOD'd the compy trying to stop it. I have also tried using cmd /c in place of start.
EDIT:
ConsolePortable starts fine here and appears to exit fine, however the following test setup does not freeze the editor:
// Program.java
class Program {public static void main(String[] args) {System.exit(0);}}

// startProgram.bat
echo Starting Program in Java ...
start java Program
echo exiting bat file ...

EDIT 2:
Perhaps I should mention that I created the file by using the touch command in cygwin. After restarting the computer, I can't duplicate this problem, though I have encountered it on other computers before.

A: I would say this is possibly an error with your editor, or you have weird permissions set up.
I quite often edit batch files with notepad (whilst running) and have not had a problem.
However, I am not sure you can just inject commands - it remembers the line number (I think) that it was on.
e.g. in your bat file, after starting, it will have finished processing.
Place a pause at the third line, then run but do not press a key after the pause. Edit the original bat file, place a command in the fourth line - and you will see that the fourth line will get processed.

A: I would try changing the line
@start ConsolePortable.exe

To
@start "myProgram" ConsolePortable.exe

As from http://ss64.com/nt/start.html:

START "title" [/Dpath] [options] "command" [parameters]
Notes:
Always include a TITLE this can be a
  simple string like "My Script" or just
  a pair of empty quotes "" According to
  the Microsoft documentation, the title
  is optional, but you may have problems
  if it is omitted.
Document files may be invoked through
  their file association just by typing
  the name of the file as a command.
  e.g. START "" WORD.DOC would launch
  the application associated with the
  .DOC file extension

This one caught me off guard when I tried to script VLC some time ago and putting a title in there fixed a seemingly related issue for me.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Como posicionar JTabbedPane na metade inferior da tela? Eu gostaria de fazer com que minha tela seja divida em no minimo duas partes, na parte de cima adicionarei alguns campos, e na parte de baixo, um JTabbedPane com algumas abas. O problema é que não sei como fazer isso, só consigo fazer o JTabbedPane ocupando toda a tela.
Segue uma imagem para ilustrar:

Tela:
package tabbedpane;

import java.awt.Dimension;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;

public class Tela extends JFrame {

    JTabbedPane tabbedPane = new JTabbedPane();

    public Tela() {
        setTitle("Apenas um EXEMPLO");
        tabbedPane.addTab("Página 1", painel1());
        tabbedPane.addTab("Página 2", painel2());
        add(tabbedPane);
        setResizable(false);
        setVisible(true);
        setSize(600, 500);
        setLocationRelativeTo(null);
        setMinimumSize(new Dimension(getWidth(), getHeight()));
         setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    }

    public static void main(String[] args) {
        Tela tela  = new Tela();
    }

    public JComponent painel1() {
        JPanel painel1 = new JPanel();
        JLabel label1;
        label1 = new JLabel("Página 1");
        painel1.add(label1);
        return painel1; // retorna painel.
    }

    public JComponent painel2() {
        JPanel painel2 = new JPanel();
        JLabel label2;
        label2 = new JLabel("Página 2");
        painel2.add(label2);
        return painel2;
    }
}

A: É possível fazendo apenas duas alterações:

*

*add(tabbedPane, BorderLayout.SOUTH); - aproveitei do LayoutManager padrão do JFrame, e indiquei a ele que posicione o componente na direção sul dentro do Frame.

*tabbedPane.setPreferredSize(new Dimension(getWidth(), 300)); - Também defini um tamanho preferido para que o LayoutManager saiba qual dimensão do componente.
Com as alterações, fica desta forma:
import java.awt.BorderLayout;
import java.awt.Dimension;

import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;

public class Tela extends JFrame {

    JTabbedPane tabbedPane = new JTabbedPane();

    public Tela() {
        setTitle("Apenas um EXEMPLO");
        tabbedPane.addTab("Página 1", painel1());
        tabbedPane.addTab("Página 2", painel2());
        tabbedPane.setPreferredSize(new Dimension(getWidth(), 300));

        /* -- exemplificacao de como adicionar o painel superior -- */
        JPanel painelSuperior = new JPanel();
        painelSuperior.add(new JButton("teste"));
        add(painelSuperior, BorderLayout.NORTH);

        add(tabbedPane, BorderLayout.SOUTH);
        setResizable(false);
        setVisible(true);
        setSize(600, 500);
        setLocationRelativeTo(null);
        setMinimumSize(new Dimension(getWidth(), getHeight()));
         setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    }

    public static void main(String[] args) {
        Tela tela  = new Tela();
    }

    public JComponent painel1() {
        JPanel painel1 = new JPanel();
        JLabel label1;
        label1 = new JLabel("Página 1");
        painel1.add(label1);
        return painel1; // retorna painel.
    }

    public JComponent painel2() {
        JPanel painel2 = new JPanel();
        JLabel label2;
        label2 = new JLabel("Página 2");
        painel2.add(label2);
        return painel2;
    }
}

Resultado ao executar este código, já com um painel superior de exemplo:


text:
Q: Dotted line with a white bachground Is there an elegant way to draw a dotted line with white solid line underneath? The reason I'm asking is that often I'm drawing lots polygons which share some dotted sides. However, I would like to have all lines having the same number of dots regardless of how many times each particular line was drawn. Here is a minimal example:
\documentclass{article}
\usepackage{tikz}

\begin{document}
    \begin{tikzpicture}
        \draw [dotted]
            (0,0) -- (1,0) -- (1,1) -- (0,1) -- cycle
            (1,0) -- (2,0) -- (2,1) -- (1,1) -- cycle
        ;
    \end{tikzpicture}
\end{document}

So here you can see two squares with a shared side. I would like to avoid the shared side having visibly larger number of dots. Obviously, I want a general solution, i.e. one which still involves drawing the same page twice but without the dots adding up.

A: The common part between both segments need to be the same distance away from the start of a segment (i.e. the recent move to):
\draw [dotted]
  (0,0) -- (1,0) -- (1,1) -- (0,1) -- cycle
  (2,0) -- (1,0) -- (1,1) -- (2,1) -- cycle;

Here, the part (1,0) -- (1,1) is at the same place and starts one unit after the recent move to (the (0,0) or the (2,0) at the start of the line).
But this can get messy real quick with a lot of rectangles but you can just draw every side separatly, every horizontal from left to right and every vertical from bottom to top:
\draw [dotted]
  foreach \x in {0, ..., 2} {
    foreach \y in {0, ..., 1} {
      [shift={(\x, \y)}]
        (0,0) --  (1,0) (0,0) --  (0,1)
        (0,1) -- +(1,0) (1,0) -- +(0,1)
    }
  };

It might be better to just define a dash pattern that has a phase which adds up nicely to the length of your edge.
Since you're using the length of 1, i.e. 1cm in the default xyz coordinate system, you could use
dash pattern = on \pgflinewidth off .66667mm-\pgflinewidth,
dash phase   = .5\pgflinewidth
% or:
dash         = on \pgflinewidth off .66667mm-\pgflinewidth phase .5\pgflinewidth

which means that the line has one square dot (on \pgflinewidth) and the next one starts after 0.66667 mm.
Since the \pgflinewidth is not a nice number that fits into the metric coordinate system we subtract the \pgflinewidth again which means just .66667mm needs to fit into 1 cm (which it does 150 times).
The dash phase is needed so that the dot starts with its center at the start of the path.
Now you can simply use the rectangle path operation again (or even your version of specifying the corners):
\draw[
  dash pattern=on \pgflinewidth off 1mm-\pgflinewidth,
  dash phase=.5\pgflinewidth
] foreach \x in {0, ..., 2} {
    foreach \y in {0, ..., 1} {
      (\x, \y) rectangle + (1,1)
    }
  };

If you change your coordinate system, you need to adjust this value (or we need to write a special key that does that for you but that is a bit mathy).
This also doesn't scale nicely with the line width since .66667mm ignores the line width. So, if your line width approaches this value the space between the dots get smaller. (This is why I'm using 1mm in the example below because of thick is used.)

I've also added an example with the grid operation (which just draws non-overlapping straight lines) – which doesn't look that nice because the pattern doesn't fit the coordinate system but it doesn't draw multiple lines on top of each other. (You can of course use a similar dash setting as above to have it nicely line up again).
The fourth example places rectangles along the path of your grid which makes it very easy for weird xyz coordinate systems though it will be a bit work do rotate them so that it will look like a dash pattern.
I've placed all examples in a \matrix to make it easier to show them in one diagram.
Code
\documentclass[tikz]{standalone}
\begin{document}
\tikz[thick]\matrix[row sep=5mm, column sep=5mm]{
\draw [dotted]
  (0,0) -- (1,0) -- (1,1) -- (0,1) -- cycle
  (2,0) -- (1,0) -- (1,1) -- (2,1) -- cycle;
&
\draw [dotted]
  foreach \x in {0, ..., 2} {
    foreach \y in {0, ..., 1} {
      [shift={(\x, \y)}]
        (0,0) --  (1,0) (0,0) --  (0,1)
        (0,1) -- +(1,0) (1,0) -- +(0,1)
    }
  };
\\
\draw[
  dash pattern=on \pgflinewidth off 1mm-\pgflinewidth,
  dash phase=.5\pgflinewidth
] foreach \x in {0, ..., 2} {
    foreach \y in {0, ..., 1} {
      (\x, \y) rectangle + (1,1)
    }
  };
&
\draw [dotted] (0,0) grid (3,2);
\\
\fill[x=(30:.5cm), y=(70:.7777cm)]
  foreach \x in {0, ..., 2} {
    foreach \y in {0, ..., 1} {
      [shift={(\x, \y)}]
      foreach \X in {0, ..., 9} {
        foreach \xy/\yx/\v in {x/y/0, y/x/0, x/y/1, y/x/1} {
          ([shift={(-.5\pgflinewidth,-.5\pgflinewidth)}]xyz cs: \xy=\X/10,\yx=\v)
            rectangle + (\pgflinewidth, \pgflinewidth)
        }
      }
    }
  };
\\};
\end{document}

Output


text:
Q: Why memory accessing instruction of SSE2 and AVX2 need (__m128 *) and (__m256*) using intel intrinsics? I'm using both SSEx and AVXx intrinsics instruction. When I'm using Intel SSE2 or AVX2 and want to load a vector from memory I should use the following instruction (data type is int):
_mm_load_si128( (__m128i *)&a[ i ][ j ]);
_mm256_load_si256( (__m256i *)&a[ i ][ j ]);

and when the data type is float I should use like follows:
_mm_load_ps(&a[ i ][ j ]);
_mm256_load_ps(&a[ i ][ j ]);

so the question is what is the differences between float and int loading from memory that need a (type *) or not?


text:
Q: Find if point lies on line segment I have line segment defined by these two points: A(x1,y1,z1) and B(x2,y2,z2). I have point p(x,y,z). How can I check if the point lies on the line segment?

A: First take the cross product of AB and AP.  If they are colinear, then it will be 0.
At this point, it could still be on the greater line extending past B or before A, so then I think you should be able to just check if pz is between az and bz.
This appears to be a duplicate, actually, and as one of the answers mentions, it is in Beautiful Code.

A: Find the distance of point P from both the line end points A, B. If AB = AP + PB, then P lies on the line segment AB.
AB = sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1)+(z2-z1)*(z2-z1));
AP = sqrt((x-x1)*(x-x1)+(y-y1)*(y-y1)+(z-z1)*(z-z1));
PB = sqrt((x2-x)*(x2-x)+(y2-y)*(y2-y)+(z2-z)*(z2-z));
if(AB == AP + PB)
    return true;

A: in case if someone looks for inline version:
public static bool PointOnLine2D (this Vector2 p, Vector2 a, Vector2 b, float t = 1E-03f)
{
    // ensure points are collinear
    var zero = (b.x - a.x) * (p.y - a.y) - (p.x - a.x) * (b.y - a.y);
    if (zero > t || zero < -t) return false;

    // check if x-coordinates are not equal
    if (a.x - b.x > t || b.x - a.x > t)
        // ensure x is between a.x & b.x (use tolerance)
        return a.x > b.x
            ? p.x + t > b.x && p.x - t < a.x
            : p.x + t > a.x && p.x - t < b.x;

    // ensure y is between a.y & b.y (use tolerance)
    return a.y > b.y
        ? p.y + t > b.y && p.y - t < a.y
        : p.y + t > a.y && p.y - t < b.y;
}

A: Your segment is best defined by parametric equation
for all points on your segment, following equation holds:
x = x1 + (x2 - x1) * p
y = y1 + (y2 - y1) * p
z = z1 + (z2 - z1) * p
Where p is a number in [0;1]
So,  if there is a p such that your point coordinates satisfy those
3 equations,  your point is on this line.  And it p is between 0 and 1 -
it is also on line segment

A: Here's some C# code for the 2D case:
public static bool PointOnLineSegment(PointD pt1, PointD pt2, PointD pt, double epsilon = 0.001)
{
  if (pt.X - Math.Max(pt1.X, pt2.X) > epsilon ||
      Math.Min(pt1.X, pt2.X) - pt.X > epsilon ||
      pt.Y - Math.Max(pt1.Y, pt2.Y) > epsilon ||
      Math.Min(pt1.Y, pt2.Y) - pt.Y > epsilon)
    return false;

  if (Math.Abs(pt2.X - pt1.X) < epsilon)
    return Math.Abs(pt1.X - pt.X) < epsilon || Math.Abs(pt2.X - pt.X) < epsilon;
  if (Math.Abs(pt2.Y - pt1.Y) < epsilon)
    return Math.Abs(pt1.Y - pt.Y) < epsilon || Math.Abs(pt2.Y - pt.Y) < epsilon;

  double x = pt1.X + (pt.Y - pt1.Y) * (pt2.X - pt1.X) / (pt2.Y - pt1.Y);
  double y = pt1.Y + (pt.X - pt1.X) * (pt2.Y - pt1.Y) / (pt2.X - pt1.X);

  return Math.Abs(pt.X - x) < epsilon || Math.Abs(pt.Y - y) < epsilon;
}

A: If the point is on the line then:
(x - x1) / (x2 - x1) = (y - y1) / (y2 - y1) = (z - z1) / (z2 - z1)

Calculate all three values, and if they are the same (to some degree of tolerance), your point is on the line.
To test if the point is in the segment, not just on the line, you can check that
x1 < x < x2, assuming x1 < x2, or
y1 < y < y2, assuming y1 < y2, or
z1 < z < z2, assuming z1 < z2

A: Or let the dotnet do the heavy lifting for you if using visual studio use a GraphicsPath
this will also allow you to add tolerances for if just clicked outside the line.
using (Drawing2D.GraphicsPath gp = new Drawing2D.GraphicsPath())
{
    gp.AddLine(new Point(x1, y1), new Point(x2, y2));

    // Make the line as wide as needed (make this larger to allow clicking slightly outside the line)
    using (Pen objPen = new Pen(Color.Black, 6))
    {
        gp.Widen(objPen);
    }

    if (gp.IsVisible(Mouse.x, Mouse.y))
    {
        // The line was clicked
    }
}

A: The cross product (B - A) × (p - A) should be much much shorter than B - A. Ideally, the cross product is zero, but that's unlikely on finite-precision floating-point hardware.

A: I use this to calculate the distance AB between points a and b.
static void Main(string[] args)
{
        double AB = segment(0, 1, 0, 4);
        Console.WriteLine("Length of segment AB: {0}",AB);
}

static double segment (int ax,int ay, int bx, int by)
{
    Vector a = new Vector(ax,ay);
    Vector b = new Vector(bx,by);
    Vector c = (a & b);
    return Math.Sqrt(c.X + c.Y);
}

struct Vector
{
    public readonly float X;
    public readonly float Y;

    public Vector(float x, float y)
    {
        this.X = x;
        this.Y = y;
    }
    public static Vector operator &(Vector a, Vector b)
    {
        return new Vector((b.X - a.X) * (b.X - a.X), (b.Y - a.Y) * (b.Y - a.Y));
    }
}

based on Calculate a point along the line A-B at a given distance from A

A: Let V1 be the vector (B-A), and V2 = (p-A), normalize both V1 and V2.
If V1==(-V2) then the point p is on the line, but preceding A, & therefore not in the segment.
If V1==V2  the point p is on the line. Get the length of (p-A) and check if this is less-or-equal to length of (B-A), if so the point is on the segment, else it is past B.

A: This is my code which can run in WPF
    public static class Math2DExtensions
    {
        public static bool CheckIsPointOnLineSegment(Point point, Line line, double epsilon = 0.1)
        {
            // Thank you @Rob Agar
            // (x - x1) / (x2 - x1) = (y - y1) / (y2 - y1)
            // x1 < x < x2, assuming x1 < x2
            // y1 < y < y2, assuming y1 < y2

            var minX = Math.Min(line.APoint.X, line.BPoint.X);
            var maxX = Math.Max(line.APoint.X, line.BPoint.X);

            var minY = Math.Min(line.APoint.Y, line.BPoint.Y);
            var maxY = Math.Max(line.APoint.Y, line.BPoint.Y);

            if (!(minX <= point.X) || !(point.X <= maxX) || !(minY <= point.Y) || !(point.Y <= maxY))
            {
                return false;
            }

            if (Math.Abs(line.APoint.X - line.BPoint.X) < epsilon)
            {
                return Math.Abs(line.APoint.X - point.X) < epsilon || Math.Abs(line.BPoint.X - point.X) < epsilon;
            }

            if (Math.Abs(line.APoint.Y - line.BPoint.Y) < epsilon)
            {
                return Math.Abs(line.APoint.Y - point.Y) < epsilon || Math.Abs(line.BPoint.Y - point.Y) < epsilon;
            }

            if (Math.Abs((point.X - line.APoint.X) / (line.BPoint.X - line.APoint.X) - (point.Y - line.APoint.Y) / (line.BPoint.Y - line.APoint.Y)) < epsilon)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }

    public record Line
    {
        public Point APoint { get; init; }

        public Point BPoint { get; init; }
    }

My code is in github
Thank you @Rob Agar and @MetaMapper

A: You could check if the point lies between the two planes defined by point1 and point2 and the line direction:
///  Returns the closest point from @a point to this line on this line.
vector3 <Type>
line3d <Type>::closest_point (const vector3 <Type> & point) const
{
    return this -> point () + direction () * dot (point - this -> point (), direction ());
}

///  Returns true if @a point lies between point1 and point2.
template <class Type>
bool
line_segment3 <Type>::is_between (const vector3 <Type> & point) const
{
    const auto closest = line () .closest_point (point);
    return abs ((closest - point0 ()) + (closest - point1 ())) <= abs (point0 () - point1 ());
}


text:
Q: LocationSettingsRequest request does not work on Xiaomi I try to show popup for users who have turned off Location Services:
val locationRequest = LocationRequest.create()
        .setInterval(TimeUnit.SECONDS.toMillis(1))
        .setFastestInterval(TimeUnit.SECONDS.toMillis(1))
        .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
    val builder = LocationSettingsRequest.Builder().addLocationRequest(locationRequest)
    LocationServices
        .getSettingsClient(this)
        .checkLocationSettings(builder.build())
        .addOnSuccessListener(this) { response: LocationSettingsResponse? ->

        }
        .addOnFailureListener(this) { ex ->
            if (ex is ResolvableApiException) {
                // Location settings are NOT satisfied,  but this can be fixed  by showing the user a dialog.
                try {
                    // Show the dialog by calling startResolutionForResult(),  and check the result in onActivityResult().
                    val resolvable = ex as ResolvableApiException
                    resolvable.startResolutionForResult(
                        this,
                        REQUEST_CODE_CHECK_SETTINGS
                    )
                } catch (sendEx: SendIntentException) {
                    // Ignore the error.
                }
            }
        }

This code piece works very well for Samsungs, but whenever a user with XIAMO REDMI NOTE 10 tests it, popup does not appear.

A: "The pop up does not appear" is not really an error description, EUR 200 would be a physical device. They likely run Android 11 with MIUI 12.5 ... while most cloud testing is Xiaomi Redmi Note 7, with Android 9. Reports suggest, to at least update the state-owned GPS-A IP address:

Hi, just found that the supl server in the Location/A-GPS settings is set to a Chinese ip address (221.176.0.55, resolves to chinamobile.com)
I guess it's a remnant from the China rom, for Europe it should probably be set to supl.google.com or perhaps supl.vodafone.com.

*

*Search for "A-GPS" in the settings.

*Replace A-GPS server 221.176.0.55 with supl.google.com.

It may well be, that Google Play Services aren't installed. In such case one can only build as a separate product flavor, targeting these devices in particular eg. with googleImplementation using LocationRequest, xiaomiImplementation using whatever location provider available.
Being able to run Google Maps or Google Earth is no problem, but this does not imply Google Play Services would also be installed - as they'd be required for location and push notifications.

According to some "authoritative source", GMS aren't banned on Xiaomi:
https://twitter.com/Xiaomi/status/1354489349442691074
But they cannot be assumed to be available either (by default).

You might be looking for "Fused Location Provider by Xiaomi Inc." aka com.xiaomi.location.fused, instead of com.android.location.fused. com.android.internal.R.array.config_locationProviderPackageNames is being used for lookup.


text:
Q: d3 force layout link position in node I've been reading several questions about d3 force layout, but I haven't found my answer yet, so I'm posting this.
I'm working with the D3 library, specifically with the force layout. Instead of adding pre-defined shapes to the nodes, I'm creating my own shapes like circles, rects and so on.
var shapes = {
        star : "m 0 0 l 23 12 l -4 -26 l 19 -19 l -27 -4 l -11 -23 l -12 23 l -27 4 l 19 19 l -4 26 l 24 -12",
        rect : "M 0 0 L 0 "+ rect_size + "L "+ 2 * rect_size + " "+ rect_size + " L "+ 2 * rect_size + " 0 L 0 0",
        vertical_rect : "M 0 0 L 0 "+ 2 * rect_size + "L "+ rect_size + " "+ 2 * rect_size + " L "+ rect_size + " 0 L 0 0",
        circle: "M 0 0 A "+ radius + " " + radius +" 0 1 0 0.00001 0 Z"
        };
var dummy_nodes = {};
var dummy_shapes = {"A" : shapes.circle, "B" : shapes.rect, "C" : shapes.rect, "D" : shapes.circle};

    // Compute the distinct nodes from the links.
links.forEach(function (link) {
        link.source = dummy_nodes[link.source] || (dummy_nodes[link.source] =
                                                    { name: link.source, shape: dummy_shapes[link.source]});
        link.target = dummy_nodes[link.target] || (dummy_nodes[link.target] =
                                                    { name: link.target,shape: dummy_shapes[link.target]});
    });
var force = d3.layout.force()
        .nodes(d3.values(dummy_nodes))
        .links(links)
        .size([960, 500])
        .linkDistance(200)
        .charge(-1500)
        .on("tick", tick)
        .start();
var svg = d3.select("body").append("svg:svg")
        .attr("width", w)
        .attr("height", h);
var node = svg.append("svg:g").selectAll(".node")
        .data(force.nodes())
        .enter().append("path")
        .attr("class", "node")
        .attr("d", function(n){ return n.shape})
        .on("dblclick", dblclick)
        .call(drag);

You can view the entire code here
I don't understand how I can change the position in wich the links(or edges) of the graph enter each node.
For example: I would like that the edges coming out of the rectangle nodes where positioned in the center of the rect, instead of the top left corner( I guess is position 0,0).
I now there must be something related with the CX and CY of each shape from SVG, but it's beyond my grasp.
I hope that my question is clear, feel free to ask anything that I've might left out
Thanks!

A: Just make the centre of your shape the origin i.e. instead of defining a rect as
   rect : "M 0 0 L 0 "+ rect_size + "L "+ 2 * rect_size + " "+ rect_size + " L "+ 2 * rect_size + " 0 L 0 0",

define it as
   rect : "M " + -rect_size + " " + (-rect_size / 2) + " h " + 2 * rect_size + " v " + rect_size + " h "+ (-2 * rect_size) + " z",

I've swapped from L to h, v and z so it's simpler. You can do the same thing with the other shapes.


text:
Q: How to compare two strings in dot separated version format in Bash? Is there any way to compare such strings on bash, e.g.: 2.4.5 and 2.8 and 2.4.5.1?

A: There probably is no universally correct way to achieve this. If you are trying to compare versions in the Debian package system try dpkg --compare-versions <first> <relation> <second>.

A: if it's just about to know whether one version is lower than another I came up checking whether sort --version-sort changes the order of my version strings:
    string="$1
$2"
    [ "$string" == "$(sort --version-sort <<< "$string")" ]

A: GNU sort has an option for it:
printf '2.4.5\n2.8\n2.4.5.1\n' | sort -V

gives:
2.4.5
2.4.5.1
2.8

A: $ for OVFTOOL_VERSION in "4.2.0" "4.2.1" "5.2.0" "3.2.0" "4.1.9" "4.0.1" "4.3.0" "4.5.0" "4.2.1" "30.1.0" "4" "5" "4.1" "4.3"
> do
>   if [ $(echo "$OVFTOOL_VERSION 4.2.0" | tr " " "\n" | sort --version-sort | head -n 1) = 4.2.0 ]; then
>     echo "$OVFTOOL_VERSION is >= 4.2.0";
>   else
>     echo "$OVFTOOL_VERSION is < 4.2.0";
>   fi
> done
4.2.0 is >= 4.2.0
4.2.1 is >= 4.2.0
5.2.0 is >= 4.2.0
3.2.0 is < 4.2.0
4.1.9 is < 4.2.0
4.0.1 is < 4.2.0
4.3.0 is >= 4.2.0
4.5.0 is >= 4.2.0
4.2.1 is >= 4.2.0
30.1.0 is >= 4.2.0
4 is < 4.2.0
5 is >= 4.2.0
4.1 is < 4.2.0
4.3 is >= 4.2.0

A: function version { echo "$@" | awk -F. '{ printf("%d%03d%03d%03d\n", $1,$2,$3,$4); }'; }

Used as such:
if [ $(version $VAR) -ge $(version "6.2.0") ]; then
    echo "Version is up to date"
fi

(from https://apple.stackexchange.com/a/123408/11374)

A: I implemented a function that returns the same results as Dennis Williamson's but uses fewer lines. It does perform a sanity check initially which causes 1..0 to fail from his tests (which I would argue should be the case) but all of his other tests pass with this code:
#!/bin/bash
version_compare() {
    if [[ $1 =~ ^([0-9]+\.?)+$ && $2 =~ ^([0-9]+\.?)+$ ]]; then
        local l=(${1//./ }) r=(${2//./ }) s=${#l[@]}; [[ ${#r[@]} -gt ${#l[@]} ]] && s=${#r[@]}

        for i in $(seq 0 $((s - 1))); do
            [[ ${l[$i]} -gt ${r[$i]} ]] && return 1
            [[ ${l[$i]} -lt ${r[$i]} ]] && return 2
        done

        return 0
    else
        echo "Invalid version number given"
        exit 1
    fi
}

A: Here is a simple Bash function that uses no external commands. It works for version strings that have up to three numeric parts in them - less than 3 is fine as well.  It can easily be extended for more. It implements =, <, <=, >, >=, and != conditions.
#!/bin/bash
vercmp() {
    version1=$1 version2=$2 condition=$3

    IFS=. v1_array=($version1) v2_array=($version2)
    v1=$((v1_array[0] * 100 + v1_array[1] * 10 + v1_array[2]))
    v2=$((v2_array[0] * 100 + v2_array[1] * 10 + v2_array[2]))
    diff=$((v2 - v1))
    [[ $condition = '='  ]] && ((diff == 0)) && return 0
    [[ $condition = '!=' ]] && ((diff != 0)) && return 0
    [[ $condition = '<'  ]] && ((diff >  0)) && return 0
    [[ $condition = '<=' ]] && ((diff >= 0)) && return 0
    [[ $condition = '>'  ]] && ((diff <  0)) && return 0
    [[ $condition = '>=' ]] && ((diff <= 0)) && return 0
    return 1
}

Here is the test:
for tv1 in '*' 1.1.1 2.5.3 7.3.0 0.5.7 10.3.9 8.55.32 0.0.1; do
    for tv2 in 3.1.1 1.5.3 4.3.0 0.0.7 0.3.9 11.55.32 10.0.0 '*'; do
      for c in '=' '>' '<' '>=' '<=' '!='; do
        vercmp "$tv1" "$tv2" "$c" && printf '%s\n' "$tv1 $c $tv2 is true" || printf '%s\n' "$tv1 $c $tv2 is false"
      done
    done
done

A subset of the test output:
<snip>

* >= * is true
* <= * is true
* != * is true
1.1.1 = 3.1.1 is false
1.1.1 > 3.1.1 is false
1.1.1 < 3.1.1 is true
1.1.1 >= 3.1.1 is false
1.1.1 <= 3.1.1 is true
1.1.1 != 3.1.1 is true
1.1.1 = 1.5.3 is false
1.1.1 > 1.5.3 is false
1.1.1 < 1.5.3 is true
1.1.1 >= 1.5.3 is false
1.1.1 <= 1.5.3 is true
1.1.1 != 1.5.3 is true
1.1.1 = 4.3.0 is false
1.1.1 > 4.3.0 is false

<snip>

A: Here's a pure Bash solution that supports revisions (e.g. '1.0-r1'), based on the answer posted by Dennis Williamson. It can easily be modified to support stuff like '-RC1' or extract the version from a more complex string  by changing the regular expression.
For details regarding the implementation, please refer to in-code comments and/or enable the included debug code:
#!/bin/bash

# Compare two version strings [$1: version string 1 (v1), $2: version string 2 (v2)]
# Return values:
#   0: v1 == v2
#   1: v1 > v2
#   2: v1 < v2
# Based on: https://stackoverflow.com/a/4025065 by Dennis Williamson
function compare_versions() {

    # Trivial v1 == v2 test based on string comparison
    [[ "$1" == "$2" ]] && return 0

    # Local variables
    local regex="^(.*)-r([0-9]*)$" va1=() vr1=0 va2=() vr2=0 len i IFS="."

    # Split version strings into arrays, extract trailing revisions
    if [[ "$1" =~ ${regex} ]]; then
        va1=(${BASH_REMATCH[1]})
        [[ -n "${BASH_REMATCH[2]}" ]] && vr1=${BASH_REMATCH[2]}
    else
        va1=($1)
    fi
    if [[ "$2" =~ ${regex} ]]; then
        va2=(${BASH_REMATCH[1]})
        [[ -n "${BASH_REMATCH[2]}" ]] && vr2=${BASH_REMATCH[2]}
    else
        va2=($2)
    fi

    # Bring va1 and va2 to same length by filling empty fields with zeros
    (( ${#va1[@]} > ${#va2[@]} )) && len=${#va1[@]} || len=${#va2[@]}
    for ((i=0; i < len; ++i)); do
        [[ -z "${va1[i]}" ]] && va1[i]="0"
        [[ -z "${va2[i]}" ]] && va2[i]="0"
    done

    # Append revisions, increment length
    va1+=($vr1)
    va2+=($vr2)
    len=$((len+1))

    # *** DEBUG ***
    #echo "TEST: '${va1[@]} (?) ${va2[@]}'"

    # Compare version elements, check if v1 > v2 or v1 < v2
    for ((i=0; i < len; ++i)); do
        if (( 10#${va1[i]} > 10#${va2[i]} )); then
            return 1
        elif (( 10#${va1[i]} < 10#${va2[i]} )); then
            return 2
        fi
    done

    # All elements are equal, thus v1 == v2
    return 0
}

# ---------- everything below this line is just for testing ----------

# Test compare_versions [$1: version string 1, $2: version string 2, $3: expected result]
function test_compare_versions() {
    local op
    compare_versions "$1" "$2"
    case $? in
        0) op="==" ;;
        1) op=">" ;;
        2) op="<" ;;
    esac
    if [[ "$op" == "$3" ]]; then
        echo -e "\e[1;32mPASS: '$1 $op $2'\e[0m"
    else
        echo -e "\e[1;31mFAIL: '$1 $3 $2' (result: '$1 $op $2')\e[0m"
    fi
}

echo -e "\nThe following tests should pass:"
while read -r test; do
    test_compare_versions $test
done << EOF
1            1            ==
2.1          2.2          <
3.0.4.10     3.0.4.2      >
4.08         4.08.01      <
3.2.1.9.8144 3.2          >
3.2          3.2.1.9.8144 <
1.2          2.1          <
2.1          1.2          >
5.6.7        5.6.7        ==
1.01.1       1.1.1        ==
1.1.1        1.01.1       ==
1            1.0          ==
1.0          1            ==
1.0.2.0      1.0.2        ==
1..0         1.0          ==
1.0          1..0         ==
1.0-r1       1.0-r3       <
1.0-r9       2.0          <
3.0-r15      3.0-r9       >
...-r1       ...-r2       <
2.0-r1       1.9.8.21-r2  >
1.0          3.8.9.32-r   <
-r           -r3          <
-r3          -r           >
-r3          -r3          ==
-r           -r           ==
0.0-r2       0.0.0.0-r2   ==
1.0.0.0-r2   1.0-r2       ==
0.0.0.1-r7   -r9          >
0.0-r0       0            ==
1.002.0-r6   1.2.0-r7     <
001.001-r2   1.1-r2       ==
5.6.1-r0     5.6.1        ==
EOF

echo -e "\nThe following tests should fail:"
while read -r test; do
    test_compare_versions $test
done << EOF
1            1            >
3.0.5-r5     3..5-r5      >
4.9.21-r3    4.8.22-r9    <
1.0-r        1.0-r1       ==
-r           1.0-r        >
-r1          0.0-r1       <
-r2          0-r2         <
EOF

A: This is also a pure bash solution, as printf is a bash builtin.
function ver()
# Description: use for comparisons of version strings.
# $1  : a version string of form 1.2.3.4
# use: (( $(ver 1.2.3.4) >= $(ver 1.2.3.3) )) && echo "yes" || echo "no"
{
    printf "%02d%02d%02d%02d" ${1//./ }
}

A: Well if you know the number of fields you can use -k n,n and get a super-simple solution
echo '2.4.5
2.8
2.4.5.1
2.10.2' | sort -t '.' -k 1,1 -k 2,2 -k 3,3 -k 4,4 -g

2.4.5
2.4.5.1
2.8
2.10.2

A: I'm using embedded Linux (Yocto) with BusyBox. BusyBox sort doesn't have a -V option (but BusyBox expr match can do regular expressions). So I needed a Bash version compare which worked with that constraint.
I've made the following (similar to Dennis Williamson's answer) to compare using a "natural sort" type of algorithm. It splits the string into numeric parts and non-numeric parts; it compares the numeric parts numerically (so 10 is greater than 9), and compares the non-numeric parts as a plain ASCII comparison.
ascii_frag() {
    expr match "$1" "\([^[:digit:]]*\)"
}

ascii_remainder() {
    expr match "$1" "[^[:digit:]]*\(.*\)"
}

numeric_frag() {
    expr match "$1" "\([[:digit:]]*\)"
}

numeric_remainder() {
    expr match "$1" "[[:digit:]]*\(.*\)"
}

vercomp_debug() {
    OUT="$1"
    #echo "${OUT}"
}

# return 1 for $1 > $2
# return 2 for $1 < $2
# return 0 for equal
vercomp() {
    local WORK1="$1"
    local WORK2="$2"
    local NUM1="", NUM2="", ASCII1="", ASCII2=""
    while true; do
        vercomp_debug "ASCII compare"
        ASCII1=`ascii_frag "${WORK1}"`
        ASCII2=`ascii_frag "${WORK2}"`
        WORK1=`ascii_remainder "${WORK1}"`
        WORK2=`ascii_remainder "${WORK2}"`
        vercomp_debug "\"${ASCII1}\" remainder \"${WORK1}\""
        vercomp_debug "\"${ASCII2}\" remainder \"${WORK2}\""

        if [ "${ASCII1}" \> "${ASCII2}" ]; then
            vercomp_debug "ascii ${ASCII1} > ${ASCII2}"
            return 1
        elif [ "${ASCII1}" \< "${ASCII2}" ]; then
            vercomp_debug "ascii ${ASCII1} < ${ASCII2}"
            return 2
        fi
        vercomp_debug "--------"

        vercomp_debug "Numeric compare"
        NUM1=`numeric_frag "${WORK1}"`
        NUM2=`numeric_frag "${WORK2}"`
        WORK1=`numeric_remainder "${WORK1}"`
        WORK2=`numeric_remainder "${WORK2}"`
        vercomp_debug "\"${NUM1}\" remainder \"${WORK1}\""
        vercomp_debug "\"${NUM2}\" remainder \"${WORK2}\""

        if [ -z "${NUM1}" -a -z "${NUM2}" ]; then
            vercomp_debug "blank 1 and blank 2 equal"
            return 0
        elif [ -z "${NUM1}" -a -n "${NUM2}" ]; then
            vercomp_debug "blank 1 less than non-blank 2"
            return 2
        elif [ -n "${NUM1}" -a -z "${NUM2}" ]; then
            vercomp_debug "non-blank 1 greater than blank 2"
            return 1
        fi

        if [ "${NUM1}" -gt "${NUM2}" ]; then
            vercomp_debug "num ${NUM1} > ${NUM2}"
            return 1
        elif [ "${NUM1}" -lt "${NUM2}" ]; then
            vercomp_debug "num ${NUM1} < ${NUM2}"
            return 2
        fi
        vercomp_debug "--------"
    done
}

It can compare more complicated version numbers such as

*

*1.2-r3 versus 1.2-r4

*1.2rc3 versus 1.2r4
Note that it doesn't return the same result for some of the corner-cases in Dennis Williamson's answer. In particular:
1            1.0          <
1.0          1            >
1.0.2.0      1.0.2        >
1..0         1.0          >
1.0          1..0         <

But those are corner cases, and I think the results are still reasonable.

A: You all gave complicated solutions. Here's a simpler one.
function compare_versions {
    local a=${1%%.*} b=${2%%.*}
    [[ "10#${a:-0}" -gt "10#${b:-0}" ]] && return 1
    [[ "10#${a:-0}" -lt "10#${b:-0}" ]] && return 2
    a=${1:${#a} + 1} b=${2:${#b} + 1}
    [[ -z $a && -z $b ]] || compare_versions "$a" "$b"
}

Usage: compare_versions <ver_a> <ver_b>
Return code 1 means first version is greater than second, 2 means less, and 0 means both are equal.

Also a non-recursive version:
function compare_versions {
    local a=$1 b=$2 x y

    while [[ $a || $b ]]; do
        x=${a%%.*} y=${b%%.*}
        [[ "10#${x:-0}" -gt "10#${y:-0}" ]] && return 1
        [[ "10#${x:-0}" -lt "10#${y:-0}" ]] && return 2
        a=${a:${#x} + 1} b=${b:${#y} + 1}
    done

    return 0
}

A: Here is a pure Bash version that doesn't require any external utilities:
#!/bin/bash
vercomp () {
    if [[ $1 == $2 ]]
    then
        return 0
    fi
    local IFS=.
    local i ver1=($1) ver2=($2)
    # fill empty fields in ver1 with zeros
    for ((i=${#ver1[@]}; i<${#ver2[@]}; i++))
    do
        ver1[i]=0
    done
    for ((i=0; i<${#ver1[@]}; i++))
    do
        if [[ -z ${ver2[i]} ]]
        then
            # fill empty fields in ver2 with zeros
            ver2[i]=0
        fi
        if ((10#${ver1[i]} > 10#${ver2[i]}))
        then
            return 1
        fi
        if ((10#${ver1[i]} < 10#${ver2[i]}))
        then
            return 2
        fi
    done
    return 0
}

testvercomp () {
    vercomp $1 $2
    case $? in
        0) op='=';;
        1) op='>';;
        2) op='<';;
    esac
    if [[ $op != $3 ]]
    then
        echo "FAIL: Expected '$3', Actual '$op', Arg1 '$1', Arg2 '$2'"
    else
        echo "Pass: '$1 $op $2'"
    fi
}

# Run tests
# argument table format:
# testarg1   testarg2     expected_relationship
echo "The following tests should pass"
while read -r test
do
    testvercomp $test
done << EOF
1            1            =
2.1          2.2          <
3.0.4.10     3.0.4.2      >
4.08         4.08.01      <
3.2.1.9.8144 3.2          >
3.2          3.2.1.9.8144 <
1.2          2.1          <
2.1          1.2          >
5.6.7        5.6.7        =
1.01.1       1.1.1        =
1.1.1        1.01.1       =
1            1.0          =
1.0          1            =
1.0.2.0      1.0.2        =
1..0         1.0          =
1.0          1..0         =
EOF

echo "The following test should fail (test the tester)"
testvercomp 1 1 '>'

Run the tests:
$ . ./vercomp
The following tests should pass
Pass: '1 = 1'
Pass: '2.1 < 2.2'
Pass: '3.0.4.10 > 3.0.4.2'
Pass: '4.08 < 4.08.01'
Pass: '3.2.1.9.8144 > 3.2'
Pass: '3.2 < 3.2.1.9.8144'
Pass: '1.2 < 2.1'
Pass: '2.1 > 1.2'
Pass: '5.6.7 = 5.6.7'
Pass: '1.01.1 = 1.1.1'
Pass: '1.1.1 = 1.01.1'
Pass: '1 = 1.0'
Pass: '1.0 = 1'
Pass: '1.0.2.0 = 1.0.2'
Pass: '1..0 = 1.0'
Pass: '1.0 = 1..0'
The following test should fail (test the tester)
FAIL: Expected '>', Actual '=', Arg1 '1', Arg2 '1'

A: This is for at most 4 fields in the version.
$ function ver { printf "%03d%03d%03d%03d" $(echo "$1" | tr '.' ' '); }
$ [ $(ver 10.9) -lt $(ver 10.10) ] && echo hello
hello

A: If you have coreutils-7 (in Ubuntu Karmic but not Jaunty) then your sort command should have a -V option (version sort) which you could use to do the comparison:
verlte() {
    [  "$1" = "`echo -e "$1\n$2" | sort -V | head -n1`" ]
}

verlt() {
    [ "$1" = "$2" ] && return 1 || verlte $1 $2
}

verlte 2.5.7 2.5.6 && echo "yes" || echo "no" # no
verlt 2.4.10 2.4.9 && echo "yes" || echo "no" # no
verlt 2.4.8 2.4.10 && echo "yes" || echo "no" # yes
verlte 2.5.6 2.5.6 && echo "yes" || echo "no" # yes
verlt 2.5.6 2.5.6 && echo "yes" || echo "no" # no

A: For old version/busybox sort. Simple form provide roughly result and often works.
sort -n

This is escpecial useful on version which contains alpha symbols like
10.c.3
10.a.4
2.b.5

A: Here's a refinement of the top answer (Dennis's) that is more concise and uses a different return value scheme to make it easy to implement <= and >= with a single comparison. It also compares everything after the first character not in [0-9.] lexicographically, so 1.0rc1 < 1.0rc2.
# Compares two tuple-based, dot-delimited version numbers a and b (possibly
# with arbitrary string suffixes). Returns:
# 1 if a<b
# 2 if equal
# 3 if a>b
# Everything after the first character not in [0-9.] is compared
# lexicographically using ASCII ordering if the tuple-based versions are equal.
compare_versions() {
    if [[ $1 == "$2" ]]; then
        return 2
    fi
    local IFS=.
    local i a=(${1%%[^0-9.]*}) b=(${2%%[^0-9.]*})
    local arem=${1#${1%%[^0-9.]*}} brem=${2#${2%%[^0-9.]*}}
    for ((i=0; i<${#a[@]} || i<${#b[@]}; i++)); do
        if ((10#${a[i]:-0} < 10#${b[i]:-0})); then
            return 1
        elif ((10#${a[i]:-0} > 10#${b[i]:-0})); then
            return 3
        fi
    done
    if [ "$arem" '<' "$brem" ]; then
        return 1
    elif [ "$arem" '>' "$brem" ]; then
        return 3
    fi
    return 2
}

To address @gammazero's comment, a longer version that (I think) is compatible with semantic versioning is this:
# Compares two dot-delimited decimal-element version numbers a and b that may
# also have arbitrary string suffixes. Compatible with semantic versioning, but
# not as strict: comparisons of non-semver strings may have unexpected
# behavior.
#
# Returns:
# 1 if a<b
# 2 if equal
# 3 if a>b
compare_versions() {
    local LC_ALL=C

    # Optimization
    if [[ $1 == "$2" ]]; then
        return 2
    fi

    # Compare numeric release versions. Supports an arbitrary number of numeric
    # elements (i.e., not just X.Y.Z) in which unspecified indices are regarded
    # as 0.
    local aver=${1%%[^0-9.]*} bver=${2%%[^0-9.]*}
    local arem=${1#$aver} brem=${2#$bver}
    local IFS=.
    local i a=($aver) b=($bver)
    for ((i=0; i<${#a[@]} || i<${#b[@]}; i++)); do
        if ((10#${a[i]:-0} < 10#${b[i]:-0})); then
            return 1
        elif ((10#${a[i]:-0} > 10#${b[i]:-0})); then
            return 3
        fi
    done

    # Remove build metadata before remaining comparison
    arem=${arem%%+*}
    brem=${brem%%+*}

    # Prelease (w/remainder) always older than release (no remainder)
    if [ -n "$arem" -a -z "$brem" ]; then
        return 1
    elif [ -z "$arem" -a -n "$brem" ]; then
        return 3
    fi

    # Otherwise, split by periods and compare individual elements either
    # numerically or lexicographically
    local a=(${arem#-}) b=(${brem#-})
    for ((i=0; i<${#a[@]} && i<${#b[@]}; i++)); do
        local anns=${a[i]#${a[i]%%[^0-9]*}} bnns=${b[i]#${b[i]%%[^0-9]*}}
        if [ -z "$anns$bnns" ]; then
            # Both numeric
            if ((10#${a[i]:-0} < 10#${b[i]:-0})); then
                return 1
            elif ((10#${a[i]:-0} > 10#${b[i]:-0})); then
                return 3
            fi
        elif [ -z "$anns" ]; then
            # Numeric comes before non-numeric
            return 1
        elif [ -z "$bnns" ]; then
            # Numeric comes before non-numeric
            return 3
        else
            # Compare lexicographically
            if [[ ${a[i]} < ${b[i]} ]]; then
                return 1
            elif [[ ${a[i]} > ${b[i]} ]]; then
                return 3
            fi
        fi
    done

    # Fewer elements is earlier
    if (( ${#a[@]} < ${#b[@]} )); then
        return 1
    elif (( ${#a[@]} > ${#b[@]} )); then
        return 3
    fi

    # Must be equal!
    return 2
}

A: You can recursively split on . and compare as shown in the following algorithm, taken from here. It returns 10 if the versions are the same, 11 if version 1 is greater than version 2 and 9 otherwise.
#!/bin/bash
do_version_check() {

   [ "$1" == "$2" ] && return 10

   ver1front=`echo $1 | cut -d "." -f -1`
   ver1back=`echo $1 | cut -d "." -f 2-`

   ver2front=`echo $2 | cut -d "." -f -1`
   ver2back=`echo $2 | cut -d "." -f 2-`

   if [ "$ver1front" != "$1" ] || [ "$ver2front" != "$2" ]; then
       [ "$ver1front" -gt "$ver2front" ] && return 11
       [ "$ver1front" -lt "$ver2front" ] && return 9

       [ "$ver1front" == "$1" ] || [ -z "$ver1back" ] && ver1back=0
       [ "$ver2front" == "$2" ] || [ -z "$ver2back" ] && ver2back=0
       do_version_check "$ver1back" "$ver2back"
       return $?
   else
           [ "$1" -gt "$2" ] && return 11 || return 9
   fi
}

do_version_check "$1" "$2"

Source

A: *

*Function V - pure bash solution, no external utilities required.

*Supports = == != < <= > and >= (lexicographic).

*Optional tail letter comparison: 1.5a < 1.5b

*Unequal length comparison: 1.6 > 1.5b

*Reads left-to-right: if V 1.5 '<' 1.6; then ....

<>
# Sample output
# Note: ++ (true) and __ (false) mean that V works correctly.

++ 3.6 '>' 3.5b
__ 2.5.7 '<=' 2.5.6
++ 2.4.10 '<' 2.5.9
__ 3.0002 '>' 3.0003.3
++ 4.0-RC2 '>' 4.0-RC1

<>
function V() # $1-a $2-op $3-$b
# Compare a and b as version strings. Rules:
# R1: a and b : dot-separated sequence of items. Items are numeric. The last item can optionally end with letters, i.e., 2.5 or 2.5a.
# R2: Zeros are automatically inserted to compare the same number of items, i.e., 1.0 < 1.0.1 means 1.0.0 < 1.0.1 => yes.
# R3: op can be '=' '==' '!=' '<' '<=' '>' '>=' (lexicographic).
# R4: Unrestricted number of digits of any item, i.e., 3.0003 > 3.0000004.
# R5: Unrestricted number of items.
{
  local a=$1 op=$2 b=$3 al=${1##*.} bl=${3##*.}
  while [[ $al =~ ^[[:digit:]] ]]; do al=${al:1}; done
  while [[ $bl =~ ^[[:digit:]] ]]; do bl=${bl:1}; done
  local ai=${a%$al} bi=${b%$bl}

  local ap=${ai//[[:digit:]]} bp=${bi//[[:digit:]]}
  ap=${ap//./.0} bp=${bp//./.0}

  local w=1 fmt=$a.$b x IFS=.
  for x in $fmt; do [ ${#x} -gt $w ] && w=${#x}; done
  fmt=${*//[^.]}; fmt=${fmt//./%${w}s}
  printf -v a $fmt $ai$bp; printf -v a "%s-%${w}s" $a $al
  printf -v b $fmt $bi$ap; printf -v b "%s-%${w}s" $b $bl

  case $op in
    '<='|'>=' ) [ "$a" ${op:0:1} "$b" ] || [ "$a" = "$b" ] ;;
    * )         [ "$a" $op "$b" ] ;;
  esac
}

Code Explained
Line 1: Define local variables:

*

*a, op, b - comparison operands and operator, i.e., "3.6" > "3.5a".

*al, bl - letter tails of a and b, initialized to the tail item, i.e., "6" and "5a".

Lines 2, 3: Left-trim digits from the tail items so only letters are left, if any, i.e., "" and "a".
Line 4: Right trim letters from a and b to leave just the sequence of numeric items as local variables ai and bi, i.e., "3.6" and "3.5".
Notable example: "4.01-RC2" > "4.01-RC1" yields ai="4.01" al="-RC2" and bi="4.01" bl="-RC1".
Line 6: Define local variables:

*

*ap, bp - zero right-paddings for ai and bi. Start by keeping the inter-item dots only, of which number equals the number of elements of a and b respectively.

Line 7: Then append "0" after each dot to make padding masks.
Line 9: Local variables:

*

*w - item width

*fmt - printf format string, to be calculated

*x - temporary

*With IFS=. bash splits variable values at '.'.

Line 10: Calculate w, the maximum item width, which will be used to align items for lexicographic comparison. In our example w=2.
Line 11: Create the printf alignment format by replacing each character of $a.$b with %${w}s, i.e., "3.6" > "3.5a" yields "%2s%2s%2s%2s".
Line 12: "printf -v a" sets the value of variable a. This is equivalent to a=sprintf(...) in many programming languages.  Note that here, by effect of IFS=. the arguments to printf split into individual items.
With the first printf items of a are left-padded with spaces while enough "0" items are appended from bp to ensure that the resulting string a can be meaningfully compared to a similarly formatted b.
Note that we append bp - not ap to ai because ap and bp may have different lenghts, so this results in a and b having equal lengths.
With the second printf we append the letter part al to a with enough padding to enable meaningful comparison. Now a is ready for comparison with b.
Line 13: Same as line 12 but for b.
Line 15: Split comparison cases between non-built-in (<= and >=) and built-in operators.
Line 16: If the comparison operator is <= then test for a<b or a=b - respectively >= a<b or a=b
Line 17: Test for built-in comparison operators.
<>
# All tests

function P { printf "$@"; }
function EXPECT { printf "$@"; }
function CODE { awk $BASH_LINENO'==NR{print " "$2,$3,$4}' "$0"; }
P 'Note: ++ (true) and __ (false) mean that V works correctly.\n'

V 2.5    '!='  2.5      && P + || P _; EXPECT _; CODE
V 2.5    '='   2.5      && P + || P _; EXPECT +; CODE
V 2.5    '=='  2.5      && P + || P _; EXPECT +; CODE

V 2.5a   '=='  2.5b     && P + || P _; EXPECT _; CODE
V 2.5a   '<'   2.5b     && P + || P _; EXPECT +; CODE
V 2.5a   '>'   2.5b     && P + || P _; EXPECT _; CODE
V 2.5b   '>'   2.5a     && P + || P _; EXPECT +; CODE
V 2.5b   '<'   2.5a     && P + || P _; EXPECT _; CODE
V 3.5    '<'   3.5b     && P + || P _; EXPECT +; CODE
V 3.5    '>'   3.5b     && P + || P _; EXPECT _; CODE
V 3.5b   '>'   3.5      && P + || P _; EXPECT +; CODE
V 3.5b   '<'   3.5      && P + || P _; EXPECT _; CODE
V 3.6    '<'   3.5b     && P + || P _; EXPECT _; CODE
V 3.6    '>'   3.5b     && P + || P _; EXPECT +; CODE
V 3.5b   '<'   3.6      && P + || P _; EXPECT +; CODE
V 3.5b   '>'   3.6      && P + || P _; EXPECT _; CODE

V 2.5.7  '<='  2.5.6    && P + || P _; EXPECT _; CODE
V 2.4.10 '<'   2.4.9    && P + || P _; EXPECT _; CODE
V 2.4.10 '<'   2.5.9    && P + || P _; EXPECT +; CODE
V 3.4.10 '<'   2.5.9    && P + || P _; EXPECT _; CODE
V 2.4.8  '>'   2.4.10   && P + || P _; EXPECT _; CODE
V 2.5.6  '<='  2.5.6    && P + || P _; EXPECT +; CODE
V 2.5.6  '>='  2.5.6    && P + || P _; EXPECT +; CODE
V 3.0    '<'   3.0.3    && P + || P _; EXPECT +; CODE
V 3.0002 '<'   3.0003.3 && P + || P _; EXPECT +; CODE
V 3.0002 '>'   3.0003.3 && P + || P _; EXPECT _; CODE
V 3.0003.3 '<' 3.0002   && P + || P _; EXPECT _; CODE
V 3.0003.3 '>' 3.0002   && P + || P _; EXPECT +; CODE

V 4.0-RC2 '>' 4.0-RC1   && P + || P _; EXPECT +; CODE
V 4.0-RC2 '<' 4.0-RC1   && P + || P _; EXPECT _; CODE

A: How about this?  Seems to work?
checkVersion() {
subVer1=$1
subVer2=$2

[ "$subVer1" == "$subVer2" ] && echo "Version is same"
echo "Version 1 is $subVer1"
testVer1=$subVer1
echo "Test version 1 is $testVer1"
x=0
while [[ $testVer1 != "" ]]
do
  ((x++))
  testVer1=`echo $subVer1|cut -d "." -f $x`
  echo "testVer1 now is $testVer1"
  testVer2=`echo $subVer2|cut -d "." -f $x`
  echo "testVer2 now is $testVer2"
  if [[ $testVer1 -gt $testVer2 ]]
  then
    echo "$ver1 is greater than $ver2"
    break
  elif [[ "$testVer2" -gt "$testVer1" ]]
  then
    echo "$ver2 is greater than $ver1"
    break
  fi
  echo "This is the sub verion for first value $testVer1"
  echo "This is the sub verion for second value $testVer2"
done
}

ver1=$1
ver2=$2
checkVersion "$ver1" "$ver2"

A: Here is another pure bash solution without any external calls:
#!/bin/bash

function version_compare {

IFS='.' read -ra ver1 <<< "$1"
IFS='.' read -ra ver2 <<< "$2"

[[ ${#ver1[@]} -gt ${#ver2[@]} ]] && till=${#ver1[@]} || till=${#ver2[@]}

for ((i=0; i<${till}; i++)); do

    local num1; local num2;

    [[ -z ${ver1[i]} ]] && num1=0 || num1=${ver1[i]}
    [[ -z ${ver2[i]} ]] && num2=0 || num2=${ver2[i]}

    if [[ $num1 -gt $num2 ]]; then
        echo ">"; return 0
    elif
       [[ $num1 -lt $num2 ]]; then
        echo "<"; return 0
    fi
done

echo "="; return 0
}

echo "${1} $(version_compare "${1}" "${2}") ${2}"

And there is even more simple solution, if you are sure that the versions in question do not contain leading zeros after the first dot:
#!/bin/bash

function version_compare {

local ver1=${1//.}
local ver2=${2//.}

    if [[ $ver1 -gt $ver2 ]]; then
        echo ">"; return 0
    elif
       [[ $ver1 -lt $ver2 ]]; then
        echo "<"; return 0
    fi

echo "="; return 0
}

echo "${1} $(version_compare "${1}" "${2}") ${2}"

This will work for something like 1.2.3 vs 1.3.1 vs 0.9.7, but won't work with
1.2.3 vs 1.2.3.0 or 1.01.1 vs 1.1.1

A: I implemented yet another comparator function. This one had two specific requirements: (i) I didn't want the function to fail by using return 1 but echo instead; (ii) as we're retrieving versions from a git repository version "1.0" should be bigger than "1.0.2", meaning that "1.0" comes from trunk.
function version_compare {
  IFS="." read -a v_a <<< "$1"
  IFS="." read -a v_b <<< "$2"

  while [[ -n "$v_a" || -n "$v_b" ]]; do
    [[ -z "$v_a" || "$v_a" -gt "$v_b" ]] && echo 1 && return
    [[ -z "$v_b" || "$v_b" -gt "$v_a" ]] && echo -1 && return

    v_a=("${v_a[@]:1}")
    v_b=("${v_b[@]:1}")
  done

  echo 0
}

Feel free to comment and suggest improvements.

A: You can use version CLI to check version's constraints
$ version ">=1.0, <2.0" "1.7"
$ go version | version ">=1.9"

Bash script example:
#!/bin/bash

if `version -b ">=9.0.0" "$(gcc --version)"`; then
  echo "gcc version satisfies constraints >=9.0.0"
else
  echo "gcc version doesn't satisfies constraints >=9.0.0"
fi

A: Wow... this is way down the list of an old question, but I think this is a pretty elegant answer. First convert each dot-separated version into its own array, using shell parameter expansion (See Shell Parameter Expansion).
v1="05.2.3"     # some evil examples that work here
v2="7.001.0.0"

declare -a v1_array=(${v1//./ })
declare -a v2_array=(${v2//./ })

Now the two arrays have the version number as a numerical string in priority order. Lots of the above solutions take you from there, but it all derives from the observation that version string is just an integer with an arbitrary base. We can test finding the first unequal digit (like strcmp does for characters in a string).
compare_version() {
  declare -a v1_array=(${1//./ })
  declare -a v2_array=(${2//./ })

  while [[ -nz $v1_array ]] || [[ -nz $v2_array ]]; do
    let v1_val=${v1_array:-0}  # this will remove any leading zeros
    let v2_val=${v2_array:-0}
    let result=$((v1_val-v2_val))

    if (( result != 0 )); then
      echo $result
      return
    fi

    v1_array=("${v1_array[@]:1}") # trim off the first "digit". it doesn't help
    v2_array=("${v2_array[@]:1}")
  done

  # if we get here, both the arrays are empty and neither has been numerically
  # different, which is equivalent to the two versions being equal

  echo 0
  return
}

This echoes a negative number if the first version is less than the second, a zero if they're equal and a positive number if the first version is greater. Some output:
$ compare_version 1 1.2
-2
$ compare_version "05.1.3" "5.001.03.0.0.0.1"
-1
$ compare_version "05.1.3" "5.001.03.0.0.0"
0
$ compare_version "05.1.3" "5.001.03.0"
0
$ compare_version "05.1.3" "5.001.30.0"
-27
$ compare_version "05.2.3" "7.001.0.0"
-2
$ compare_version "05.1.3" "5.001.30.0"
-27
$ compare_version "7.001.0.0" "05.1.3"
2

Degenerate cases like, ".2" or "3.0." don't work (undefined results), and if non-numeric characters are present beside the '.' it might fail (haven't tested) but will certainly be undefined. So this should be paired with a sanitizing function or appropriate check for valid formatting. Also, I'm sure with some tweaking, this could be made more robust without too much extra baggage.

A: ver_cmp()
{
    local IFS=.
    local V1=($1) V2=($2) I
    for ((I=0 ; I<${#V1[*]} || I<${#V2[*]} ; I++)) ; do
        [[ ${V1[$I]:-0} -lt ${V2[$I]:-0} ]] && echo -1 && return
        [[ ${V1[$I]:-0} -gt ${V2[$I]:-0} ]] && echo 1 && return
    done
    echo 0
}

ver_eq()
{
    [[ $(ver_cmp "$1" "$2") -eq 0 ]]
}

ver_lt()
{
    [[ $(ver_cmp "$1" "$2") -eq -1 ]]
}

ver_gt()
{
    [[ $(ver_cmp "$1" "$2") -eq 1 ]]
}

ver_le()
{
    [[ ! $(ver_cmp "$1" "$2") -eq 1 ]]
}

ver_ge()
{
    [[ ! $(ver_cmp "$1" "$2") -eq -1 ]]
}

To test:
( ( while read V1 V2 ; do echo $V1 $(ver_cmp $V1 $V2) $V2 ; done ) <<EOF
1.2.3 2.2.3
2.2.3 2.2.2
3.10 3.2
2.2 2.2.1
3.1 3.1.0
EOF
) | sed 's/ -1 / < / ; s/ 0 / = / ; s/ 1 / > /' | column -t

1.2.3  <  2.2.3
2.2.3  >  2.2.2
3.10   >  3.2
2.2    <  2.2.1
3.1    =  3.1.0

ver_lt 10.1.2 10.1.20 && echo 'Your version is too old'

Your version is too old

A: When the Bash gets too complicated, just pipe it into python!
vercomp(){ echo "$1" "$2" | python3 -c "import re, sys; arr = lambda x: list(map(int, re.split('[^0-9]+', x))); x, y = map(arr, sys.stdin.read().split()); exit(not x >= y)"; }

Example comparing two version numbers:
vercomp 2.8 2.4.5 && echo ">=" || echo "<"

This python one liner compares the left version number to the right version number and exits 0 if the left version is equal or higher. It also handles versions like 2.4.5rc3
Broken down, this is the readable code:
import re, sys

# Convert a version string into a list "2.4.5" -> [2, 4, 5]
arr = lambda x: list(map(int, re.split('[^0-9]+', x)))

# Read the version numbers from stdin and apply the above function to them
x, y = map(arr, sys.stdin.read().split())

# Exit 0 if the left number is greater than the right
exit(not x >= y)

A: I came across and solved this problem, to add an additional (and shorter and simpler) answer...
First note, extended shell comparison failed as you may already know...
    if [[ 1.2.0 < 1.12.12 ]]; then echo true; else echo false; fi
    false

Using the sort -t'.'-g (or sort -V as mentioned by kanaka) to order versions and simple bash string comparison I found a solution.  The input file contains versions in columns 3 and 4 which I want to compare.  This iterates through the list identifying a match or if one is greater than the other.  Hope this may still help anyone looking to do this using bash as simple as possible.
while read l
do
    #Field 3 contains version on left to compare (change -f3 to required column).
    kf=$(echo $l | cut -d ' ' -f3)
    #Field 4 contains version on right to compare (change -f4 to required column).
    mp=$(echo $l | cut -d ' ' -f4)

    echo 'kf = '$kf
    echo 'mp = '$mp

    #To compare versions m.m.m the two can be listed and sorted with a . separator and the greater version found.
    gv=$(echo -e $kf'\n'$mp | sort -t'.' -g | tail -n 1)

    if [ $kf = $mp ]; then
        echo 'Match Found: '$l
    elif [ $kf = $gv ]; then
        echo 'Karaf feature file version is greater '$l
    elif [ $mp = $gv ]; then
        echo 'Maven pom file version is greater '$l
   else
       echo 'Comparison error '$l
   fi
done < features_and_pom_versions.tmp.txt

Thanks to Barry's blog for the sort idea...
ref: http://bkhome.org/blog/?viewDetailed=02199

A: ### the answer is does we second argument is higher
function _ver_higher {
        ver=`echo -ne "$1\n$2" |sort -Vr |head -n1`
        if [ "$2" == "$1" ]; then
                return 1
        elif [ "$2" == "$ver" ]; then
                return 0
        else
                return 1
        fi
}

if _ver_higher $1 $2; then
        echo higher
else
        echo same or less
fi

It's pretty simple and small.

A: Thanks to Dennis's solution, we can extend it to allow comparison operators '>', '<', '=', '==', '<=', and '>='.
# compver ver1 '=|==|>|<|>=|<=' ver2
compver() {
    local op
    vercomp $1 $3
    case $? in
        0) op='=';;
        1) op='>';;
        2) op='<';;
    esac
    [[ $2 == *$op* ]] && return 0 || return 1
}

We can then use comparison operators in the expressions like:
compver 1.7 '<=' 1.8
compver 1.7 '==' 1.7
compver 1.7 '=' 1.7

and test only the true/false of the result, like:
if compver $ver1 '>' $ver2; then
    echo "Newer"
fi

A: Here's another pure bash version, rather smaller than the accepted answer. It only checks whether a version is less than or equal to a "minimum version", and it will check alphanumeric sequences lexicographically, which often gives the wrong result ("snapshot" is not later than "release", to give a common example). It will work fine for major/minor.
is_number() {
    case "$BASH_VERSION" in
        3.1.*)
            PATTERN='\^\[0-9\]+\$'
            ;;
        *)
            PATTERN='^[0-9]+$'
            ;;
    esac

    [[ "$1" =~ $PATTERN ]]
}

min_version() {
    if [[ $# != 2 ]]
    then
        echo "Usage: min_version current minimum"
        return
    fi

    A="${1%%.*}"
    B="${2%%.*}"

    if [[ "$A" != "$1" && "$B" != "$2" && "$A" == "$B" ]]
    then
        min_version "${1#*.}" "${2#*.}"
    else
        if is_number "$A" && is_number "$B"
        then
            [[ "$A" -ge "$B" ]]
        else
            [[ ! "$A" < "$B" ]]
        fi
    fi
}

A: Another approach(modified version of @joynes) that compares dotted versions as asked in the question
 (i.e "1.2", "2.3.4", "1.0", "1.10.1", etc.).
The maximum number of positions has to be known in advance. The approach expects max 3 version positions.
expr $(printf "$1\n$2" | sort -t '.' -k 1,1 -k 2,2 -k 3,3 -g | sed -n 2p) != $2

example usage:
expr $(printf "1.10.1\n1.7" | sort -t '.' -k 1,1 -k 2,2 -k 3,3 -g | sed -n 2p) != "1.7"

returns: 1 since 1.10.1 is bigger than 1.7
expr $(printf "1.10.1\n1.11" | sort -t '.' -k 1,1 -k 2,2 -k 3,3 -g | sed -n 2p) != "1.11"

returns: 0 since 1.10.1 is lower than 1.11

A: function version_compare () {
  function sub_ver () {
    local len=${#1}
    temp=${1%%"."*} && indexOf=`echo ${1%%"."*} | echo ${#temp}`
    echo -e "${1:0:indexOf}"
  }
  function cut_dot () {
    local offset=${#1}
    local length=${#2}
    echo -e "${2:((++offset)):length}"
  }
  if [ -z "$1" ] || [ -z "$2" ]; then
    echo "=" && exit 0
  fi
  local v1=`echo -e "${1}" | tr -d '[[:space:]]'`
  local v2=`echo -e "${2}" | tr -d '[[:space:]]'`
  local v1_sub=`sub_ver $v1`
  local v2_sub=`sub_ver $v2`
  if (( v1_sub > v2_sub )); then
    echo ">"
  elif (( v1_sub < v2_sub )); then
    echo "<"
  else
    version_compare `cut_dot $v1_sub $v1` `cut_dot $v2_sub $v2`
  fi
}

### Usage:

version_compare "1.2.3" "1.2.4"
# Output: <

Credit goes to @Shellman

A: I didn't like any of these solutions because they're buggy, non-portable, etc.
My (current) effort to produce a better solution... src:version_compare(), tests
Sorta-copied/Pasted here...
Source:
##
# Compare two versions.
#
# **Usage:** version_compare version1 operator version2
#
# - operator:
#
#   + ``lesser_than``, ``-lt``, ``<``
#   + ``lesser_than_or_equal``, ``-le``, ``<=``
#   + ``greater_than``, ``-gt``, ``>``
#   + ``greater_than_or_equal``, ``-ge``, ``>=``
#   + ``equal``, ``-eq``, ``==``
#   + ``not_equal``, ``-ne``, ``!=``
#
# - version{1,2}: arbitrary version strings to compare
#
# **Version Format:** ``[0-9]+($VERSION_SEPARATOR[0-9]+)*`` (i.e. 1, 1.0, 90, 1.2.3.4)
#
# **Returns:** true if comparison statement is correct
##
version_compare() {
    _largest_version "$1" "$3"; _cmp="$(printf '%s' "$?")"

    # Check for valid responses or bail early
    case "$_cmp" in
        1|0|2) :;;
        *) _die "$_cmp" 'version comparison failed';;
    esac

    # The easy part
    case "$2" in
        'lesser_than'|'-lt'|'<')
            [ "$_cmp" = '2' ] && return 0
            ;;
        'lesser_or_equal'|'-le'|'<=')
            [ "$_cmp" = '0' ] && return 0
            [ "$_cmp" = '2' ] && return 0
            ;;
        'greater_than'|'-gt'|'>')
            [ "$_cmp" = '1' ] && return 0
            ;;
        'greater_or_equal'|'-ge'|'>=')
            [ "$_cmp" = '1' ] && return 0
            [ "$_cmp" = '0' ] && return 0
            ;;
        'equal'|'-eq'|'==')
            [ "$_cmp" = '0' ] && return 0
            ;;
        'not_equal'|'-ne'|'!=')
            [ "$_cmp" = '1' ] && return 0
            [ "$_cmp" = '2' ] && return 0
            ;;
        *) _die 7 'Unknown operatoration called for version_compare().';;
    esac
    return 1
}

##
# Print a formatted (critical) message and exit with status.
#
# **Usage:** _die [exit_status] message
#
# - exit_status: exit code to use with script termination (default: 1)
# - message: message to print before terminating script execution
##
_die() {
        # If first argument was an integer, use as exit_status
        if [ "$1" -eq "$1" ] 2>/dev/null; then
                _exit_status="$1"; shift
        else
                _exit_status=1
        fi

        printf '*** CRITICAL: %s ***\n' "$1"
        exit "$_exit_status"
}

##
# Compare two versions.
# Check if one version is larger/smaller/equal than/to another.
#
# **Usage:** _largest_version ver1 ver2
#
# Returns: ($1 > $2): 1 ; ($1 = $2): 0 ; ($1 < $2): 2
# [IOW- 1 = $1 is largest; 0 = neither ; 2 = $2 is largest]
##
_largest_version() (
    # Value used to separate version components
    VERSION_SEPARATOR="${VERSION_SEPARATOR:-.}"

    for _p in "$1" "$2"; do
        [ "$(printf %.1s "$_p")" = "$VERSION_SEPARATOR" ] &&
            _die 7 'invalid version pattern provided'
    done

    # Split versions on VER_SEP into int/sub
    _v="$1$2"
    _v1="$1"
    _s1="${1#*$VERSION_SEPARATOR}"
    if [ "$_v1" = "$_s1" ]; then
        _s1=''
        _m1="$_v1"
    else
        _m1="${1%%$VERSION_SEPARATOR*}"
    fi
    _v2="$2"
    _s2="${2#*$VERSION_SEPARATOR}"
    if [ "$_v2" = "$_s2" ]; then
        _s2=''
        _m2="$_v2"
    else
        _m2="${2%%$VERSION_SEPARATOR*}"
    fi

    # Both are equal
    [ "$_v1" = "$_v2" ] && return 0

    # Something is larger than nothing (30 < 30.0)
    if [ -n "$_v1" ] && [ ! -n "$_v2" ]; then
        return 1
    elif [ ! -n "$_v1" ] && [ -n "$_v2" ]; then
        return 2
    fi

    # Check for invalid
    case "$_m1$_m2" in
        *[!0-9]*)
            _die 7 'version_compare called with unsupported version type'
            ;;
    esac

    # If a ver_sep is present
    if [ "${_v#*$VERSION_SEPARATOR}" != "$_v" ]; then
        # Check for a larger "major" version number
        [ "$_m1" -lt "$_m2" ] && return 2
        [ "$_m1" -gt "$_m2" ] && return 1

        # Compare substring components
        _largest_version "$_s1" "$_s2"; return "$?"
    else
        # Only integers present; simple integer comparison
        [ "$_v1" -lt "$_v2" ] && return 2
        [ "$_v1" -gt "$_v2" ] && return 1
    fi
)

Tests:
# Simple test of all operators
( version_compare '1' 'lesser_than' '2' ); [ "$?" = '0' ] || return 1
( version_compare '2' 'equal' '2' ); [ "$?" = '0' ] || return 1
( version_compare '3' 'not_equal' '1' ); [ "$?" = '0' ] || return 1
( version_compare '2' 'greater_than' '1' ); [ "$?" = '0' ] || return 1
( version_compare '1' '-lt' '2' ); [ "$?" = '0' ] || return 1
( version_compare '2' '-eq' '2' ); [ "$?" = '0' ] || return 1
( version_compare '3' '-ne' '1' ); [ "$?" = '0' ] || return 1
( version_compare '2' '-gt' '1' ); [ "$?" = '0' ] || return 1

# Semver test of primary operators (expect true)
( version_compare '7.0.1' '-lt' '7.0.2' ); [ "$?" = '0' ] || return 1
( version_compare '7.0.2' '-eq' '7.0.2' ); [ "$?" = '0' ] || return 1
( version_compare '3.0.2' '-ne' '2.0.7' ); [ "$?" = '0' ] || return 1
( version_compare '7.0.2' '-gt' '7.0.1' ); [ "$?" = '0' ] || return 1

# Semver test of primary operators (expect false)
( version_compare '7.0.2' '-lt' '7.0.1' ); [ "$?" = '1' ] || return 1
( version_compare '3.0.2' '-eq' '2.0.7' ); [ "$?" = '1' ] || return 1
( version_compare '7.0.2' '-ne' '7.0.2' ); [ "$?" = '1' ] || return 1
( version_compare '7.0.1' '-gt' '7.0.2' ); [ "$?" = '1' ] || return 1

# Mismatched version strings (expect true)
( version_compare '7' '-lt' '7.1' ); [ "$?" = '0' ] || return 1
( version_compare '3' '-ne' '7.0.0' ); [ "$?" = '0' ] || return 1
( version_compare '7.0.1' '-gt' '7' ); [ "$?" = '0' ] || return 1

# Mismatched version strings (expect false)
( version_compare '7.0.0' '-eq' '7.0' ); [ "$?" = '1' ] || return 1

# Invalid operation supplied
( version_compare '2' '-inv' '1' >/dev/null ); [ "$?" = '7' ] || return 1

# Invalid version formats
( version_compare '1..0' '==' '1.0' >/dev/null ); [ "$?" = '7' ] || return 1
( version_compare '1.0' '==' '1..0' >/dev/null ); [ "$?" = '7' ] || return 1
( version_compare '1.0' '==' '1.0b7' >/dev/null ); [ "$?" = '7' ] || return 1
( version_compare '1.0a' '==' '1.0' >/dev/null ); [ "$?" = '7' ] || return 1

# "how does that handle comparing 10.0.0 (not a number) to 2.0 (a number)?"
( version_compare '10.0.0' '-lt' '2.0' ); [ "$?" = '1' ] || return 1
( version_compare '10.0' '-gt' '2.0.0' ); [ "$?" = '0' ] || return 1

# not less/greater-than... but equal
( version_compare '7' '-lt' '7' ); [ "$?" = '1' ] || return 1
( version_compare '7' '-gt' '7' ); [ "$?" = '1' ] || return 1

# String vs. numerical comparison
( version_compare '1.18.1' '-gt' '1.8.1' ); [ "$?" = '0' ] || return 1

# Random tests found on the internet
( version_compare '1' '==' '1' ); [ "$?" = '0' ] || return 1
( version_compare '2.1' '<' '2.2' ); [ "$?" = '0' ] || return 1
( version_compare '3.0.4.10' '>' '3.0.4.2' ); [ "$?" = '0' ] || return 1
( version_compare '4.08' '<' '4.08.01' ); [ "$?" = '0' ] || return 1
( version_compare '3.2.1.9.8144' '>' '3.2' ); [ "$?" = '0' ] || return 1
( version_compare '3.2' '<' '3.2.1.9.8144' ); [ "$?" = '0' ] || return 1
( version_compare '1.2' '<' '2.1' ); [ "$?" = '0' ] || return 1
( version_compare '2.1' '>' '1.2' ); [ "$?" = '0' ] || return 1
( version_compare '5.6.7' '==' '5.6.7' ); [ "$?" = '0' ] || return 1
( version_compare '1.01.1' '==' '1.1.1' ); [ "$?" = '0' ] || return 1
( version_compare '1.1.1' '==' '1.01.1' ); [ "$?" = '0' ] || return 1
( version_compare '1' '!=' '1.0' ); [ "$?" = '0' ] || return 1
( version_compare '1.0.0' '!=' '1.0' ); [ "$?" = '0' ] || return 1

A: A useful trick here is string indexing.
$ echo "${BASH_VERSION}"
4.4.23(1)-release

$ echo "${BASH_VERSION:0:1}"
4

A: I use a function that normalizes the numbers and than compare them.
The for loop is necessary to convert octal numbers in version strings to decimal, e.g. 1.08 → 1 8, 1.0030 → 1 30, 2021-02-03 → 2021 2 3...
(Tested with bash 5.0.17
#!/usr/bin/env bash

v() {
  printf "%04d%04d%04d%04d%04d" $(for i in ${1//[^0-9]/ }; do printf "%d " $((10#$i)); done)
}

while read -r test; do
  set -- $test
  printf "$test    "
  eval "if [[ $(v $1) $3 $(v $2) ]] ; then echo true; else echo false; fi"
done << EOF
1              1                   ==
2.1            2.2                  <
3.0.4.10       3.0.4.2              >
4.08           4.08.01              <
3.2.1.9.8144   3.2                  >
3.2            3.2.1.9.8144         <
1.2            2.1                  <
2.1            1.2                  >
5.6.7          5.6.7               ==
1.01.1         1.1.1               ==
1.1.1          1.01.1              ==
1              1.0                 ==
1.0            1                   ==
1.0.2.0        1.0.2               ==
1..0           1.0                 ==
1.0            1..0                ==
1              1                    >
1.2.3~rc2      1.2.3~rc4            >
1.2.3~rc2      1.2.3~rc4           ==
1.2.3~rc2      1.2.3~rc4            <
1.2.3~rc2      1.2.3~rc4           !=
1.2.3~rc2      1.2.3+rc4            <
2021-11-23-rc1 2021-11-23-rc1.1     <
2021-11-23-rc1 2021-11-23-rc1-rf1   <
2021-01-03-rc1 2021-01-04           <
5.0.17(1)-release 5.0.17(2)-release <
EOF

result:
1              1                   ==    true
2.1            2.2                  <    true
3.0.4.10       3.0.4.2              >    true
4.08           4.08.01              <    true
3.2.1.9.8144   3.2                  >    true
3.2            3.2.1.9.8144         <    true
1.2            2.1                  <    true
2.1            1.2                  >    true
5.6.7          5.6.7               ==    true
1.01.1         1.1.1               ==    true
1.1.1          1.01.1              ==    true
1              1.0                 ==    true
1.0            1                   ==    true
1.0.2.0        1.0.2               ==    true
1..0           1.0                 ==    true
1.0            1..0                ==    true
1              1                    >    false
1.2.3~rc2      1.2.3~rc4            >    false
1.2.3~rc2      1.2.3~rc4           ==    false
1.2.3~rc2      1.2.3~rc4            <    true
1.2.3~rc2      1.2.3~rc4           !=    true
1.2.3~rc2      1.2.3+rc4            <    true
2021-11-23-rc1 2021-11-23-rc1.1     <    true
2021-11-23-rc1 2021-11-23-rc1-rf1   <    true
2021-01-03-rc1 2021-01-04           <    true
5.0.17(1)-release 5.0.17(2)-release <    true

A: My two cents:
vercomp () {
    if [[ "${1}" == "${2}" ]]; then
        echo '0'
        return
    fi
    echo "${1}" | sed 's/\([0-9]\+\)\./\1\n/g' | {
        _RES_=-1
        for _VB_ in $(echo "${2}" | sed 's/\([0-9]\+\)\./\1\n/g'); do
            if ! read -r _VA_ || [[ "${_VB_}" -gt "${_VA_}" ]]; then
                _RES_=1
                break
            fi
        done
        read -r _VA_ && echo '-1' || echo "${_RES_}"
    }
}

Syntax:
vercomp VERSION_A VERSION_B

Prints:

*

*-1 if VERSION_A is more recent

*0 if the two versions are equal

*1 if VERSION_B is more recent

A: Instead of overcomplicating your life by writing long code, use something what already exists. Many times when bash is not enough python can help. And you still can call it from your bash script easily (bonus: variable substitution from bash to python):
VERSION1=1.2.3
VERSION2=1.2.4

cat <<EOF | python3 | grep -q True
from packaging import version
print(version.parse("$VERSION1") > version.parse("$VERSION2"))
EOF

if [ "$?" == 0 ];  then
   echo "$VERSION1 is greater than $VERSION2"
else
   echo "$VERSION2 is greater or equal than $VERSION1"
fi

More here: How do I compare version numbers in Python?

A: I hope this is useful to someone (use with awk)
  #!/bin/bash

  available_version=1.2.3 # or online version
  this_version=1.2.1

  if [[ "ok" == "$(echo | awk "(${available_version} > ${this_version}) { print \"ok\"; }")" ]]; then
    echo "Notice, new version is available"
  elif [[ "ok" == "$(echo | awk "(${available_version} == ${this_version}) { print \"ok\"; }")" ]]; then
    echo "OK, version is up to date"
  else
    echo "Warning, the current version is ahead of the online version!"
  fi


text:
Q: pip install failed on 'Temporary failure in name resolution' inspite we install local pkg We want to install the Jinja2-2.10-py2.py3-none-any.whl package by pip - on new REDHAT OS ( version 7.2 )
pip install Jinja2-2.10-py2.py3-none-any.whl
Processing ./Jinja2-2.10-py2.py3-none-any.whl
Collecting MarkupSafe>=0.23 (from Jinja2==2.10)
  Retrying (Retry(total=4, connect=None, read=None, redirect=None)) after connection broken by 'ProtocolError('Connection aborted.', gaierror(-3, 'Temporary failure in name resolution'))': /simple/markupsafe/

I am not understand why pip failed with "'Temporary failure in name resolution" while we want to install the - Jinja2-2.10-py2.py3-none-any.whl package by pip ?
We try also the following without successfully:
pip install --no-index --find-links  Jinja2-2.10-py2.py3-none-any.whl
Ignoring indexes: https://pypi.python.org/simple
You must give at least one requirement to install (maybe you meant "pip install Jinja2-2.10-py2.py3-none-any.whl"?)

pip install --no-index /tmp/install/Jinja2-2.10-py2.py3-none-any.whl
Ignoring indexes: https://pypi.python.org/simple
Processing ./Jinja2-2.10-py2.py3-none-any.whl
Collecting MarkupSafe>=0.23 (from Jinja2==2.10)
  Could not find a version that satisfies the requirement MarkupSafe>=0.23 (from Jinja2==2.10) (from versions: )
No matching distribution found for MarkupSafe>=0.23 (from Jinja2==2.10)

 pip install -U Jinja2-2.10-py2.py3-none-any.whl
Processing ./Jinja2-2.10-py2.py3-none-any.whl
Collecting MarkupSafe>=0.23 (from Jinja2==2.10)
  Retrying (Retry(total=4, connect=None, read=None, redirect=None)) after connection broken by 'ProtocolError('Connection aborted.', gaierror(-3, 'Temporary failure in name resolution'))': /simple/markupsafe/

 pip install -e  Jinja2-2.10-py2.py3-none-any.whl
Jinja2-2.10-py2.py3-none-any.whl should either be a path to a local project or a VCS url beginning with svn+, git+, hg+, or bzr+

in this case PIP - is local folder
pip install -e PIP/Jinja2-2.10-py2.py3-none-any.whl
PIP/Jinja2-2.10-py2.py3-none-any.whl should either be a path to a local project or a VCS url beginning with svn+, git+, hg+, or bzr+

UPDATE
[root@Master install_zone]# ls PIP/
Jinja2-2.10-py2.py3-none-any.whl

[root@Master install_zone]#  pip install --no-index --find-links=./PIP Jinja2
Ignoring indexes: https://pypi.python.org/simple
Collecting Jinja2
Collecting MarkupSafe>=0.23 (from Jinja2)
  Could not find a version that satisfies the requirement MarkupSafe>=0.23 (from Jinja2) (from versions: )
No matching distribution found for MarkupSafe>=0.23 (from Jinja2)
[root@Master install_zone]#

WE CHECK THE resolving as: ( details are from /etc/resolv.conf )
[root@Master install_zone]# host  sys54.com
sys54.com has address 32.44.1.154
[root@Master install_zone]# host 32.44.1.154
17.2.21.10.in-addr.arpa domain name pointer mpsload.sys54.com.

A: Your command is slightly wrong, the find-links argument should point to the directory the package is in, not the package itself:

-f, --find-links       If a url or path to an html file, then
  parse for links to archives. If a local path or file:// url that's a
  directory, then look for archives in
                                the directory listing.

Above pip install --no-index --find-links  Jinja2-2.10-py2.py3-none-any.whl is directing pip to look in a Jinja2-2.10-py2.py3-none-any.whl directory for a package, but you've not told pip what to install.
Assuming you downloaded the file into a subdirectory called PIP, your command should be: pip install --no-index --find-links=./PIP Jinja2


text: Q: Intersection of pencils in $\mathcal{R}^2$ Consider $9n$ pencils through non-collinear points $p_1, \ldots , p_{9n}$ in $R^2$ each consisting of at most $n$ concurrent lines. Define the intersection $S$ of these pencils to be the set of points which lie on at least one line in each of the $9n$ pencils. Is it true that $|S|$ is $O(n)$?


text:
Q: The identity used to sign the executable is no longer valid I have an application that I am  debugging on iPad.
 2 days ago I wanted to debug a same updated application but I am  having this error.

The identity used to sign the executable is no longer valid.
Please verify that your device's clock is properly set, and that your
  signing certificate is not expired.
(0xE8008018).

I don't have iPhone Developer certificate yet, but I have debugged this game once.

A: If you are using jailcoder, make sure you jailbreak your iphone successfully. Don't forget install AppSync for IOS in Cydia.

A: This may happen when your certificate expire in your Key Chain.
EDIT : I'd now recommand cert and sigh to generate your certificates and provisionning profiles. These are two commands part of the fastlane tools from KrauseFx.
Using cert & sigh:

*

*Open a terminal and type cert

*Answer the prompted questions to sect your user, password, team, app, etc.

*Open a terminal and type sigh

*Answer the prompted questions to sect your user, password, team, app, etc.

*Select the right profile in Code Signing Identity (iPhone Developer)

Conventional way:

*

*Just go to the new provisioning portal : Certificates, Identifier, Profiles

*Login with your developer account.

*Go to Certificates and click the Plus button.

*Then select iOS Apps Development and click Continue.

*Follow the whole process and download the newly generated certificate.

*Download it and put it in your keychain.

*Update your profiles from XCode Organizer devices window

*Select the right profile in Code Signing Identity (iPhone Developer)

A: In the latest update from xcode this problem usually occurs when your certificate has expired and xcode continues to use the old one until it has expired.
Closing xcode and opening it again will fire off an automatic process of downloading your new certificate and getting your app working.
Just close xcode right down (Cmd + Q) then open it back up again, load your project and hit play .. it will ask you if you'd like assistance to auto fix the certificate problem then you just follow the onscreen instructions and it does all the hard work for you :)

A: You have your provisioning profiles outdated.

*

*xcode

*Preferences

*Accounts

*Select your apple id

*View Details (Right-bottom corner)

*Download All

*Run again and DONE!

A: This may be somewhat of an empirical approach but is worthwhile in the face of many commentators noting either "this worked for me" or "this didn't work for me". Firstly, the problem can lie in a number of locations, either your certificates (code signing identities) or your provisioning profiles. Identifying where the problem lies first before doing anything will save a lot of wasted effort. You will need to check in three places:

*

*XCode

*Keychain Access

*The Developer Portal (Developer Members Centre)

OK, in XCode click on the Project (Above the Targets Heading), select Build Settings and scroll to 'Code Signing'. Expand the 'CODE_SIGNING_IDENTITY' heading and you will see a bunch of identities (Debug, Release etc.) Each one of these will match up with a certificate in Keychain Access. Find the match and check the expiry date...if it has expired you will need to update it in the Developer Portal and download it. Check EVERY identity, not just the first one you find that has expired. Also, if it has expired you will need to regenerate any provisioning profile that used the expired certificate.
If no problems with the certificates, check the expiry date of all the Provisioning Profiles. Once again, if they have expired, they will need to be regenerated.
Once complete, repeat the same process for the TARGET you are trying to build for.
None of this worked? An expired certificate is lurking in one of your provisioning profiles. A sign that this might be the case is that when you click on a CODE_SIGNING_IDENTITY the identity is below Other... eg.
This is usually a sure sign that there is an expired certificate lurking about and that one of your profiles is using it.

A: I faced to this problem when my membership was expired and I renewed it. I use xCode6 and I solve this problem by revoking expired developer certificate from Member Center and cleaning build folder ( alt+[Product>Clean] ). xCode handle others issue itself.
See "Replacing Expired Certificates" section on this link:
https://developer.apple.com/library/ios/documentation/IDEs/Conceptual/AppDistributionGuide/MaintainingCertificates/MaintainingCertificates.html

A: I had this problem with XCode 6.3 Below is the steps that worked for me.
Go to XCode > Preferences > Accounts Select your developer account then click View Details... Click on the refresh button on the left bottom of the window. It should notify you that you're missing few certificates. Click Request. XCode automatically should download missing certificates. Click Done and it should work.

A: Neither restarting Xcode nor restarting my Mac helped.
Solution within Xcode:

*

*In Xcode, go to Preferences --> Accounts --> View Details

*Press the + symbol and select iOS Development

*Press the refresh button in the lower left corner (called Download all in Xcode 7)

PS:

*

*Sometimes it may also help to delete invalid provisioning profiles: right-click -> move to trash

*I saw this error exactly one year after signing up as an Apple developer.

A: If all the above previous suggestions fail after renewing your certificate, as they did for me, browse to the following location;
~/Library/MobileDevice/Provisioning Profiles
...and delete your provisioning profiles.
Then download your provisioning profile again from;
https://developer.apple.com/account/ios/profile/profileList.action

A: you debug it on simulator only if you don't have iPhone Developer certificate. check on left corner in
xcode you select simulator not device.

A: I faced the same issue, I deleted all provisioning assets from xcode & added them back, and just relaunched Xcode.
My App was loaded on to the device and it worked.

A: This does also happen if your developer certificate is expired. Time to pay apple and renew it :P

A: First: go to build settings and check, if your valid Code Signing Identity is chosen.
If that doesn't help, try the more complicated stuff

A: In my case, this dialog message worked

The identity used to sign the executable is no longer valid.
Please verify that your device's clock is properly set, and that your
  signing certificate is not expired.
(0xE8008018).

My certificate in Keychain Access was given status to be not valid yet in red color with expiry about one year and an hour in future. I set my time to be one hour ahead and status of the certificate became valid in green color. So, anyone out here who thinks the solution to be the xcode restart is not correct but it would be cause of time elapsed of the xcode restart to make the certificate valid. As, by clicking the Fix Issue button revokes and creates new certificate with exactly one year ahead (plus some minutes depending upon locales to raise this issue).

A: My solution, after nothing else worked, was to go to Keychain Access and delete all "iOS developer" keys/certificates, then let Xcode regenerate them.

A: Try restarting XCode. It worked for me.

A: Try setting the time on the mobile device and the Mac to "set date and time automatically" checkbox and restart xcode, that did it for me

A: The Problem here is that your profile was built on an expired certificated
-so you have to go inside the developer portal and renew your certificate if it was expired
-then regenerate the profile so it will be rebulit on the new certificate
i suggest to use the  iPhone configuration utility tool to manage profiles on your mac

A: If your certificate is not installed locally. Or you tried running the certificate and opted to "revoke and request" a new certificate then you have the option to do that on the machine you are trying to run on
go to Preferences-> Accounts-> under your AppleId -> View Details -> under signing identities you can see the status of your certificate "Valid" or "Revoked" if revoked and you want to request a new one go to the -> + then -> the type of distribution you are trying to use.

A: In Xcode 5.1 - there is a self help area that did the job for me.
You'll find it in the General section after clicking on your project name under > Targets.
You should see a warning icon and a description of the issue in the Identity section (right where you type in your build/version numbers).
It noticed that there was no certificate currently stored and via some self-help boxes and a change of my password, I got it going.

A: These were the reasons I had this error:
The App ID didn't have my iOS Developer Certificate checked (I'm a member of an Enterprise program) and I had 2 provisioning profiles with the same App ID in my Mac.  I deleted one.
Hopefully this helps someone.

A: I had this problem several times, normally it can be solved by close-reopen Xcode.
I did delete derived data from Xcode organizer. It eventually works

A: I tried all of the above.  I kept getting the error about the UUID not  being found.
I went to the project, opened project.pbxproj and found all instances of the UUID (2) and deleted the UUID (not the entire line).
Fixed the problem.

A: I fixed this issue by selecting the correct team within Xcode (I'm part of multiple teams). Also, I revoked my certificate, requested a new one, uploaded that, and then re-downloaded it.

A: Experienced the same issue. Was an issue with an expired certificate.  You'll need to create a new cert and corresponding prov profile.  Follow dulgan's advice for doing so.

A: Removed the profiles from the directory on your machine: "~/Library/MobileDevice/Provisioning Profiles". And logged to apple developer centre and edited the specific provisioning profile and selected the certificate for provisioning profile and generated the profile again. Installed the new profile and it worked for me.

A: Found another way this occurs today. When you edit your provisioning profile after a certificate change you can see the certificates selected says 2 of 1 certificates selected (if you just use 1 certificate). Just by unselecting and reselecting the certificate you can regenerate and install the profile and it solves the problem.

A: @vomako 's solution almost solved my problem but I had to take another couple of steps.
I refer to the following...

In Xcode 6.1.1, I went to Preferences --> Accounts --> View Details

After upgrading to Xcode 6.1.1, the main issue for me that the >View Details button was greyed out.
I had to delete my account, restart Xcode, then add my developer account back in.
After this step, I could yet again view details and refresh my provisioning profiles.

A: I selected None from Team dropdown in target general settings. Then selected the original team. Xcode shows some spinner next to it. Wait for it to complete and then everything works. Tried it in Xcode 6.2

A: Today I faced this issue on my Xcode 6.3 public release.
I tried to restart Xcode several times but issue remained there.
What worked for me is
Manually create a new development profile at "http://developer.apple.com"
download and install this new profile, select this new profile from xcode build and run.

A: Same happened to me, In my case I just needed to approve apple's ne terms of service over:
https://developer.apple.com/membercenter

A: I took a bit of a hiatus from iOS to work on an Angular project and had this surprise waiting for me when I came back :-) In my case, I think it had to do with the fact that Apple is merging its developer programs, (at least from what I understand they are merging their developer programs), and I had to accept their new agreements.
Anyways, to fix this I combined a lot of the answers you'll find here and scattered throughout the web.
First, make sure to accept any pending agreements through both iTunes Connect and Apple's developer center. Make sure to accept any agreements in the "Agreements, Tax and Banking" section in iTunes Connect.
Second, via Xcode, go to Preferences -> Accounts -> View Details and at the bottom left there should be an option to refresh your profiles. When I did this Xcode installed a few new profiles.
Finally, restart Xcode.
Give some time in between each step for Apple's servers to update if these steps don't work right away.

A: I solve this problem using the new provision profile from apple developer account, Clean Derive-Data, And Refresh Developer Account in XCode.
Thanks your support. :)

A: I came through this error. The problem was The developer identity and Mobile Provisioning Profile mismatch.
Delete keychain certificates and fresh install matching provisioning profile and developer certificate fixed the problem.

A: I have tried many method to solve this problem.But they did not work.
Including

*

* restart my Xcode or my Mac.

* delete invalid profiles and generate again.

* reset Xcode > Preferences > Accounts.

* update iOS version and Xcode version.
What finally worked for me is:

register a new apple developer account and add to Xcode

I think maybe my developer account has some problem.

A: I've resolved editing my provisioning.
In fact, i've noticed that this mobile provisioning was not associated with my signing identity.
So, from the developer apple i followed this step:
 Select Provisioning Profiles -> Edit -> check my identity from "Certificates".
Effectively it's a strange error...

A: I had this problem and tried everything here but it didn't help. Then I noticed that the cord I was using was a little frayed, so I tried a new cord and it worked.

A: I have one strange problem.
In fact when i plug my phone to my mac the time of the device change but not use the actual hour. For example on my computer  I have this hour : 05:17 pm but on my phone when is unlocked time is frozen to 09:41 am so when i try to build my app on phone from xCode i have the next error message :
Please verify that your device's clock is properly set
The strange thing is that when my phone is still pluged to the mac the time on lockScreen is good (05:17 pm)... And if i check on Date & Time on general settings I have this strange thing too (time of statusbar is wrong but time below is good) :
Wrong time on statusBar
After few minutes i understood that it was because of QuickTime Player which was running on my mac with view of my iPhone (i was going to save a video demo of my app).
To resolve the problem I had to quit all applications and restart computer.
In plus at the end if problem persists do these steps :

*

*xcode: Preferences > Accounts

*Select your apple account

*Remove it

*Add your Apple account (+)

*Run your app again.

Hope this can help.
Thank you,

A: I have solved the same problem. Just from "https://developer.apple.com/account/ios/profile/production/create" re-created the new Provisioning Profiles. Then download and install the new Provisioning Profiles of (Development and Distribution).

A: Method no 12454: Set invalid (or any other) provisioning profile -> compile (you get error). Then set the correct provisioning profile. Might as well work ( did for me )...


text:
Q: How do you decipher complex declarations of pointers+arrays? Although I use std::vector almost all the time, I am interested in understanding as much as I can about pointers. Examples of what I am talking about:
char* array[5]; // What does it mean?
// 1) pointer to an array of 5 elements!
// 2) an array of 5 pointers?

I am interested in the precise definition of this declaration.

A: Not just pointers and arrays: How to interpret complex C/C++ declarations:

Start reading the declaration from the
  innermost parentheses, go right, and
  then go left. When you encounter
  parentheses, the direction should be
  reversed. Once everything in the
  parentheses has been parsed, jump out
  of it. Continue till the whole
  declaration has been parsed.
One small change to the right-left
  rule: When you start reading the
  declaration for the first time, you
  have to start from the identifier, and
  not the innermost parentheses.

You example:
char* array[5];

Is an array of 5 pointers to char.

A: cdecl is a program which is nice for this sort of thing. (particularly when you add function pointers into the mix!)
Type `help' or `?' for help
cdecl> explain char* foo[5]
declare foo as array 5 of pointer to char
cdecl> declare bar as array 5 of pointer to function (integer, integer) returning char
char (*bar[5])(int , int )

A: I learned the clockwise/spiral rule long ago from some magazine article. Here's an online article that describes the technique:

*

*http://c-faq.com/decl/spiral.anderson.html
It's served me well, though I still struggle mightily with some of the monstrous template-based declarations I come across at times.

A: The general procedure for reading a type in C/C++ is:

*

*Identify the final type, which can be a basic type or a typedef identifier, and which can have type modifiers such as const, volatile, etc.  In your example that's "char".

*Apply the operators to the identifier in the same order of precedence as they have in expressions.  These operators can be * (dereference), [] (index) and () (call function).

In the original philosophy of the syntax, your example would have been written "char *array[5]", the identifier is "array" and the operators are [] (index) then * (dereference).
The declaration then reads like a contract "if you apply these operators in that order, then you get an object of the final type".
In your case the full sentence is "if you index the variable "array", then dereference the resulting expression, you get a char".
You can also consider it like that "if you index the variable "array", then you get an object such that if you dereference it, you get a char"
The trick is mostly to keep track of the fact that [] and () have a higher precedence than *.  You can control the operator order with parentheses just like for regular expressions.

A: char * is the type and you have an array of 5 of them.

A: [] has higher precedence than *, that's why it's an array of pointers and not the other way around.

A: you always read pointers from right to left interpreting the '*' as a pointer.
for example char** a[5] is an array of 5 pointers to pointers of characters...


text:
Q: Write out without quitting in Vim? I looked through the vim manual, and I could only find the commands for "write and quit" and "write (if edited) and quit". Is there a command for "write out without quitting", similar to ^o in nano?

A: Use the write command:
:write

Which can be abbreviated:
:w

If you want to write to another file without changing the current file, supply a different filename to the write command:
:write newfile

If you want to write to another file and change to that file, use the saveas command:
:saveas newfile

Which can be abbreviated:
:s newfile