Enjoy the memory leak in libjaspernet :-)

git-svn-id: c32cf1ecefca26b8770d7b0740bc0c5c174087e4@369 c754d5e9-d413-0410-bcdf-9574c9dba6b7

--- applications/libjaspernet/JasperWrapper.cs
+++ applications/libjaspernet/JasperWrapper.cs
@@ -1,317 +1,348 @@
 using System;
 using System.Runtime.InteropServices; // For DllImport().

-public struct jas_matrix_t {            /* A matrix of pixels (one matrix per component) */
-  public int    flags;    		/* Additional state information. */
-  public int    xstart;  		/* The starting horizontal index. */
-  public int    ystart;			/* The starting vertical index. */
-  public int    xend; 	 		/* The ending horizontal index. */
-  public int    yend;  			/* The ending vertical index. */
-  public int    numrows;        	/* The number of rows in the matrix. */
-  public int    numcols;        	/* The number of columns in the matrix. */
-  public IntPtr row_ptrs;		/* Pointers to the start of each row. */
-  public int    maxrows;        	/* The allocated size of the rows array. */
-  public IntPtr data;  			/* The matrix data buffer. */
-  public int    datasize;       	/* The allocated size of the data array. */
-
-  public static jas_matrix_t fromPtr(IntPtr ptr) {
-    return (jas_matrix_t)Marshal.PtrToStructure(ptr, typeof(jas_matrix_t));
-  }
-
-  public int[] get_int_array() {
-    int[] retval=new int[datasize];
-    Marshal.Copy(data, retval, 0, datasize); /* only the low byte has any meaning */
-    return retval;
-  }
-
-  public int get_pixel(int x, int y) {
-    return Marshal.ReadInt32(data, y*numcols+x);
-  }
+public struct jas_matrix_t
+{            /* A matrix of pixels (one matrix per component) */
+    public int flags;    		/* Additional state information. */
+    public int xstart;  		/* The starting horizontal index. */
+    public int ystart;			/* The starting vertical index. */
+    public int xend; 	 		/* The ending horizontal index. */
+    public int yend;  			/* The ending vertical index. */
+    public int numrows;        	/* The number of rows in the matrix. */
+    public int numcols;        	/* The number of columns in the matrix. */
+    public IntPtr row_ptrs;		/* Pointers to the start of each row. */
+    public int maxrows;        	/* The allocated size of the rows array. */
+    public IntPtr data;  			/* The matrix data buffer. */
+    public int datasize;       	/* The allocated size of the data array. */
+
+    public static jas_matrix_t fromPtr(IntPtr ptr)
+    {
+        return (jas_matrix_t)Marshal.PtrToStructure(ptr, typeof(jas_matrix_t));
+    }
+
+    public int[] get_int_array()
+    {
+        int[] retval = new int[datasize];
+        Marshal.Copy(data, retval, 0, datasize); /* only the low byte has any meaning */
+        return retval;
+    }
+
+    public int get_pixel(int x, int y)
+    {
+        return Marshal.ReadInt32(data, y * numcols + x);
+    }
 }

-public struct jas_image_cmpt_t {        /* Image component class. */
-  public int    tlx;                    /* The x-coordinate of the top-left corner of the component. */
-  public int    tly;                    /* The y-coordinate of the top-left corner of the component. */
-  public int    hstep;                  /* The horizontal sampling period in units of the reference grid. */
-  public int    vstep;                  /* The vertical sampling period in units of the reference grid. */
-  public int    width;                  /* The component width in samples. */
-  public int    height;                 /* The component height in samples. */
-  public int    prec;                   /* precision */
-  public int    sgnd;                   /* signed-ness */
-  public IntPtr stream;                 /* The stream containing the component data. */
-  public int    cps;                    /* The number of characters per sample in the stream. */
-  public int    type;                   /* The type of component (e.g., opacity, red, green, blue, luma). */
-
-  public static jas_image_cmpt_t fromPtr(IntPtr ptr) {
-    return (jas_image_cmpt_t)Marshal.PtrToStructure(ptr, typeof(jas_image_cmpt_t));
-  }
+public struct jas_image_cmpt_t
+{        /* Image component class. */
+    public int tlx;                    /* The x-coordinate of the top-left corner of the component. */
+    public int tly;                    /* The y-coordinate of the top-left corner of the component. */
+    public int hstep;                  /* The horizontal sampling period in units of the reference grid. */
+    public int vstep;                  /* The vertical sampling period in units of the reference grid. */
+    public int width;                  /* The component width in samples. */
+    public int height;                 /* The component height in samples. */
+    public int prec;                   /* precision */
+    public int sgnd;                   /* signed-ness */
+    public IntPtr stream;                 /* The stream containing the component data. */
+    public int cps;                    /* The number of characters per sample in the stream. */
+    public int type;                   /* The type of component (e.g., opacity, red, green, blue, luma). */
+
+    public static jas_image_cmpt_t fromPtr(IntPtr ptr)
+    {
+        return (jas_image_cmpt_t)Marshal.PtrToStructure(ptr, typeof(jas_image_cmpt_t));
+    }
 }

-public struct jas_image_t {
-  public int    tlx;                     /* The x-coordinate of the top-left corner of the image bounding box. */
-  public int    tly;                     /* The y-coordinate of the top-left corner of the image bounding box. */
-  public int    brx;                     /* The x-coordinate of the bottom-right corner of the image bounding
+public struct jas_image_t
+{
+    public int tlx;                     /* The x-coordinate of the top-left corner of the image bounding box. */
+    public int tly;                     /* The y-coordinate of the top-left corner of the image bounding box. */
+    public int brx;                     /* The x-coordinate of the bottom-right corner of the image bounding
 		                            box (plus one). */
-  public int    bry;                     /* The y-coordinate of the bottom-right corner of the image bounding
+    public int bry;                     /* The y-coordinate of the bottom-right corner of the image bounding
 		                            box (plus one). */
-  public int    numcmpts;                /* The number of components. */
-  public int    maxcmpts;                /* The maximum number of components that this image can have (i.e., the
+    public int numcmpts;                /* The number of components. */
+    public int maxcmpts;                /* The maximum number of components that this image can have (i.e., the
 		                            allocated size of the components array). */
-  public IntPtr cmpts;                   /* array of pointers to jas_image_cmpt_t: Per-component information. */
-  public int    clrspc;
-  public IntPtr cmprof;
-  public bool   inmem;
-
-  public static jas_image_t fromPtr(IntPtr ptr) {
-    return (jas_image_t)Marshal.PtrToStructure(ptr, typeof(jas_image_t));
-  }
-
-  public int width { get { return brx-tlx; } }
-  public int height { get { return bry-tly; } }
-
-  public jas_image_cmpt_t[] get_components() {
-    jas_image_cmpt_t[] retval=new jas_image_cmpt_t[numcmpts];
-    int i;
-
-    for(i=0;i<numcmpts;i++) retval[i]=jas_image_cmpt_t.fromPtr(Marshal.ReadIntPtr(cmpts,i*4));
-    return retval;
-  }
-
+    public IntPtr cmpts;                   /* array of pointers to jas_image_cmpt_t: Per-component information. */
+    public int clrspc;
+    public IntPtr cmprof;
+    public bool inmem;
+
+    public static jas_image_t fromPtr(IntPtr ptr)
+    {
+        return (jas_image_t)Marshal.PtrToStructure(ptr, typeof(jas_image_t));
+    }
+
+    public int width { get { return brx - tlx; } }
+    public int height { get { return bry - tly; } }
+
+    public jas_image_cmpt_t[] get_components()
+    {
+        jas_image_cmpt_t[] retval = new jas_image_cmpt_t[numcmpts];
+        int i;
+
+        for (i = 0; i < numcmpts; i++) retval[i] = jas_image_cmpt_t.fromPtr(Marshal.ReadIntPtr(cmpts, i * 4));
+        return retval;
+    }
+
 }

-class JasperWrapper {
-  const string JASPER_LIBRARY = "libjasper.dll";
-
-  [DllImport(JASPER_LIBRARY)]
+public class Jasper
+{
+    const string JASPER_LIBRARY = "libjasper.dll";
+
+    [DllImport(JASPER_LIBRARY)]
     private static extern int jas_init();

-  public static int jasper_init() {
-    int retval=jas_init();
-    bitmap_format_id=jas_image_strtofmt("bmp");
-    Console.WriteLine("bmp = "+bitmap_format_id);
-    return retval;
-  }
-
-  [DllImport(JASPER_LIBRARY)]
+    public static int jasper_init()
+    {
+        int retval = jas_init();
+        bitmap_format_id = jas_image_strtofmt("bmp");
+        Console.WriteLine("bmp = " + bitmap_format_id);
+        return retval;
+    }
+
+    [DllImport(JASPER_LIBRARY)]
     private static extern IntPtr jas_getversion();
-
-  [DllImport(JASPER_LIBRARY)]
+
+    [DllImport(JASPER_LIBRARY)]
     private static extern int jas_setdbglevel(int level);
-
-  [DllImport(JASPER_LIBRARY)]
+
+    [DllImport(JASPER_LIBRARY)]
     public static extern IntPtr jas_stream_fopen(string filename, string mode);
-
-  [DllImport(JASPER_LIBRARY)]
+
+    [DllImport(JASPER_LIBRARY)]
     private static extern IntPtr jas_stream_memopen(IntPtr buf, int bufsize);
-
-  public static IntPtr jas_stream_memopen(byte[] buf) {
-    IntPtr bufPtr = Marshal.AllocHGlobal(buf.Length);
-    Marshal.Copy(buf,0,bufPtr,buf.Length);
-
-    return jas_stream_memopen(bufPtr, buf.Length);
-  }
-
-  [DllImport(JASPER_LIBRARY)]
+
+    public static IntPtr jas_stream_memopen(byte[] buf)
+    {
+        IntPtr bufPtr = Marshal.AllocHGlobal(buf.Length);
+        Marshal.Copy(buf, 0, bufPtr, buf.Length);
+
+        return jas_stream_memopen(bufPtr, buf.Length);
+    }
+
+    [DllImport(JASPER_LIBRARY)]
     public static extern int jas_stream_flush(IntPtr stream);
-
-  [DllImport(JASPER_LIBRARY)]
+
+    [DllImport(JASPER_LIBRARY)]
     public static extern int jas_stream_close(IntPtr stream);
-
-  [DllImport(JASPER_LIBRARY)]
+
+    [DllImport(JASPER_LIBRARY)]
+    public static extern int jas_stream_destroy(IntPtr stream);
+
+    [DllImport(JASPER_LIBRARY)]
     public static extern int jas_image_getfmt(IntPtr stream);
-
-  /* Get the ID for the image format with the specified name. */
-  [DllImport(JASPER_LIBRARY)]
+
+    /* Get the ID for the image format with the specified name. */
+    [DllImport(JASPER_LIBRARY)]
     private static extern int jas_image_strtofmt(string name);

-  [DllImport(JASPER_LIBRARY)]
+    [DllImport(JASPER_LIBRARY)]
     public static extern int jas_image_fmtfromname(string filename);
-
-  [DllImport(JASPER_LIBRARY)]
+
+    [DllImport(JASPER_LIBRARY)]
     public static extern int jas_image_encode(IntPtr image, IntPtr out_stream, int fmt, string optstr);
-
-  [DllImport(JASPER_LIBRARY)]
+
+    [DllImport(JASPER_LIBRARY)]
     public static extern IntPtr jas_image_decode(IntPtr in_stream, int fmt, string optstr);
-
-  [DllImport(JASPER_LIBRARY)]
+
+    [DllImport(JASPER_LIBRARY)]
     public static extern IntPtr jas_image_destroy(IntPtr image_ptr);
-
-  public static int jas_image_cmpttype(jas_image_t image, int cmptno) {
-    jas_image_cmpt_t cmpt=
-      (jas_image_cmpt_t)Marshal.PtrToStructure(Marshal.ReadIntPtr(image.cmpts, cmptno*4),
-					       typeof(jas_image_cmpt_t));
-    return cmpt.type;
-  }
-
-  [DllImport(JASPER_LIBRARY)]
+
+    public static int jas_image_cmpttype(jas_image_t image, int cmptno)
+    {
+        jas_image_cmpt_t cmpt =
+          (jas_image_cmpt_t)Marshal.PtrToStructure(Marshal.ReadIntPtr(image.cmpts, cmptno * 4),
+                               typeof(jas_image_cmpt_t));
+        return cmpt.type;
+    }
+
+    [DllImport(JASPER_LIBRARY)]
     public static extern int jas_image_readcmpt(IntPtr image_ptr, int cmptno,
-						int x, int y, int width, int height, IntPtr data);
-
-  public static string get_jasper_version() {
-    string text = Marshal.PtrToStringAuto(jas_getversion());
-    if(text==null) throw new Exception("jas_getversion returned NULL\n");
-    return text;
-  }
-
-  [DllImport(JASPER_LIBRARY)]
+                        int x, int y, int width, int height, IntPtr data);
+
+    public static string get_jasper_version()
+    {
+        string text = Marshal.PtrToStringAuto(jas_getversion());
+        if (text == null) throw new Exception("jas_getversion returned NULL\n");
+        return text;
+    }
+
+    [DllImport(JASPER_LIBRARY)]
     public static extern IntPtr jas_matrix_create(int width, int height);
-
-  [DllImport(JASPER_LIBRARY)]
+
+    [DllImport(JASPER_LIBRARY)]
     public static extern void jas_matrix_destroy(IntPtr matrix);

-  public static int[] get_multiplexed_image_data(IntPtr image_ptr, int[] order) {
-    if(order.Length>4) throw new Exception("order.Length must be <= 4");
-    jas_image_t image_struct=jas_image_t.fromPtr(image_ptr);
-
-    IntPtr matrix=jas_matrix_create(image_struct.height, image_struct.width);
-    int [] pixels = new int [image_struct.height*image_struct.width];
-
-    for(int c=0;c<order.Length;c++) {
-      int retval=jas_image_readcmpt(image_ptr, order[c], 0, 0,
-				    image_struct.width, image_struct.height, matrix);
-      if(retval!=0) {
-	jas_matrix_destroy(matrix);
-	throw new Exception("jas_iamge_readcmpt returned "+retval);
-      }
-
-      int[] temp_array=(jas_matrix_t.fromPtr(matrix)).get_int_array();
-      for(int i=0;i<temp_array.Length;i++) pixels[i] |= (temp_array[i]&0xFF) << (c*8);
-    }
-    jas_matrix_destroy(matrix);
-    return pixels;
-  }
-
-  public static String version {
-    get { return get_jasper_version(); }
-  }
-
-  private static int bitmap_format_id=0;
-
-  public static int[] jasper_decode_j2c(byte[] input) {
-    IntPtr input_stream_ptr=jas_stream_memopen(input);
-    int format=jas_image_getfmt(input_stream_ptr);
-
-    Console.WriteLine("file is format # "+format);
-
-    IntPtr image_ptr=jas_image_decode(input_stream_ptr, format, "");
-    if(image_ptr==IntPtr.Zero) throw new Exception("Error decoding image");
-
-    jas_image_t image_struct=(jas_image_t)Marshal.PtrToStructure(image_ptr, typeof(jas_image_t));
-
-    Console.WriteLine("image has "+image_struct.numcmpts+" components");
-    int[] mux_order=null;
-    switch(image_struct.numcmpts) {
-        case 4: mux_order=new int[] {0, 1, 2, 3}; break; /* ARGB? */
-        case 3: mux_order=new int[] {0, 1, 2};    break; /* RGB? */
-        case 2: mux_order=new int[] {0, 1};       break; /* ??? */
-        case 1: mux_order=new int[] {0};          break; /* grayscale */
-	default: throw new Exception("Unhandled number of components:" + image_struct.numcmpts);
-    }
-
-    int[] pixels=get_multiplexed_image_data(image_ptr, mux_order);
-
-    Console.WriteLine("Image dimensions: "+image_struct.width	+ " x " + image_struct.height);
-    jas_stream_close(input_stream_ptr);
-    jas_image_destroy(image_ptr);
-    return pixels;
-  }
-
-  public static byte[] jasper_decode_j2c_to_bmp(byte[] input, int output_buffer_size) {
-    IntPtr input_stream_ptr = jas_stream_memopen(input);
-    IntPtr bufPtr = Marshal.AllocHGlobal(output_buffer_size);
-    IntPtr output_stream_ptr=jas_stream_memopen(bufPtr, output_buffer_size);
-
-    int format=jas_image_getfmt(input_stream_ptr);
-
-    Console.WriteLine("file is format # "+format);
-
-    IntPtr image_ptr=jas_image_decode(input_stream_ptr, format, "");
-    if(image_ptr==IntPtr.Zero) throw new Exception("Error decoding image");
-
-    int retval=jas_image_encode(image_ptr, output_stream_ptr, bitmap_format_id, "");
+    public static int[] get_multiplexed_image_data(IntPtr image_ptr, int[] order)
+    {
+        if (order.Length > 4) throw new Exception("order.Length must be <= 4");
+        jas_image_t image_struct = jas_image_t.fromPtr(image_ptr);
+
+        IntPtr matrix = jas_matrix_create(image_struct.height, image_struct.width);
+        int[] pixels = new int[image_struct.height * image_struct.width];
+
+        for (int c = 0; c < order.Length; c++)
+        {
+            int retval = jas_image_readcmpt(image_ptr, order[c], 0, 0,
+                          image_struct.width, image_struct.height, matrix);
+            if (retval != 0)
+            {
+                jas_matrix_destroy(matrix);
+                throw new Exception("jas_iamge_readcmpt returned " + retval);
+            }
+
+            int[] temp_array = (jas_matrix_t.fromPtr(matrix)).get_int_array();
+            for (int i = 0; i < temp_array.Length; i++) pixels[i] |= (temp_array[i] & 0xFF) << (c * 8);
+        }
+        jas_matrix_destroy(matrix);
+        return pixels;
+    }
+
+    public static String version
+    {
+        get { return get_jasper_version(); }
+    }
+
+    private static int bitmap_format_id = 0;
+
+    public static int[] jasper_decode_j2c(byte[] input)
+    {
+        IntPtr input_stream_ptr = jas_stream_memopen(input);
+        int format = jas_image_getfmt(input_stream_ptr);
+
+        Console.WriteLine("file is format # " + format);
+
+        IntPtr image_ptr = jas_image_decode(input_stream_ptr, format, "");
+        if (image_ptr == IntPtr.Zero) throw new Exception("Error decoding image");
+
+        jas_image_t image_struct = (jas_image_t)Marshal.PtrToStructure(image_ptr, typeof(jas_image_t));
+
+        Console.WriteLine("image has " + image_struct.numcmpts + " components");
+        int[] mux_order = null;
+        switch (image_struct.numcmpts)
+        {
+            case 4: mux_order = new int[] { 0, 1, 2, 3 }; break; /* ARGB? */
+            case 3: mux_order = new int[] { 0, 1, 2 }; break; /* RGB? */
+            case 2: mux_order = new int[] { 0, 1 }; break; /* ??? */
+            case 1: mux_order = new int[] { 0 }; break; /* grayscale */
+            default: throw new Exception("Unhandled number of components:" + image_struct.numcmpts);
+        }
+
+        int[] pixels = get_multiplexed_image_data(image_ptr, mux_order);
+
+        Console.WriteLine("Image dimensions: " + image_struct.width + " x " + image_struct.height);
+        jas_stream_close(input_stream_ptr);
+        jas_image_destroy(image_ptr);
+        return pixels;
+    }
+
+    public static byte[] jasper_decode_j2c_to_bmp(byte[] input, int output_buffer_size)
+    {
+        IntPtr input_stream_ptr = jas_stream_memopen(input);
+        IntPtr bufPtr = Marshal.AllocHGlobal(output_buffer_size);
+        IntPtr output_stream_ptr = jas_stream_memopen(bufPtr, output_buffer_size);
+
+        int format = jas_image_getfmt(input_stream_ptr);
+
+        Console.WriteLine("file is format # " + format);
+
+        IntPtr image_ptr = jas_image_decode(input_stream_ptr, format, "");
+        if (image_ptr == IntPtr.Zero) throw new Exception("Error decoding image");
+
+        int retval = jas_image_encode(image_ptr, output_stream_ptr, bitmap_format_id, "");
+
+        if (retval != 0) throw new Exception("Error encoding image: " + retval);
+
+        byte[] buf = new byte[output_buffer_size];
+        Marshal.Copy(bufPtr, buf, 0, output_buffer_size);
+        Marshal.FreeHGlobal(bufPtr);
+
+        jas_image_destroy(image_ptr);
+        //jas_stream_flush(output_stream_ptr);
+        //jas_stream_close(output_stream_ptr);
+        //jas_stream_destroy(output_stream_ptr);
+        jas_stream_close(input_stream_ptr);
+
+        return buf;
+    }
+
+    //public static void Main(string[] args)
+    //{
+    //    jasper_init();
+    //    Console.WriteLine("get_jasper_version=" + get_jasper_version());
+    //    jas_setdbglevel(1000);
+
+    //    if (args.Length == 1)
+    //    {
+    //        Console.WriteLine("Opening file: " + args[0]);
+    //        IntPtr input_stream_ptr = jas_stream_fopen(args[0], "rb");
+
+    //        if (input_stream_ptr == IntPtr.Zero)
+    //        {
+    //            Console.Error.WriteLine("Error opening input file\n");
+    //            return;
+    //        }
+    //        /*
+    //      IntPtr output_stream_ptr=jas_stream_fopen("foo.jpg", "w+b");

-    if(retval!=0) throw new Exception("Error encoding image: "+retval);
-
-    byte[] buf=new byte[output_buffer_size];
-    Marshal.Copy(bufPtr,buf,0,output_buffer_size);
-    Marshal.FreeHGlobal(bufPtr);
-
-    jas_image_destroy(image_ptr);
-    jas_stream_flush(output_stream_ptr);
-    jas_stream_close(output_stream_ptr);
-    jas_stream_close(input_stream_ptr);
-
-    return buf;
-  }
-
-  public static void Main(string[] args) {
-    jasper_init();
-    Console.WriteLine("get_jasper_version="+get_jasper_version());
-    jas_setdbglevel(1000);
-
-    if(args.Length==1) {
-      Console.WriteLine("Opening file: "+args[0]);
-      IntPtr input_stream_ptr=jas_stream_fopen(args[0], "rb");
-
-      if(input_stream_ptr==IntPtr.Zero) {
-	Console.Error.WriteLine("Error opening input file\n");
-	return;
-      }
-      /*
-	IntPtr output_stream_ptr=jas_stream_fopen("foo.jpg", "w+b");
+    //      if(output_stream_ptr==IntPtr.Zero) {
+    //      Console.Error.WriteLine("Error opening output file\n");
+    //      return;
+    //      }*/
+
+    //        int format = jas_image_getfmt(input_stream_ptr);
+
+    //        Console.WriteLine("file is format # " + format);
+
+    //        IntPtr image_ptr = jas_image_decode(input_stream_ptr, format, "");
+    //        if (image_ptr == IntPtr.Zero)
+    //        {
+    //            Console.Error.WriteLine("Error decoding image");
+    //            return;
+    //        }
+
+    //        jas_image_t image_struct = (jas_image_t)Marshal.PtrToStructure(image_ptr, typeof(jas_image_t));
+
+    //        Console.WriteLine("image has " + image_struct.numcmpts + " components");
+    //        int[] mux_order = null;
+    //        switch (image_struct.numcmpts)
+    //        {
+    //            case 4: mux_order = new int[] { 0, 1, 2, 3 }; break; /* ARGB? */
+    //            case 3: mux_order = new int[] { 0, 1, 2 }; break; /* RGB? */
+    //            case 2: mux_order = new int[] { 0, 1 }; break; /* ??? */
+    //            case 1: mux_order = new int[] { 0 }; break; /* grayscale */
+    //            default: throw new Exception("Unhandled number of components:" + image_struct.numcmpts);
+    //        }
+
+    //        int[] pixels = get_multiplexed_image_data(image_ptr, mux_order);
+
+    //        int row, col;
+    //        Console.WriteLine("Image dimensions: " + image_struct.width
+    //              + " x " + image_struct.height);
+
+    //        for (row = 0; row < image_struct.height; row++)
+    //            for (col = 0; col < image_struct.width; col++)
+    //            {
+    //                Console.WriteLine("(" + row + "," + col + "): " + pixels[image_struct.width * row + col].ToString("x8"));
+    //            }
+    //        /*
+    //      int output_format=jas_image_fmtfromname("foo.jpg");

-	if(output_stream_ptr==IntPtr.Zero) {
-	Console.Error.WriteLine("Error opening output file\n");
-	return;
-	}*/
-
-      int format=jas_image_getfmt(input_stream_ptr);
-
-      Console.WriteLine("file is format # "+format);
-
-      IntPtr image_ptr=jas_image_decode(input_stream_ptr, format, "");
-      if(image_ptr==IntPtr.Zero) {
-	Console.Error.WriteLine("Error decoding image");
-	return;
-      }
-
-      jas_image_t image_struct=(jas_image_t)Marshal.PtrToStructure(image_ptr, typeof(jas_image_t));
-
-      Console.WriteLine("image has "+image_struct.numcmpts+" components");
-      int[] mux_order=null;
-      switch(image_struct.numcmpts) {
-        case 4: mux_order=new int[] {0, 1, 2, 3}; break; /* ARGB? */
-        case 3: mux_order=new int[] {0, 1, 2};    break; /* RGB? */
-        case 2: mux_order=new int[] {0, 1};       break; /* ??? */
-        case 1: mux_order=new int[] {0};          break; /* grayscale */
-	default: throw new Exception("Unhandled number of components:" + image_struct.numcmpts);
-      }
-
-      int[] pixels=get_multiplexed_image_data(image_ptr, mux_order);
-
-      int row, col;
-      Console.WriteLine("Image dimensions: "+image_struct.width
-			+ " x " + image_struct.height);
-
-      for(row=0; row<image_struct.height; row++)
-	for(col=0; col< image_struct.width; col++) {
-	  Console.WriteLine("("+row+","+col+"): "+pixels[image_struct.width*row+col].ToString("x8"));
-	}
-      /*
-	int output_format=jas_image_fmtfromname("foo.jpg");
+    //      int retval=jas_image_encode(image_ptr, output_stream_ptr, output_format, "");

-	int retval=jas_image_encode(image_ptr, output_stream_ptr, output_format, "");
+    //      if(retval!=0) {
+    //         Console.Error.WriteLine("Error encoding image: "+retval);
+    //         return;
+    //      }

-	if(retval!=0) {
-	   Console.Error.WriteLine("Error encoding image: "+retval);
-	   return;
-	}
-
-	jas_stream_flush(output_stream_ptr);
-	jas_stream_close(output_stream_ptr); */
-      jas_stream_close(input_stream_ptr);
-
-      jas_image_destroy(image_ptr);
-    }
-  }
+    //      jas_stream_flush(output_stream_ptr);
+    //      jas_stream_close(output_stream_ptr); */
+    //        jas_stream_close(input_stream_ptr);
+
+    //        jas_image_destroy(image_ptr);
+    //    }
+    //}
 }


avoid logging urls since they may contains user/pwd

--- projects/FogBugzNet/HttpUtils.cs
+++ projects/FogBugzNet/HttpUtils.cs
@@ -39,12 +39,12 @@
             catch (System.Net.WebException x)
             {
                 Utils.Log.Error(x.ToString() + ". Connection status: " + x.Status.ToString());
-                throw new EServerError("Unable to find FogBugz server at location: " + url);
+                throw new EServerError("Unable to find FogBugz server");
             }
             catch (System.UriFormatException x)
             {
                 Utils.Log.Error(x.ToString());
-                throw new EURLError("The server URL you provided appears to be malformed: " + url);
+                throw new EURLError("The server URL you provided appears to be malformed");
             }
         }

@@ -78,12 +78,12 @@
             catch (System.Net.WebException x)
             {
                 Utils.Log.Error(x.ToString() + ". Connection status: " + x.Status.ToString());
-                throw new EServerError("Unable to find FogBugz server at location: " + url);
+                throw new EServerError("Unable to find FogBugz server");
             }
             catch (System.UriFormatException x)
             {
                 Utils.Log.Error(x.ToString());
-                throw new EURLError("The server URL you provided appears to be malformed: " + url);
+                throw new EURLError("The server URL you provided appears to be malformed");
             }
         }


Injector for adding ThingComp to ThingDef

--- DLL_Project/MonoBehaviour/ModController.cs
+++ DLL_Project/MonoBehaviour/ModController.cs
@@ -1,6 +1,7 @@
 using System;
 using System.Collections.Generic;
 using System.Linq;
+using System.Reflection;

 using RimWorld;
 using UnityEngine;
@@ -60,6 +61,11 @@
                 InjectMapComponents();
             }
         }
+
+	    public void							OnLevelWasLoaded()
+	    {
+		    InjectThingComp<CompPawnGizmo>("Human");
+	    }

         #endregion

@@ -186,8 +192,39 @@
             }
         }

-        #endregion
-
-    }
+		#endregion
+
+		#region ThingComp Injection
+
+	    void								InjectThingComp<T>(string defName) where T : ThingComp
+		{
+			// Access ThingDef database
+			var typeFromHandle = typeof(DefDatabase<ThingDef>);
+			var defsByName = typeFromHandle.GetField("defsByName", BindingFlags.Static | BindingFlags.NonPublic);
+			if (defsByName == null)
+			{
+				CCL_Log.Error("ThingComp Injection", "defName is null!");
+			}
+			var dictDefsByName = defsByName?.GetValue(null) as Dictionary<string, ThingDef>;
+			if (dictDefsByName == null)
+			{
+				CCL_Log.Error("ThingComp Injection", "Cannot access private members!");
+			}
+
+			var def = dictDefsByName?.Values.ToList().Find(s => s.defName == defName);
+
+			if (def != null && def.comps.Any(curComp => curComp.GetType() == typeof(T)))
+			{
+				return;
+			}
+
+			CCL_Log.Message("ThingComp Injection", "Injecting ThingComp to" + def.defName);
+			var compProperties = new CompProperties { compClass = typeof(T) };
+			def.comps.Add(compProperties);
+		}
+
+		#endregion
+
+	}

 }


fixed null pointer exception

fixed null pointer exception

--- data-structures-csharp/data-structures-csharp/Hash/LinearProbingDictionary.cs
+++ data-structures-csharp/data-structures-csharp/Hash/LinearProbingDictionary.cs
@@ -18,7 +18,6 @@
         private int capacity;
         private readonly int stepSize;
         private int count;
-        private bool[] isFilled;
         private Pair<Tkey, TValue>[] pairs;

         public ICollection<Tkey> Keys
@@ -54,7 +53,6 @@
             this.capacity = capacity;
             this.stepSize = stepSize;
             pairs = new Pair<Tkey, TValue>[capacity];
-            isFilled = new bool[capacity];
         }

         public LinearProbingDictionary(int stepSize)
@@ -124,7 +122,6 @@
             if ((index = GetIndex(key)) != -1)
             {
                 pairs[index] = null;
-                isFilled[index] = false;
                 count--;
             }
         }
@@ -178,8 +175,7 @@
         public void Clear()
         {
             count = 0;
-            isFilled = Array.ConvertAll<bool, bool>(isFilled, b => b = false);
-            pairs = Array.ConvertAll<Pair<Tkey, TValue>, Pair<Tkey, TValue>>(pairs, pair => pair = null);
+            pairs = new Pair<Tkey, TValue>[capacity];
         }

         public bool Contains(KeyValuePair<Tkey, TValue> item)
@@ -207,7 +203,6 @@
                 return;
             }
             pairs[index] = null;
-            isFilled[index] = false;
             count--;
         }

@@ -215,6 +210,10 @@
         {
             foreach (var pair in pairs)
             {
+                if(pair == null)
+                {
+                    continue;
+                }
                 yield return new KeyValuePair<Tkey, TValue>(pair.Key, pair.Value);
             }
         }


Work on summaries

Work on summaries

--- DefinitionsAndCodes/DefinitionsAndCodes.cs
+++ DefinitionsAndCodes/DefinitionsAndCodes.cs
@@ -6,7 +6,7 @@
 namespace UWaterlooAPI.DefinitionsAndCodes
 {
 	/// <summary>
-	/// todo
+	/// Info about an organization unit.
 	/// </summary>
 	public class OrganizationalUnit
 	{
@@ -25,7 +25,7 @@
 	}

 	/// <summary>
-	/// todo
+	/// Info about the naming convertion of a term
 	/// </summary>
 	public class Term
 	{


F12 now also toggles the console.

F12 now also toggles the console.

--- ethernet/client/scripts/actionmap.global.cs
+++ ethernet/client/scripts/actionmap.global.cs
@@ -10,6 +10,7 @@
 //------------------------------------------------------------------------------

 GlobalActionMap.bind(keyboard, "tilde", toggleConsole);
+GlobalActionMap.bind(keyboard, "F12", toggleConsole);
 GlobalActionMap.bindCmd(keyboard, "alt enter", "", "toggleFullScreen();");
 //GlobalActionMap.bindCmd(keyboard, "F1", "", "contextHelp();");


Minor refactoring

Minor refactoring

--- samples/cs/tar/Main.cs
+++ samples/cs/tar/Main.cs
@@ -27,8 +27,6 @@

 using System;
 using System.IO;
-
-using ICSharpCode.SharpZipLib;
 using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
 using ICSharpCode.SharpZipLib.GZip;
 using ICSharpCode.SharpZipLib.BZip2;
@@ -129,14 +127,14 @@
 	/// </summary>
 	public Tar()
 	{
-		this.blockingFactor = TarBuffer.DefaultBlockFactor;
-		this.userId   = 0;
+		blockingFactor = TarBuffer.DefaultBlockFactor;
+		userId   = 0;

 		string sysUserName = Environment.UserName;
-		this.userName = ((sysUserName == null) ? "" : sysUserName);
+		userName = ((sysUserName == null) ? "" : sysUserName);

-		this.groupId   = 0;
-		this.groupName = "None";
+		groupId   = 0;
+		groupName = "None";
 	}

 	/// <summary>


Add keys to entities formerly without them

Signed-off-by: Max Cairney-Leeming <d90f0d0190ac210d40c0e06a2594c771efeb4f5b@gmail.com>


Always cancel notification when it is clicked.

--- src/Android/UI.Android.cs
+++ src/Android/UI.Android.cs
@@ -27,16 +27,18 @@
         protected override void OnDestroy()
         {
             base.OnDestroy();
-            if (AppUI._notificationTcs != null)
-            {
-                AppUI._notificationTcs.TrySetResult(true);
+            if (AppUI._notificationTcs != null &&
+                AppUI._notificationTcs.TrySetResult(true))
+            {
+                var manager = (NotificationManager)GetSystemService(NotificationService);
+                manager.Cancel(AppUI.NotificationCode);
             }
         }
     }

     public partial class AppUI : IAppUI
     {
-        private const int NotificationCode = 90002;
+        internal const int NotificationCode = 90002;

         private int lastNotificationId;


Fix bugs in android notify

Fix bugs in android notify

--- src/Android/UI.Android.cs
+++ src/Android/UI.Android.cs
@@ -16,16 +16,16 @@
     using Android.Text.Method;

     [Activity]
-    class RedirectActivity : Activity
+    class NotificationRedirectActivity : Activity
     {
-        public RedirectActivity()
-        {
+        public NotificationRedirectActivity()
+        {
+            Finish();
+
             if (AppUI._notificationTcs != null)
             {
                 AppUI._notificationTcs.TrySetResult(true);
             }
-
-            Finish();
         }
     }

@@ -123,11 +123,11 @@

             if (_notificationTcs != null)
             {
-                _notificationTcs.SetResult(false);
+                _notificationTcs.TrySetResult(false);
             }
             _notificationTcs = new TaskCompletionSource<bool>();

-            var intent = new Intent(context, typeof(RedirectActivity));
+            var intent = new Intent(context, typeof(NotificationRedirectActivity));

             intent.SetFlags(ActivityFlags.ReorderToFront);


Fix for BL-8228 Error in Book.AllLanguages  with Juarez-Guatemala branding

--- src/BloomExe/Book/Book.cs
+++ src/BloomExe/Book/Book.cs
@@ -1808,6 +1808,12 @@
 			var xmatterXpath = countXmatter ? "" : " and not(contains(@class, 'bloom-frontMatter')) and not(contains(@class, 'bloom-backMatter'))";
 			// editable divs that are in non-x-matter pages and have a potentially interesting language.
 			var langDivs = OurHtmlDom.SafeSelectNodes(pageXpathFront + xmatterXpath + xpathEnd).Cast<XmlElement>()
+				// BL-8228. Don't proceed if this is a text without normal parentage, e.g. boilerplate text from a Branding pack.
+				// Before we added this line, the next one (testing for bloom-ignoreChildrenForBookLanguageList) would throw with
+				// the Juarez and Associates (Guatemala) Branding Pack.
+				.Where(div => div.ParentNode?.Attributes?["class"] != null)
+				// At least up through 4.7, bloom-ignoreChildrenForBookLanguageList is used to prevent counting localized
+				// headers in comprehension quiz as languages of the book.
 				.Where(div => !div.ParentNode.Attributes["class"].Value.Contains("bloom-ignoreChildrenForBookLanguageList"))
 				.Where(div => div.Attributes["class"].Value.IndexOf("bloom-editable", StringComparison.InvariantCulture) >= 0)
 				.Where(div =>


revert common assembly info

revert common assembly info

--- src/CommonAssemblyInfo.cs
+++ src/CommonAssemblyInfo.cs
@@ -24,8 +24,8 @@

-[assembly: AssemblyVersion("0.3.10")]
+[assembly: AssemblyVersion("0.3.7")]

-[assembly: AssemblyFileVersion("0.3.10")]
+[assembly: AssemblyFileVersion("0.3.7")]


Update DateTimeExtensions.cs

Update DateTimeExtensions.cs

--- src/DateTimeExtensions.cs
+++ src/DateTimeExtensions.cs
@@ -3,6 +3,9 @@

 namespace HallLibrary.Extensions
 {
+	/// <summary>
+	/// Contains extension methods for working with <see cref="DateTime" />s.
+	/// </summary>
 	public static class DateTimeExtensions
 	{
 		/// <summary>


Update XML doc comments

Update XML doc comments

--- src/DotNet/ModuleDefMD.cs
+++ src/DotNet/ModuleDefMD.cs
@@ -435,7 +435,7 @@
 		}

 		/// <summary>
-		/// Resolves a <see cref="InterfaceImpl"/>
+		/// Resolves an <see cref="InterfaceImpl"/>
 		/// </summary>
 		/// <param name="rid">The row ID</param>
 		/// <returns>A <see cref="InterfaceImpl"/> instance or null if <paramref name="rid"/> is invalid</returns>
@@ -516,7 +516,7 @@
 		}

 		/// <summary>
-		/// Resolves a <see cref="EventMap"/>
+		/// Resolves an <see cref="EventMap"/>
 		/// </summary>
 		/// <param name="rid">The row ID</param>
 		/// <returns>A <see cref="EventMap"/> instance or null if <paramref name="rid"/> is invalid</returns>
@@ -525,7 +525,7 @@
 		}

 		/// <summary>
-		/// Resolves a <see cref="EventPtr"/>
+		/// Resolves an <see cref="EventPtr"/>
 		/// </summary>
 		/// <param name="rid">The row ID</param>
 		/// <returns>A <see cref="EventPtr"/> instance or null if <paramref name="rid"/> is invalid</returns>
@@ -534,7 +534,7 @@
 		}

 		/// <summary>
-		/// Resolves a <see cref="EventDef"/>
+		/// Resolves an <see cref="EventDef"/>
 		/// </summary>
 		/// <param name="rid">The row ID</param>
 		/// <returns>A <see cref="EventDef"/> instance or null if <paramref name="rid"/> is invalid</returns>
@@ -606,7 +606,7 @@
 		}

 		/// <summary>
-		/// Resolves a <see cref="ImplMap"/>
+		/// Resolves an <see cref="ImplMap"/>
 		/// </summary>
 		/// <param name="rid">The row ID</param>
 		/// <returns>A <see cref="ImplMap"/> instance or null if <paramref name="rid"/> is invalid</returns>
@@ -624,7 +624,7 @@
 		}

 		/// <summary>
-		/// Resolves a <see cref="ENCLog"/>
+		/// Resolves an <see cref="ENCLog"/>
 		/// </summary>
 		/// <param name="rid">The row ID</param>
 		/// <returns>A <see cref="ENCLog"/> instance or null if <paramref name="rid"/> is invalid</returns>
@@ -633,7 +633,7 @@
 		}

 		/// <summary>
-		/// Resolves a <see cref="ENCMap"/>
+		/// Resolves an <see cref="ENCMap"/>
 		/// </summary>
 		/// <param name="rid">The row ID</param>
 		/// <returns>A <see cref="ENCMap"/> instance or null if <paramref name="rid"/> is invalid</returns>
@@ -642,7 +642,7 @@
 		}

 		/// <summary>
-		/// Resolves a <see cref="AssemblyDef"/>
+		/// Resolves an <see cref="AssemblyDef"/>
 		/// </summary>
 		/// <param name="rid">The row ID</param>
 		/// <returns>A <see cref="AssemblyDef"/> instance or null if <paramref name="rid"/> is invalid</returns>
@@ -651,7 +651,7 @@
 		}

 		/// <summary>
-		/// Resolves a <see cref="AssemblyProcessor"/>
+		/// Resolves an <see cref="AssemblyProcessor"/>
 		/// </summary>
 		/// <param name="rid">The row ID</param>
 		/// <returns>A <see cref="AssemblyProcessor"/> instance or null if <paramref name="rid"/> is invalid</returns>
@@ -660,7 +660,7 @@
 		}

 		/// <summary>
-		/// Resolves a <see cref="AssemblyOS"/>
+		/// Resolves an <see cref="AssemblyOS"/>
 		/// </summary>
 		/// <param name="rid">The row ID</param>
 		/// <returns>A <see cref="AssemblyOS"/> instance or null if <paramref name="rid"/> is invalid</returns>
@@ -669,7 +669,7 @@
 		}

 		/// <summary>
-		/// Resolves a <see cref="AssemblyRef"/>
+		/// Resolves an <see cref="AssemblyRef"/>
 		/// </summary>
 		/// <param name="rid">The row ID</param>
 		/// <returns>A <see cref="AssemblyRef"/> instance or null if <paramref name="rid"/> is invalid</returns>
@@ -678,7 +678,7 @@
 		}

 		/// <summary>
-		/// Resolves a <see cref="AssemblyRefProcessor"/>
+		/// Resolves an <see cref="AssemblyRefProcessor"/>
 		/// </summary>
 		/// <param name="rid">The row ID</param>
 		/// <returns>A <see cref="AssemblyRefProcessor"/> instance or null if <paramref name="rid"/> is invalid</returns>
@@ -687,7 +687,7 @@
 		}

 		/// <summary>
-		/// Resolves a <see cref="AssemblyRefOS"/>
+		/// Resolves an <see cref="AssemblyRefOS"/>
 		/// </summary>
 		/// <param name="rid">The row ID</param>
 		/// <returns>A <see cref="AssemblyRefOS"/> instance or null if <paramref name="rid"/> is invalid</returns>
@@ -705,7 +705,7 @@
 		}

 		/// <summary>
-		/// Resolves a <see cref="ExportedType"/>
+		/// Resolves an <see cref="ExportedType"/>
 		/// </summary>
 		/// <param name="rid">The row ID</param>
 		/// <returns>A <see cref="ExportedType"/> instance or null if <paramref name="rid"/> is invalid</returns>
@@ -944,7 +944,7 @@
 		}

 		/// <summary>
-		/// Resolves a <see cref="IImplementation"/>
+		/// Resolves an <see cref="IImplementation"/>
 		/// </summary>
 		/// <param name="codedToken">An <c>Implementation</c> coded token</param>
 		/// <returns>A <see cref="IImplementation"/> or null if <paramref name="codedToken"/> is invalid</returns>


 * Fixed a bug in the uber-ctor for UserInfo

git-svn-id: e2945e6dc2723cb01f425b5a7c3c201ce5019a89@952 080cfd25-d5d9-4c59-82ea-70d02a200d8b

--- src/Gablarski/UserInfo.cs
+++ src/Gablarski/UserInfo.cs
@@ -129,6 +129,8 @@
 			UserId = userId;
 			CurrentChannelId = currentChannelId;
 			IsMuted = muted;
+			Comment = comment;
+			Status = status;
 		}

 		internal UserInfo (string username, int userId, int currentChannelId, bool muted)


Save downloaded files to application data folder.

--- kanboxwp/kanboxwp/Utils/FileUtil.cs
+++ kanboxwp/kanboxwp/Utils/FileUtil.cs
@@ -177,7 +177,7 @@
             {
                 throw new ArgumentException("Invalid file name (null).");
             }
-            StorageFile localFile = await CreateFileInFolders(fileName);
+            StorageFile localFile = await CreateFileInAppDataFolder(fileName);
             using (var localFileStream = await localFile.OpenStreamForWriteAsync())
             {
                 await inputStream.CopyToAsync(localFileStream);
@@ -185,7 +185,7 @@
             return localFile;
         }

-        private static async Task<StorageFile> CreateFileInFolders(string fileName)
+        private static async Task<StorageFile> CreateFileInAppDataFolder(string fileName)
         {
             int lastPathSeperatorIndex = fileName.LastIndexOf("/");
             string fPath = null;
@@ -210,6 +210,35 @@
         }

         /// <summary>
+        /// Get StorageFile object from local application data folder.
+        /// </summary>
+        /// <param name="fileFullName">File name with full path.</param>
+        /// <returns></returns>
+        public static async Task<StorageFile >GetFileInAppDataFolder(string fileFullName)
+        {
+            int lastPathSeperatorIndex = fileFullName.LastIndexOf("/");
+            string fPath = null;
+            string fName = fileFullName;
+            if (lastPathSeperatorIndex >= 0)
+            {
+                fPath = fileFullName.Substring(0, lastPathSeperatorIndex);
+                fName = fileFullName.Substring(lastPathSeperatorIndex + 1);
+            }
+
+            StorageFolder localFolder = ApplicationData.Current.LocalFolder;
+            string[] pathes = fPath.Split('/');
+            for (int i = 0; i < pathes.Length; i++)
+            {
+                if (!string.IsNullOrEmpty(pathes[i].Trim()))
+                {
+                    localFolder = await localFolder.GetFolderAsync(pathes[i]);
+                }
+            }
+            StorageFile sfile = await localFolder.GetFileAsync(fName);
+            return sfile;
+        }
+
+        /// <summary>
         /// Get parent path.
         /// </summary>
         /// <param name="path">Input path MUST hasn't filename.</param>


Updated version to 1.5.3

Updated version to 1.5.3

--- src/GlobalAssemblyInfo.cs
+++ src/GlobalAssemblyInfo.cs
@@ -27,4 +27,4 @@
 // You can specify all the values or you can default the Build and Revision Numbers
 // by using the '*' as shown below:

-[ assembly : AssemblyVersion( "1.5.2.0" ) ]+[ assembly : AssemblyVersion( "1.5.3.0" ) ]


Increment AssemblyVersion. Resolves #299

--- src/GlobalAssemblyInfo.cs
+++ src/GlobalAssemblyInfo.cs
@@ -7,5 +7,5 @@

 [assembly: NeutralResourcesLanguage("en-US")]

-[assembly: AssemblyVersion("2.0.2.0")]
-[assembly: AssemblyFileVersion("2.0.2.0")]
+[assembly: AssemblyVersion("3.0.0.0")]
+[assembly: AssemblyFileVersion("3.0.0.0")]


Update code analysis suppression list.

Update code analysis suppression list.

--- src/GlobalSuppressions.cs
+++ src/GlobalSuppressions.cs
@@ -12,7 +12,7 @@

 // Filename: GlobalSuppressions.cs

-// Version:  2020-01-13 13:05
+// Version:  2020-01-20 20:39

 //

@@ -128,6 +128,8 @@

 [assembly: SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope", Justification = "Typical false positive", Scope = "member", Target = "~M:SilDev.Drawing.ImageEx.SwitchGrayScale(System.Drawing.Image,System.Object,System.Boolean)~System.Drawing.Image")]

+[assembly: SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope", Justification = "Typical false positive", Scope = "member", Target = "~M:SilDev.Forms.FormEx.FadeIn(System.Windows.Forms.Form,System.Int32,System.Double,System.Boolean)")]
+
 [assembly: SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope", Justification = "Typical false positive", Scope = "member", Target = "~M:SilDev.Forms.RichTextBoxEx.SetDefaultContextMenuStrip(System.Windows.Forms.RichTextBox,System.Windows.Forms.IWin32Window)")]

 [assembly: SuppressMessage("Usage", "CA2217:Do not mark enums with FlagsAttribute", Justification = "Enums are not disqualified for FlagsAttribute if some intermediate bit fields are left out or skipped", Scope = "type", Target = "~T:SilDev.WinApi.ProcessInfoFlags")]


fix bug

fix bug

--- src/MSharp/Entity/User.cs
+++ src/MSharp/Entity/User.cs
@@ -22,14 +22,14 @@
 		{
 			var j = Json.Parse(jsonString);

-			this.BannerImageUrl = j.bannerImageUrl.Value != null ? new Uri(j.bannerImageUrl.Value) : null;
+			this.BannerImageUrl = !string.IsNullOrEmpty(j.bannerImageUrl.Value) ? new Uri(j.bannerImageUrl.Value) : null;
 			this.Bio = j.bio.Value;
 			this.Color = ColorTranslator.FromHtml(j.color.Value);
 			this.Comment = j.comment.Value;
 			this.CreatedAt = null; //TODO
 			this.FollowersCount = j.followersCount.Value;
 			this.FollowingsCount = j.followingsCount.Value;
-			this.IconImageUrl = j.iconImageUrl.Value != null ? new Uri(j.iconImageUrl.Value) : null;
+			this.IconImageUrl = !string.IsNullOrEmpty(j.iconImageUrl.Value) ? new Uri(j.iconImageUrl.Value) : null;
 			this.Id = j.id.Value;
 			this.IsDisplayNotFollowUserMention = j.isDisplayNotFollowUserMention.Value;
 			this.IsPlus = j.isPlus.Value;
@@ -47,8 +47,8 @@
 			this.Tags = new List<string>();
 			foreach (var tag in j.tags)
 				this.Tags.Add(tag.Value);
-			this.Url = j.url.Value != null ? new Uri(j.url.Value) : null;
-			this.WallpaperImageUrl = j.wallpaperImageUrl.Value != null ? new Uri(j.wallpaperImageUrl.Value) : null;
+			this.Url = !string.IsNullOrEmpty(j.url.Value) ? new Uri(j.url.Value) : null;
+			this.WallpaperImageUrl = !string.IsNullOrEmpty(j.wallpaperImageUrl.Value) ? new Uri(j.wallpaperImageUrl.Value) : null;
 		}

 		/// <summary>


add update after file delete

add update after file delete

--- src/MacroManager/Addon.cs
+++ src/MacroManager/Addon.cs
@@ -103,6 +103,7 @@
                             else
                             {
                                 MessageBox.Show(e.Form, MacroManagerResources.PathNotFoundMessage.FormatString(macro.Path), "Citavi", MessageBoxButtons.OK, MessageBoxIcon.Error);
+                                UpdateTools(e.Form, true);
                             }

                         }


Fix #559

Fix #559

--- letsencrypt-win-simple/Program.cs
+++ letsencrypt-win-simple/Program.cs
@@ -147,7 +147,7 @@
                     Log.Error("Exception {@e}", e.Message);
                 }

-                if (Options.Test || (!Options.Renew && !Options.CloseOnFinish))
+                if (!Options.CloseOnFinish && (!Options.Renew || Options.Test))
                 {
                     if (Input.PromptYesNo("Would you like to start again?"))
                     {


added try/catch around Directory.CreateDirectory(certificatePath);

--- letsencrypt-win-simple/Program.cs
+++ letsencrypt-win-simple/Program.cs
@@ -82,13 +82,24 @@
             Directory.CreateDirectory(configPath);

             certificatePath = Properties.Settings.Default.CertificatePath;
+
             if (string.IsNullOrWhiteSpace(certificatePath))
             {
                 certificatePath = configPath;
             }
+
+            try
+            {
+                Directory.CreateDirectory(certificatePath);
+            }
+            catch (Exception ex)
+            {
+                Log.Error("Error creating the certificate directory. Error: {@ex}", ex);
+                return;
+            }
+
             Console.WriteLine("Certificate Folder: " + certificatePath);
             Log.Information("Certificate Folder: {certificatePath}", certificatePath);
-            Directory.CreateDirectory(certificatePath);

             try
             {


IsFlying flag for spawn in air.

IsFlying flag for spawn in air.

--- src/MiNET/MiNET/Player.cs
+++ src/MiNET/MiNET/Player.cs
@@ -469,6 +469,7 @@
 		public bool IsNoPvm { get; set; }
 		public bool IsNoMvp { get; set; }
 		public bool IsNoClip { get; set; }
+		public bool IsFlying { get; set; };

 		public virtual void SendAdventureSettings()
 		{
@@ -488,7 +489,8 @@
 			if (IsNoClip || IsSpectator || GameMode == GameMode.Spectator) flags |= 0x80; // No clip

 			flags |= 0x100; // Worldbuilder
-			//flags |= 0x200; // Flying
+
+			if (IsFlying) flags |= 0x200;
 			//flags |= 0x400; // Mute

 			mcpeAdventureSettings.flags = flags;


ValidateConfig in Program: check for conflicting stratum ports

--- src/MiningCore/Program.cs
+++ src/MiningCore/Program.cs
@@ -254,13 +254,14 @@
 				logger.ThrowLogPoolStartupException("No pools configured!");

 			ValidatePoolIds();
+			ValidateStratumPorts();
 		}

 		private static void ValidatePoolIds()
 		{
 			// check for missing ids
 			if (clusterConfig.Pools.Any(pool => string.IsNullOrEmpty(pool.Id)))
-				logger.ThrowLogPoolStartupException($"Pool {clusterConfig.Pools.ToList().IndexOf(clusterConfig.Pools.First(pool => string.IsNullOrEmpty(pool.Id)))} has an empty id!");
+				throw new PoolStartupAbortException($"Pool {clusterConfig.Pools.ToList().IndexOf(clusterConfig.Pools.First(pool => string.IsNullOrEmpty(pool.Id)))} has an empty id!");

 			// check for duplicate ids
 			var ids = clusterConfig.Pools
@@ -268,7 +269,20 @@
 				.ToArray();

 			if (ids.Any(id => id.Count() > 1))
-				logger.ThrowLogPoolStartupException($"Duplicate pool id '{ids.First(id => id.Count() > 1).Key}'!");
+				throw new PoolStartupAbortException($"Duplicate pool id '{ids.First(id => id.Count() > 1).Key}'!");
+		}
+
+		private static void ValidateStratumPorts()
+		{
+			var ports = clusterConfig.Pools.SelectMany(x => x.Ports.Select(y => y.Key))
+				.GroupBy(x => x)
+				.ToArray();
+
+			foreach (var port in ports)
+			{
+				if(port.Count() > 1)
+					throw new PoolStartupAbortException($"Stratum port {port.Key} is used multiple times");
+			}
 		}

 		private static void ValidateRuntimeEnvironment()


Fix benchmark

Fix benchmark

--- tests/Scratch/Benchmark.cs
+++ tests/Scratch/Benchmark.cs
@@ -1,10 +1,8 @@
 using BenchmarkDotNet.Attributes;
-using BosunReporter;
-using BosunReporter.Metrics;
+using StackExchange.Metrics;
+using StackExchange.Metrics.Metrics;
 using System;
 using System.Collections.Generic;
-using System.Diagnostics;
-using System.Text;
 using System.Threading;
 using System.Threading.Tasks;

@@ -23,7 +21,7 @@
         {
             _cancellationTokenSource = new CancellationTokenSource();

-            var emptyOptions = new BosunOptions(ex => Console.WriteLine(ex))
+            var emptyOptions = new MetricsCollectorOptions(ex => Console.WriteLine(ex))
             {
                 Endpoints = Array.Empty<MetricEndpoint>(),
                 DefaultTags = new Dictionary<string, string> { { "host", NameTransformers.Sanitize(Environment.MachineName.ToLower()) } },
@@ -32,7 +30,7 @@
                 ThrowOnQueueFull = false,
             };

-            var httpOptions = new BosunOptions(ex => Console.WriteLine(ex))
+            var httpOptions = new MetricsCollectorOptions(ex => Console.WriteLine(ex))
             {
                 Endpoints = new[]
                 {
@@ -44,7 +42,7 @@
                 ThrowOnQueueFull = false,
             };

-            var udpOptions = new BosunOptions(ex => Console.WriteLine(ex))
+            var udpOptions = new MetricsCollectorOptions(ex => Console.WriteLine(ex))
             {
                 Endpoints = new[]
                 {


Deduplicate.

Deduplicate.


Magnitude of Complex(inf,inf) == inf

Magnitude of Complex(inf,inf) == inf

--- src/Numerics/Complex32.cs
+++ src/Numerics/Complex32.cs
@@ -188,6 +188,8 @@
             {
                 float a = Math.Abs(_real);
                 float b = Math.Abs(_imag);
+                if (float.IsPositiveInfinity(a) && float.IsPositiveInfinity(b))
+                    return float.PositiveInfinity;
                 if (a > b)
                 {
                     double tmp = b / a;
@@ -201,8 +203,8 @@
                 else
                 {
                     double tmp = a / b;
-                    return b*(float)Math.Sqrt(1.0f + tmp*tmp);
-                }
+                    return b * (float)Math.Sqrt(1.0f + tmp * tmp);
+                }
             }
         }

@@ -504,9 +506,9 @@
         /// </summary>
         public Tuple<Complex32, Complex32, Complex32> CubicRoots()
         {
-            float r = (float)Math.Pow(Magnitude, 1d/3d);
-            float theta = Phase/3;
-            const float shift = (float)Constants.Pi2/3;
+            float r = (float)Math.Pow(Magnitude, 1d / 3d);
+            float theta = Phase / 3;
+            const float shift = (float)Constants.Pi2 / 3;
             return new Tuple<Complex32, Complex32, Complex32>(
                 FromPolarCoordinates(r, theta),
                 FromPolarCoordinates(r, theta + shift),
@@ -676,7 +678,7 @@
             float r = d / c;
             float t = 1 / (c + d * r);
             float e, f;
-            if (r!=0.0f) // one can use r >= float.Epsilon || r <= float.Epsilon instead
+            if (r != 0.0f) // one can use r >= float.Epsilon || r <= float.Epsilon instead
             {
                 e = (a + b * r) * t;
                 f = (b - a * r) * t;


结果集实现更多接口

结果集实现更多接口

--- src/ObjectAccessResult.cs
+++ src/ObjectAccessResult.cs
@@ -35,7 +35,7 @@
 		#endregion
 	}

-	public class ObjectAccessResult<T> : ObjectAccessResult, IEnumerable<T>, IEnumerator<T>
+	public class ObjectAccessResult<T> : ObjectAccessResult, IEnumerator<T>, ICollection, IList<T>, IList
 	{
 		#region 静态字段
 		private static readonly object _lock = new object();
@@ -44,6 +44,7 @@
 		#region 字段
 		private IEnumerator _enumerator;
 		private Execute<T> _getResult;
+		private List<T> _list;
 		#endregion

 		#region 构造函数
@@ -55,22 +56,32 @@
 		#endregion

 		#region 属性
-		public IEnumerator Enumerator
-		{
-			get
-			{
-				if(_enumerator == null)
+		private List<T> List
+		{
+			get
+			{
+				if(_list == null)
 				{
 					lock(_lock)
 					{
-						if(_enumerator == null)
+						if(_list == null)
 						{
 							var parameter = new CreatingSqlParameter(false, 0, 0, 0);
 							var result = base.CreateSql(parameter);
-							_enumerator = _getResult(result).ToList().GetEnumerator();
+							_list = _getResult(result).ToList();
 						}
 					}
 				}
+				return _list;
+			}
+		}
+
+		public IEnumerator Enumerator
+		{
+			get
+			{
+				if(_enumerator == null)
+					_enumerator = List.GetEnumerator();
 				return _enumerator;
 			}
 		}
@@ -126,5 +137,147 @@
 			}
 		}
 		#endregion
+
+		#region ICollection 成员
+		public void CopyTo(Array array, int index)
+		{
+			((ICollection)List).CopyTo(array, index);
+		}
+
+		public int Count
+		{
+			get
+			{
+				return List.Count;
+			}
+		}
+
+		public bool IsSynchronized
+		{
+			get
+			{
+				return ((ICollection)List).IsSynchronized;
+			}
+		}
+
+		public object SyncRoot
+		{
+			get
+			{
+				return ((ICollection)List).SyncRoot;
+			}
+		}
+		#endregion
+
+		#region IList<T> 成员
+		public int IndexOf(T item)
+		{
+			return List.IndexOf(item);
+		}
+
+		public void Insert(int index, T item)
+		{
+			List.Insert(index, item);
+		}
+
+		public void RemoveAt(int index)
+		{
+			List.RemoveAt(index);
+		}
+
+		public T this[int index]
+		{
+			get
+			{
+				return List[index];
+			}
+			set
+			{
+				List[index] = value;
+			}
+		}
+		#endregion
+
+		#region ICollection<T> 成员
+		public void Add(T item)
+		{
+			List.Add(item);
+		}
+
+		public void Clear()
+		{
+			List.Clear();
+		}
+
+		public bool Contains(T item)
+		{
+			return List.Contains(item);
+		}
+
+		public void CopyTo(T[] array, int arrayIndex)
+		{
+			((ICollection<T>)List).CopyTo(array, arrayIndex);
+		}
+
+		public bool IsReadOnly
+		{
+			get
+			{
+				return ((ICollection<T>)List).IsReadOnly;
+			}
+		}
+
+		public bool Remove(T item)
+		{
+			return List.Remove(item);
+		}
+		#endregion
+
+		#region IList 成员
+		public int Add(object value)
+		{
+			return ((IList)List).Add(value);
+		}
+
+		public bool Contains(object value)
+		{
+			return ((IList)List).Contains(value);
+		}
+
+		public int IndexOf(object value)
+		{
+			return ((IList)List).IndexOf(value);
+		}
+
+		public void Insert(int index, object value)
+		{
+			((IList)List).Insert(index, value);
+		}
+
+		public bool IsFixedSize
+		{
+			get
+			{
+				return ((IList)List).IsFixedSize;
+			}
+		}
+
+		public void Remove(object value)
+		{
+			((IList)List).Remove(value);
+		}
+
+		object IList.this[int index]
+		{
+			get
+			{
+				return ((IList)List)[index];
+			}
+			set
+			{
+				((IList)List)[index] = value;
+			}
+		}
+		#endregion
 	}
 }


Remove unused variable

Remove unused variable

--- src/ProjectEuler/Maths.cs
+++ src/ProjectEuler/Maths.cs
@@ -237,8 +237,6 @@
                 return result;
             }

-            long sqrt = (long)Math.Sqrt(value);
-
             result = true;

             long i = 5;


Increase version to 2.4.0

Increase version to 2.4.0

--- src/Properties/Version.cs
+++ src/Properties/Version.cs
@@ -25,5 +25,5 @@
 //      Revision
 //
 [assembly: AssemblyVersion("2.1.0")]
-[assembly: AssemblyFileVersion("2.3.0")]
-[assembly: AssemblyInformationalVersion("2.3.0")]
+[assembly: AssemblyFileVersion("2.4.0")]
+[assembly: AssemblyInformationalVersion("2.4.0")]


Show good message if async is not supported

cf. #632

--- source/Glimpse.AspNet/AspNetFrameworkProvider.cs
+++ source/Glimpse.AspNet/AspNetFrameworkProvider.cs
@@ -1,6 +1,7 @@
 using System;
 using System.Configuration;
 using System.Runtime.Remoting.Messaging;
+using System.Runtime.Serialization;
 using System.Web;
 using Glimpse.AspNet.Extensions;
 using Glimpse.Core.Extensibility;
@@ -56,12 +57,12 @@
             }

             if (HttpContext.Current == null)
-                return CallContext.LogicalGetData("Glimpse.HttpContext") as HttpContextBase;
+                return AntiSerializationWrapper<HttpContextBase>.Unwrap(CallContext.LogicalGetData("Glimpse.HttpContext"));

-            var wrapper = new HttpContextWrapper(HttpContext.Current);
-            CallContext.LogicalSetData("Glimpse.HttpContext", wrapper);
+            var context = new HttpContextWrapper(HttpContext.Current);
+            CallContext.LogicalSetData("Glimpse.HttpContext", new AntiSerializationWrapper<HttpContextBase>(context));

-            return wrapper;
+            return context;
         }

         private ILogger Logger { get; set; }
@@ -142,5 +143,31 @@
                 Logger.Error("Exception writing Http response.", exception);
             }
         }
+
+        [Serializable]
+        private struct AntiSerializationWrapper<T> : ISerializable
+        {
+            private readonly T value;
+
+            public AntiSerializationWrapper(T value)
+            {
+                this.value = value;
+            }
+
+            public void GetObjectData(SerializationInfo info, StreamingContext context)
+            {
+                throw new NotSupportedException(
+                    "Some environments conflict with current Glimpse async support. " +
+                    "Please set Glimpse:DisableAsyncSupport = true in Web.config, or see https://github.com/Glimpse/Glimpse/issues/632 for more details.");
+            }
+
+            public static T Unwrap(object wrapper)
+            {
+                if (ReferenceEquals(wrapper, null))
+                    return default(T);
+
+                return ((AntiSerializationWrapper<T>)wrapper).value;
+            }
+        }
     }
 }


v2.1.0-beta4

--- src/SharedAssemblyInfo.cs
+++ src/SharedAssemblyInfo.cs
@@ -4,7 +4,7 @@
 [assembly: AssemblyProduct("Cassette")]
 [assembly: AssemblyCopyright("Copyright © 2011 Andrew Davey")]

-[assembly: AssemblyInformationalVersion("2.1.0-beta3")]
+[assembly: AssemblyInformationalVersion("2.1.0-beta4")]

 [assembly: AssemblyVersion("2.1.0.*")]
 [assembly: AssemblyFileVersion("2.1.0.0")]


Changed Unhanded Exception signature. Thank you PCL...

--- src/SimpleAuth/Api/Api.cs
+++ src/SimpleAuth/Api/Api.cs
@@ -15,7 +15,8 @@
 {
 	public class Api
 	{
-		public static event UnhandledExceptionEventHandler UnhandledException;
+		public delegate void ApiExceptionEventHandler(object sender,Exception e);
+		public static event ApiExceptionEventHandler UnhandledException;

 		public bool Verbose { get; set; } = false;

@@ -440,7 +441,7 @@
 		public virtual void OnException(object sender,Exception ex)
 		{
 			Console.WriteLine(ex);
-			UnhandledException?.Invoke(sender, new UnhandledExceptionEventArgs(ex,false));
+			UnhandledException?.Invoke(sender,ex);
 		}
 	}
 }


Added support for adding new pattern converters during configuration

git-svn-id: 223c0ba935819ffdcafdc68147dc609b4e469b1e@312097 13f79535-47bb-0310-9956-ffa450edef68

--- src/Util/PatternString.cs
+++ src/Util/PatternString.cs
@@ -40,7 +40,7 @@
 	/// of the process in general.</para>
 	/// </remarks>
 	/// <author>Nicko Cadell</author>
-	public class PatternString
+	public class PatternString : IOptionHandler
 	{
 		#region Static Fields

@@ -62,6 +62,11 @@
 		/// the head of the pattern converter chain
 		/// </summary>
 		private PatternConverter m_head;
+
+		/// <summary>
+		/// patterns defined on this PatternString only
+		/// </summary>
+		private Hashtable m_instanceRulesRegistry = new Hashtable();

 		#endregion

@@ -105,7 +110,8 @@
 		/// <param name="pattern">The pattern to use with this PatternString</param>
 		public PatternString(string pattern)
 		{
-			ConversionPattern = pattern;
+			m_pattern = pattern;
+			ActivateOptions();
 		}

 		#endregion
@@ -118,12 +124,33 @@
 		public string ConversionPattern
 		{
 			get { return m_pattern;	}
-			set
-			{
-				m_pattern = value;
-				m_head = CreatePatternParser(m_pattern).Parse();
-			}
-		}
+			set { m_pattern = value; }
+		}
+
+		#region Implementation of IOptionHandler
+
+		/// <summary>
+		/// Initialize object options
+		/// </summary>
+		/// <remarks>
+		/// <para>
+		/// This is part of the <see cref="IOptionHandler"/> delayed object
+		/// activation scheme. The <see cref="ActivateOptions"/> method must
+		/// be called on this object after the configuration properties have
+		/// been set. Until <see cref="ActivateOptions"/> is called this
+		/// object is in an undefined state and must not be used.
+		/// </para>
+		/// <para>
+		/// If any of the configuration properties are modified then
+		/// <see cref="ActivateOptions"/> must be called again.
+		/// </para>
+		/// </remarks>
+		virtual public void ActivateOptions()
+		{
+			m_head = CreatePatternParser(m_pattern).Parse();
+		}
+
+		#endregion

 		/// <summary>
 		/// Returns PatternParser used to parse the conversion string. Subclasses
@@ -141,6 +168,11 @@
 			{
 				patternParser.PatternConverters.Add(entry.Key, entry.Value);
 			}
+			// Add the instance patterns
+			foreach(DictionaryEntry entry in m_instanceRulesRegistry)
+			{
+				patternParser.PatternConverters[entry.Key] = entry.Value;
+			}

 			return patternParser;
 		}
@@ -151,6 +183,11 @@
 		/// <param name="writer">The TextWriter to write the formatted event to</param>
 		public void Format(TextWriter writer)
 		{
+			if (writer == null)
+			{
+				throw new ArgumentNullException("writer");
+			}
+
 			PatternConverter c = m_head;

 			// loop through the chain of pattern converters
@@ -171,5 +208,69 @@
 			Format(writer);
 			return writer.ToString();
 		}
+
+		/// <summary>
+		/// Add a converter to this PatternString
+		/// </summary>
+		/// <param name="converterInfo">the converter info</param>
+		/// <remarks>
+		/// This version of the method is used by the configurator.
+		/// Programmatic users should use the alternative <see cref="AddConverter(string,Type)"/> method.
+		/// </remarks>
+		public void AddConverter(ConverterInfo converterInfo)
+		{
+			AddConverter(converterInfo.Name, converterInfo.Type);
+		}
+
+		/// <summary>
+		/// Add a converter to this PatternString
+		/// </summary>
+		/// <param name="name">the name of the conversion pattern for this converter</param>
+		/// <param name="type">the type of the converter</param>
+		public void AddConverter(string name, Type type)
+		{
+			if (name == null) throw new ArgumentNullException("name");
+			if (type == null) throw new ArgumentNullException("type");
+
+			if (!typeof(PatternConverter).IsAssignableFrom(type))
+			{
+				throw new ArgumentException("The converter type specified ["+type+"] must be a subclass of log4net.Util.PatternConverter", "type");
+			}
+			m_instanceRulesRegistry[name] = type;
+		}
+
+		/// <summary>
+		/// Wrapper class used to map converter names to converter types
+		/// </summary>
+		public sealed class ConverterInfo
+		{
+			private string m_name;
+			private Type m_type;
+
+			/// <summary>
+			/// default constructor
+			/// </summary>
+			public ConverterInfo()
+			{
+			}
+
+			/// <summary>
+			/// Gets or sets the name of the conversion pattern
+			/// </summary>
+			public string Name
+			{
+				get { return m_name; }
+				set { m_name = value; }
+			}
+
+			/// <summary>
+			/// Gets or sets the type of the converter
+			/// </summary>
+			public Type Type
+			{
+				get { return m_type; }
+				set { m_type = value; }
+			}
+		}
 	}
 }


This is how it will look in the feature configuration.

--- src/WebApp/HomeFeature.cs
+++ src/WebApp/HomeFeature.cs
@@ -2,6 +2,7 @@
 using System.Web;
 using Dolstagis.Web;
 using Dolstagis.Web.Sessions;
+using Dolstagis.Web.StructureMap;

 namespace WebApp
 {
@@ -11,6 +12,11 @@
         {
             Description("The home page and static content.");
             Active.When(req => true);
+
+            Container.Is<StructureMapContainer>()
+                .Setup.Application(x => { })
+                .Setup.Domain(x => { })
+                .Setup.Request(x => { });

             Services.For<ISessionStore>().Singleton().Use<InMemorySessionStore>();


Revert remove assert formula.RootAtom != null

--- src/WpfMath/TexFormula.cs
+++ src/WpfMath/TexFormula.cs
@@ -1,4 +1,4 @@
-using System.Collections.Generic;
+using System.Collections.Generic;
 using System.Diagnostics;
 using System.Linq;
 using System.Windows.Media;
@@ -33,6 +33,7 @@
         public void Add(TexFormula formula, SourceSpan source = null)
         {
             Debug.Assert(formula != null);
+            Debug.Assert(formula.RootAtom != null);

             this.Add(
                 formula.RootAtom is RowAtom


* optimization for the voronoi edges filtering and deep traverse

--- matmill.cs
+++ matmill.cs
@@ -68,7 +68,7 @@

             public void Add(Line2F seg)
             {
-                ulong[] h1 = hash(seg.p1);
+                ulong[] h1 = hash(seg.p1);

                 insert_seg(h1[0], seg);
                 insert_seg(h1[1], seg);
@@ -85,7 +85,7 @@

             public void Remove(Line2F seg)
             {
-                ulong[] h1 = hash(seg.p1);
+                ulong[] h1 = hash(seg.p1);

                 remove_seg(h1[0], seg);
                 remove_seg(h1[1], seg);
@@ -251,6 +251,8 @@

             public bool Is_leaf { get { return Children.Count == 0; } }

+            double _deep_distance = 0;
+
             public List<Branch> Df_traverse()  //
             {
                 List<Branch> result = new List<Branch>();
@@ -260,9 +262,11 @@
                 return result;
             }

-
+            // NOTE: deep distance is memoized, so this should be called only on finalized branch
             public double Deep_distance()
             {
+                if (_deep_distance != 0) return _deep_distance;
+
                 double dist = Curve.GetPerimeter();
                 foreach (Branch b in Children)
                     dist += b.Deep_distance();
@@ -315,7 +319,7 @@
         {
             List<Point2F> points = new List<Point2F>();
             foreach (Point3F pt in PointListUtils.CreatePointlistFromPolylineStep(p, step).Points.ToArray())
-                points.Add(new Point2F(pt.X, pt.Y));
+                points.Add((Point2F) pt);
             if (points.Count < 2) return points;
             // sometimes first and last points would be too close to each other for the closed shapes, remove dupe
             if (Point2F.Distance(points[0], points[points.Count - 1]) < GENERAL_TOLERANCE * 4)
@@ -328,6 +332,8 @@

         List<Line2F> get_mat_segments()
         {
+            bool ANALIZE_INNER_INTERSECTIONS = false;
+
             List<Point2F> plist = new List<Point2F>();

             plist.AddRange(sample_curve(this._reg.OuterCurve, _cutter_r / 10));
@@ -361,35 +367,36 @@

             List<GraphEdge> edges = new Voronoi(GENERAL_TOLERANCE).generateVoronoi(xs, ys, min_x, max_x, min_y, max_y);

-            Host.log("voroning completed");
+            Host.log("voroning completed. Got {0} edges", edges.Count);

             List<Line2F> inner_segments = new List<Line2F>();

             foreach (GraphEdge e in edges)
             {
-                if (new Point2F(e.x1, e.y1).DistanceTo(new Point2F(e.x2, e.y2)) < GENERAL_TOLERANCE)
-                    continue;
-
-                Line2F line = new Line2F(e.x1, e.y1, e.x2, e.y2);
-                Polyline p = new Line(line).ToPolyline();
-
-                if (this._reg.OuterCurve.Intersects(p)) continue;
-                if (this._reg.OuterCurve.PolylineOutsidePolyline(p, GENERAL_TOLERANCE)) continue;
+                Line2F seg = new Line2F(e.x1, e.y1, e.x2, e.y2);
+
+                if (seg.Length() < GENERAL_TOLERANCE) continue;    // extra small segment, discard
+                if (!_reg.OuterCurve.PointInPolyline(seg.p1, GENERAL_TOLERANCE)) continue;  // p1 is outside of outer curve boundary
+                if (!_reg.OuterCurve.PointInPolyline(seg.p2, GENERAL_TOLERANCE)) continue;  // p2 is outside of outer curve boundary
+                if (ANALIZE_INNER_INTERSECTIONS && _reg.OuterCurve.LineIntersections(seg, GENERAL_TOLERANCE).Length != 0) continue; // both endpoints are inside, but there are intersections, outer curve must be concave

                 bool should_add = true;
                 foreach (Polyline hole in this._reg.HoleCurves)
                 {
-                    if (hole.Intersects(p) || hole.PolylineInsidePolyline(p, GENERAL_TOLERANCE))
+                    if (   hole.PointInPolyline(seg.p1, GENERAL_TOLERANCE)                      // p1 is inside hole
+                        || hole.PointInPolyline(seg.p2, GENERAL_TOLERANCE)                      // p2 is inside hole
+                        || (ANALIZE_INNER_INTERSECTIONS && hole.LineIntersections(seg, GENERAL_TOLERANCE).Length != 0))          // p1, p2 are outside hole, but there are intersections
                     {
                         should_add = false;
                         break;
                     }
                 }

-
                 if (should_add)
-                    inner_segments.Add(line);
-            }
+                    inner_segments.Add(seg);
+            }
+
+            Host.log("Got {0} inner segments", inner_segments.Count);

             return inner_segments;
         }
@@ -401,13 +408,13 @@
             Vector2F normal = new Vector2F();
             int seg = 0;

-            Point3F nearest = this._reg.OuterCurve.GetNearestPoint(pt, ref normal, ref seg, true);
-            radius = Point2F.Distance(point(nearest), pt);
+            Point2F nearest = (Point2F) this._reg.OuterCurve.GetNearestPoint(pt, ref normal, ref seg, true);
+            radius = pt.DistanceTo(nearest);

             foreach (Polyline hole in this._reg.HoleCurves)
             {
-                nearest = hole.GetNearestPoint(pt, ref normal, ref seg, true);
-                double dist = Point2F.Distance(point(nearest), pt);
+                nearest = (Point2F)hole.GetNearestPoint(pt, ref normal, ref seg, true);
+                double dist = pt.DistanceTo(nearest);
                 if (dist < radius)
                     radius = dist;
             }
@@ -620,7 +627,7 @@

         void attach_segments(Branch me, Segpool pool)
         {
-            Point2F running_end = point(me.Curve.Points[me.Curve.Points.Count - 1].Point);
+            Point2F running_end = (Point2F)me.Curve.Points[me.Curve.Points.Count - 1].Point;
             List<Point2F> followers;

             while (true)


Added searching in the current directory for executable file.

The searching of path had a bug where the current directory was not
searched, this change searches the current directory before going down
the searching path.

--- sudo/PathHelpers.cs
+++ sudo/PathHelpers.cs
@@ -3,6 +3,7 @@
 using System.IO;
 using System.Linq;
 using Microsoft.Win32;
+using System.Reflection;

 namespace sudo
 {
@@ -147,7 +148,12 @@
             var path = Path.GetDirectoryName(arg);
             if (path != null && path == "")
             {
-                path = SearchPath("", arg, null, true);
+                var currentDirectory = new DirectoryInfo(Environment.CurrentDirectory);
+                if (currentDirectory.GetFiles(arg).Length == 0)
+                {
+                    path = SearchPath("", arg, null, true);
+                }
+                path = currentDirectory.FullName;
             }
             else
             {


Correção para assinatura do xml de envio no provedor ISSe

--- src/ACBr.Net.NFSe/Providers/ISSe/ProviderISSe.cs
+++ src/ACBr.Net.NFSe/Providers/ISSe/ProviderISSe.cs
@@ -47,6 +47,12 @@
         #region Methods

         #region Protected Methods
+
+        protected override void AssinarEnviarSincrono(RetornoEnviar retornoWebservice)
+        {
+            //retornoWebservice.XmlEnvio = XmlSigning.AssinarXmlTodos(retornoWebservice.XmlEnvio, "Rps", "", Certificado); -> nao tem assinatura no RPS para esse provider
+            retornoWebservice.XmlEnvio = DFe.Core.XmlSigning.AssinarXml(retornoWebservice.XmlEnvio, "EnviarLoteRpsSincronoEnvio", "LoteRps", Certificado);
+        }

         protected override IServiceClient GetClient(TipoUrl tipo)
         {
@@ -57,4 +63,4 @@

         #endregion Methods
     }
-}+}


update MemoryCache to use DateTimeOffset

--- src/Abp/Runtime/Caching/Memory/AbpMemoryCache.cs
+++ src/Abp/Runtime/Caching/Memory/AbpMemoryCache.cs
@@ -36,7 +36,7 @@

             if (absoluteExpireTime.HasValue)
             {
-                _memoryCache.Set(key, value, DateTimeOffset.Now.Add(absoluteExpireTime.Value));
+                _memoryCache.Set(key, value, absoluteExpireTime.Value);
             }
             else if (slidingExpireTime.HasValue)
             {
@@ -44,7 +44,7 @@
             }
             else if (DefaultAbsoluteExpireTime.HasValue)
             {
-                _memoryCache.Set(key, value, DateTimeOffset.Now.Add(DefaultAbsoluteExpireTime.Value));
+                _memoryCache.Set(key, value, DefaultAbsoluteExpireTime.Value);
             }
             else
             {


Center the dialog on the owner, rather than the screen

In some rare cases, high DPI and VS might cause dialogs to be centered off-screen.
To be safe, center on the owner window instead, which is always the visible IDE anyway,
so it's also more appropriate.

--- src/Clide.Core.Windows/UI/DialogWindowFactory.cs
+++ src/Clide.Core.Windows/UI/DialogWindowFactory.cs
@@ -52,7 +52,7 @@
                     await jtf.SwitchToMainThreadAsync();
                     ErrorHandler.ThrowOnFailure(uiShell.GetValue().GetDialogOwnerHwnd(out var owner));
                     new WindowInteropHelper(dialogWindow).Owner = owner;
-                    dialogWindow.WindowStartupLocation = WindowStartupLocation.CenterScreen;
+                    dialogWindow.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                     dialogWindow.ShowInTaskbar = false;
                 });

@@ -62,4 +62,4 @@
             return dialog;
         }
     }
-}+}


为修改表达式构建器增加对Interval类型递增运算的新特性。 :chart_with_upwards_trend:

--- src/Common/Expressions/UpdateStatementBuilder.cs
+++ src/Common/Expressions/UpdateStatementBuilder.cs
@@ -110,24 +110,31 @@
 				return;

 			//确认当前成员是否有必须的写入值
-			var required = context.TryGetProvidedValue(member.Token.Property, out var value);
+			var provided = context.TryGetProvidedValue(member.Token.Property, out var value);

 			//如果不是批量更新，并且当前成员没有改动则返回
-			if(!context.IsMultiple && !this.HasChanges(data, member.Name) && !required)
+			if(!context.IsMultiple && !this.HasChanges(data, member.Name) && !provided)
 				return;

 			if(member.Token.Property.IsSimplex)
 			{
 				//忽略不可变属性
-				if(member.Token.Property.Immutable && !required)
+				if(member.Token.Property.Immutable && !provided)
 					return;

 				var field = table.CreateField(member.Token);
-				var parameter = required ?
+				var parameter = provided ?
 					Expression.Parameter(ParameterExpression.Anonymous, field, member, value) :
 					Expression.Parameter(ParameterExpression.Anonymous, field, member);

-				statement.Fields.Add(new FieldValue(field, parameter));
+				if(!provided && !context.IsMultiple)
+					value = member.Token.GetValue(context.Data);
+
+				if(value is Interval interval)
+					statement.Fields.Add(new FieldValue(field, field.AddAssign(parameter)));
+				else
+					statement.Fields.Add(new FieldValue(field, parameter));
+
 				statement.Parameters.Add(parameter);
 			}
 			else


update no caixa

update no caixa

--- artesanatoCapixaba/Caixa.cs
+++ artesanatoCapixaba/Caixa.cs
@@ -242,6 +242,9 @@
                 relatorioItens.Cell(2 + aux, 3).Style.Font.SetBold(true);
                 /*--------------------------------------------------------------------------------------*/

+                leitor.Close();
+                con.Close();
+
                 workbook.SaveAs(saveFile.FileName.ToString() + ".xlsx");

                 Cursor.Current = Cursors.Default;


completed the initial coding of the server process.

--- aspNETserve.Ice/Service1.cs
+++ aspNETserve.Ice/Service1.cs
@@ -10,30 +10,88 @@
 using System.ComponentModel;
 using System.Data;
 using System.Diagnostics;
+using System.IO;
 using System.Net;
 using System.ServiceProcess;
 using System.Text;
+using System.Threading;
 using aspNETserve;
+using aspNETserve.Configuration;
+using aspNETserve.Configuration.Xml;

 namespace aspNETserve.Ice {
     public partial class Service1 : ServiceBase {
-        private IServer _server = new Server(IPAddress.Any, "/", @"C:\webroot", 8081);
+        private IList<IAsyncServer> _servers;
+        private const string _configFileName = "aspNETserve.config.xml";
+        private readonly FileSystemWatcher _fileWatcher;

         public Service1() {
             InitializeComponent();
+
+            //setup a file watcher that will cycle the applications
+            //in case of a configuration change.
+            _fileWatcher = new FileSystemWatcher(_configFileName);
+            _fileWatcher.Changed += delegate { CycleServer(); };
         }

         protected override void OnStart(string[] args) {
-            _server.Start();
+            Configure();
+            foreach (IAsyncServer server in _servers)
+                server.StartAsync();
         }

         protected override void OnStop() {
-            _server.Stop();
+            foreach (IAsyncServer server in _servers)
+                server.StopAsync();
+
+
+            //since we want this thread to block until all the servers have stopped or
+            //errored out then we need to wait. The reason we did async in the first place
+            //was to speed up the shutdown process by allowing all the servers to shutdown
+            //at the same time.
+
+            bool waiting;
+            do {
+                waiting = false;    //We reset this at the top of each loop, otherwise we would never exit.
+
+                foreach (IAsyncServer server in _servers) { //so look at each IAsyncServer
+                    if(server.Status == ServerStatus.ShuttingDown) {
+                        //and if the status is "ShuttingDown" then that means we need to keep waiting.
+                        waiting = true;
+                        break;
+                    }
+                }
+                Thread.Sleep(300);  //Sleep a little to give other threads time to work
+            } while (waiting);
+
+            //At this point we know that none of the servers in shutting down.
+            //What we don't know is what status they are in. But for now we
+            //simply won't concern ourselfs, and assume they have stopped.
         }

-        protected void CycleServer() {
+        private void CycleServer() {
             OnStop();
             OnStart(null);
         }
+
+        private void Configure() {
+            if(_servers != null) {  //if the collection of servers exists then...
+                foreach(IAsyncServer server in _servers) {
+                    server.Dispose();   //...just make sure to call dipose on each server object.
+                }
+            }
+
+            _servers = new List<IAsyncServer>(); //construct a new collection of servers
+
+            using (FileStream configFile = File.OpenRead(_configFileName)) {
+                //using the configuration file, read the application config elements...
+
+                IConfiguration config = XmlConfigurationManager.FromXml(configFile);
+                foreach(IApplication application in config.Applications) {
+                    IAsyncServer server = new AsyncServer(application); //... to construct each server.
+                    _servers.Add(server);   //...and add it to the collection.
+                }
+            }
+        }
     }
 }


(DxLib): guess key of version 6 archives.

--- ArcFormats/DxLib/ArcDX.cs
+++ ArcFormats/DxLib/ArcDX.cs
@@ -2,7 +2,7 @@
 //! \date       Thu Oct 08 00:18:56 2015
 //! \brief      DxLib engine archives with 'DX' signature.
 //
-// Copyright (C) 2015-2017 by morkt
+// Copyright (C) 2015-2018 by morkt
 //
 // Permission is hereby granted, free of charge, to any person obtaining a copy
 // of this software and associated documentation files (the "Software"), to
@@ -64,9 +64,10 @@

         public DxOpener ()
         {
-            Extensions = new string[] { "dxa", "hud", "usi", "med", "dat", "bin", "bcx" };
+            Extensions = new string[] { "dxa", "hud", "usi", "med", "dat", "bin", "bcx", "wolf" };
             Signatures = new uint[] {
-                0x19EF8ED4, 0xA9FCCEDD, 0x0AEE0FD3, 0x5523F211, 0x5524F211, 0x69FC5FE4, 0x09E19ED9, 0
+                0x19EF8ED4, 0xA9FCCEDD, 0x0AEE0FD3, 0x5523F211, 0x5524F211, 0x69FC5FE4, 0x09E19ED9, 0x7DCC5D83,
+                0
             };
         }

@@ -100,14 +101,27 @@
                     return null;
                 }
             }
-            return GuessKey (file);
-        }
-
-        ArcFile GuessKey (ArcView file)
+            var arc = GuessKey (file);
+            if (arc != null)
+            {
+                KnownKeys.Insert (0, arc.Key);
+                Trace.WriteLine (string.Format ("Restored key '{0}'", RestoreKey (arc.Key)), "[DXA]");
+            }
+            return arc;
+        }
+
+        DxArchive GuessKey (ArcView file)
         {
             if (file.MaxOffset > uint.MaxValue)
                 return null;
-            var key = new byte[12];
+            var key = GuessKeyV6 (file);
+            if (key != null)
+            {
+                var dir = ReadIndex (file, 6, key);
+                if (dir != null)
+                    return new DxArchive (file, this, dir, key, 6);
+            }
+            key = new byte[12];
             for (short version = 4; version >= 1; --version)
             {
                 file.View.Read (0, key, 0, 12);
@@ -130,15 +144,34 @@
                 {
                     var dir = ReadIndex (file, version, key);
                     if (null != dir)
-                    {
-                        KnownKeys.Insert (0, key);
-                        Trace.WriteLine (string.Format ("Restored key '{0}'", RestoreKey (key)), "[DXA]");
                         return new DxArchive (file, this, dir, key, version);
-                    }
                 }
                 catch { /* ignore parse errors */ }
             }
             return null;
+        }
+
+        byte[] GuessKeyV6 (ArcView file)
+        {
+            var header = file.View.ReadBytes (0, 0x30);
+            header[0] ^= (byte)'D';
+            header[1] ^= (byte)'X';
+            header[2] ^= 6;
+            uint key0 = header.ToUInt32 (0);
+            header[8] ^= (byte)0x30;
+            uint data_offset_hi = header.ToUInt32 (12) ^ key0;
+            if (data_offset_hi != 0)
+                return null;
+            uint key2 = header.ToUInt32 (8);
+            uint key1 = header.ToUInt32 (0x1C);
+            long index_offset = header.ToInt64 (0x10) ^ key1 ^ ((long)key2 << 32);
+            if (index_offset <= 0x30 || index_offset >= file.MaxOffset)
+                return null;
+            var key = new byte[12];
+            LittleEndian.Pack (key0, key, 0);
+            LittleEndian.Pack (key1, key, 4);
+            LittleEndian.Pack (key2, key, 8);
+            return key;
         }

         public override Stream OpenEntry (ArcFile arc, Entry entry)


Set MaxItemsPerTrade correctly, closes #81

--- ArchiSteamFarm/Trading.cs
+++ ArchiSteamFarm/Trading.cs
@@ -28,7 +28,7 @@

 namespace ArchiSteamFarm {
 	internal sealed class Trading {
-		internal const ushort MaxItemsPerTrade = 100; // TODO: This should be corrected later, https://github.com/JustArchi/ArchiSteamFarm/issues/81
+		internal const ushort MaxItemsPerTrade = 150;

 		private readonly Bot Bot;
 		private readonly SemaphoreSlim Semaphore = new SemaphoreSlim(1);


Added hearts and love

Added hearts and love


Add the usage of the .net linked list as an example for comparison in the outcomes

--- AlgorithmsAndDataStructures/AlgorithmsAndDataStructures/Program.cs
+++ AlgorithmsAndDataStructures/AlgorithmsAndDataStructures/Program.cs
@@ -7,7 +7,16 @@
     {
         static void Main(string[] args)
         {
-
+            // AT FIRST USE THE .NET FRAMEWORK LINKEDLIST CLASS
+            System.Collections.Generic.LinkedList<int> list = new System.Collections.Generic.LinkedList<int>();
+            list.AddLast(3);
+            list.AddLast(5);
+            list.AddLast(7);
+
+            foreach (var value in list)
+            {
+                Console.WriteLine(value);
+            }

             // +-----+------+
             // |  3  | null +


Updated controller struct. (#2182)

Updated controller struct. (#2182)

--- Assets/MixedRealityToolkit/_Core/Definitions/Devices/Controller.cs
+++ Assets/MixedRealityToolkit/_Core/Definitions/Devices/Controller.cs
@@ -1,7 +1,6 @@
 // Copyright (c) Microsoft Corporation. All rights reserved.
 // Licensed under the MIT License. See LICENSE in the project root for license information.

-using Microsoft.MixedReality.Toolkit.Internal.Definitions.InputSystem;
 using UnityEngine;

 namespace Microsoft.MixedReality.Toolkit.Internal.Definitions.Devices
@@ -11,34 +10,45 @@
     /// </summary>
     public struct Controller
     {
+        public Controller(uint id, Handedness handedness, Vector3 position, Quaternion rotation, ControllerState controllerState, InteractionDefinition[] interactions) : this()
+        {
+            Id = id;
+            Handedness = handedness;
+            Position = position;
+            Rotation = rotation;
+            ControllerState = controllerState;
+            Interactions = interactions;
+        }
+
+
         /// <summary>
-        /// The ID assigned to the Controller
+        /// The ID assigned to the Controller.
         /// </summary>
-        public string Id { get; set; }
+        public uint Id { get; }

         /// <summary>
         /// The designated hand that the controller is managing, as defined by the SDK / Unity.
         /// </summary>
-        public Handedness Handedness { get; set; }
+        public Handedness Handedness { get; }

         /// <summary>
         /// Outputs the current position of the controller, as defined by the SDK / Unity.
         /// </summary>
-        public Vector3 Position { get; set; }
+        public Vector3 Position { get; }

         /// <summary>
         /// Outputs the current rotation of the controller, as defined by the SDK / Unity.
         /// </summary>
-        public Quaternion Rotation { get; set; }
+        public Quaternion Rotation { get; }

         /// <summary>
         /// Outputs the current state of the controller, whether it is tracked or not. As defined by the SDK / Unity.
         /// </summary>
-        public ControllerState ControllerState { get; set; }
+        public ControllerState ControllerState { get; }

         /// <summary>
         /// Details the list of available buttons / interactions available from the controller.
         /// </summary>
-        public InteractionDefinition[] Interactions { get; set; }
+        public InteractionDefinition[] Interactions { get; }
     }
 }


Reorder parameters of previously wrongly refactored string interpolation

--- Duplicati/Library/Backend/Rclone/Rclone.cs
+++ Duplicati/Library/Backend/Rclone/Rclone.cs
@@ -249,7 +249,7 @@
         {
             try
             {
-                RcloneCommandExecuter(rclone_executable, $"copyto {local_repo}:{filename} {remote_repo}:{Path.Combine(this.remote_path, remotename)}", CancellationToken.None).Await();
+                RcloneCommandExecuter(rclone_executable, $"copyto {remote_repo}:{Path.Combine(this.remote_path, remotename)} {local_repo}:{filename}", CancellationToken.None).Await();
             }
             catch (FolderMissingException ex) {
                 throw new FileMissingException(ex);


Synchronize with current version of BadgerJAUS.

--- BadgerControlModule/ViewModels/BadgerRobotsInformationViewModel.cs
+++ BadgerControlModule/ViewModels/BadgerRobotsInformationViewModel.cs
@@ -46,7 +46,7 @@

         public IEnumerable<Node> CurrentNodes
         {
-            get { return selectedSubsystem.NodeList.Values; }
+            get { return selectedSubsystem.NodeList; }
         }

         public ICommand Refresh


Changed WEBDAV to send an empty body with a PROPFIND request.
Fixed issue #217.

git-svn-id: bf0bd98e94caaaf89d4dca54eab1bef459ce3438@426 59da171f-624f-0410-aa54-27559c288bec

--- Duplicati/Library/Backend/WEBDAV/WEBDAV.cs
+++ Duplicati/Library/Backend/WEBDAV/WEBDAV.cs
@@ -43,7 +43,12 @@
         /// </summary>
         private List<string> m_filenamelist = null;

-        private static readonly byte[] PROPFIND = System.Text.Encoding.UTF8.GetBytes("<?xml version=\"1.0\"?><D:propfind xmlns:D=\"DAV:\"><D:allprop/></D:propfind>");
+        // According to the WEBDAV standard, the "allprop" request should return all properties, however this seems to fail on some servers (box.net).
+        // I've found this description: http://www.webdav.org/specs/rfc2518.html#METHOD_PROPFIND
+        //  "An empty PROPFIND request body MUST be treated as a request for the names and values of all properties."
+        //
+        //private static readonly byte[] PROPFIND_BODY = System.Text.Encoding.UTF8.GetBytes("<?xml version=\"1.0\"?><D:propfind xmlns:D=\"DAV:\"><D:allprop/></D:propfind>");
+        private static readonly byte[] PROPFIND_BODY = new byte[0];

         public WEBDAV()
         {
@@ -120,10 +125,10 @@
                 req.Method = "PROPFIND";
                 req.Headers.Add("Depth", "1");
                 req.ContentType = "text/xml";
-                req.ContentLength = PROPFIND.Length;
+                req.ContentLength = PROPFIND_BODY.Length;

                 using (System.IO.Stream s = req.GetRequestStream())
-                    s.Write(PROPFIND, 0, PROPFIND.Length);
+                    s.Write(PROPFIND_BODY, 0, PROPFIND_BODY.Length);

                 try
                 {


Just make it a normal label

Just make it a normal label

--- Battery-Commander.Web/Views/Shared/DisplayTemplates/Soldier.cshtml
+++ Battery-Commander.Web/Views/Shared/DisplayTemplates/Soldier.cshtml
@@ -4,7 +4,7 @@
 {
     if(String.Equals("Unknown", Model.LastName, StringComparison.CurrentCultureIgnoreCase))
     {
-        Unknown
+        Unknown
         return;
     }


attempt to take shared elements into account into the query

--- EAAddinFramework/SchemaBuilder/EASchema.cs
+++ EAAddinFramework/SchemaBuilder/EASchema.cs
@@ -917,8 +917,12 @@
                                 and c.Start_Object_ID in ({subsetElementIDs})
                                 and oo.ea_guid in ({schemaSourceElementGuids})";
             }
+            //get the dictionary based on the query
+            var subsetDictionary = this.model.getDictionaryFromQuery(sqlGetData);
+            //for all shared subsetElements, we add an entry with the same GUID as these are both subset element as sourceElement
+
             //return dictionary based on query
-            return this.model.getDictionaryFromQuery(sqlGetData);
+            return subsetDictionary;
         }

         void matchSubsetElements(Package destinationPackage, HashSet<Classifier> subsetElements)
@@ -1061,8 +1065,8 @@
             allElementIDs.AddRange(parentElementIDs);
             var parentIDString = String.Join(",", parentElementIDs);
             var allElementIDString = String.Join(",", allElementIDs);
-            var sqlGetData = $@"select o.Object_ID from  (
-                    select o.Object_ID from ((t_object o
+            var sqlGetData = $@"select o.Object_ID from (
+                    select o.Object_ID, o.Package_ID  from ((t_object o
                     inner join t_connector c on (o.Object_ID = c.End_Object_ID
                                                 and c.Connector_Type in ('Aggregation', 'Association')))
                     inner join t_object oo on (oo.Object_ID = c.Start_Object_ID
@@ -1071,7 +1075,7 @@
                     and oo.Object_ID in ({parentIDString})
                     and o.Object_ID not in ({allElementIDString})
                     union
-                    select o.Object_ID from ((t_object o
+                    select o.Object_ID, o.Package_ID from ((t_object o
                     inner join t_attribute a on a.Classifier = o.Object_ID)
                     inner join t_object oo on oo.Object_ID = a.Object_ID)
                     where o.Object_Type in ('Class', 'Enumeration', 'DataType', 'PrimitiveType')
@@ -1087,16 +1091,44 @@
 					where tv.Object_ID = o.Object_ID
 							and tv.Property = '{this.settings.elementTagName}'
 							and tv.Value in ({this.elementGUIDstring})
+					union
+					select tv.ea_guid
+					from (( t_objectproperties tv
+					inner join t_object po on po.Object_ID = tv.Object_ID)
+					inner join t_package p on p.ea_guid = po.ea_guid
+											and o.Package_ID = p.Package_ID)
+					where tv.Property = 'shared'
+					and tv.Value = 'true'
+					union
+					select tv.ea_guid
+					from t_objectproperties tv
+					where tv.Object_ID = o.Object_ID
+					and tv.Property = 'shared'
+					and tv.Value = 'true'
 					)";
             }
             else
             {
                 sqlGetData += Environment.NewLine +
-                    $@"(select * from t_connector tr
+                    $@"(select tr.ea_guid from t_connector tr
 					inner join t_object oso on oso.Object_ID = tr.End_Object_ID
 									and oso.ea_guid in ({this.elementGUIDstring})
 					where tr.Stereotype = 'trace'
 					and tr.Start_Object_ID = o.Object_ID
+					union
+					select tv.ea_guid
+					from (( t_objectproperties tv
+					inner join t_object po on po.Object_ID = tv.Object_ID)
+					inner join t_package p on p.ea_guid = po.ea_guid
+											and o.Package_ID = p.Package_ID)
+					where tv.Property = 'shared'
+					and tv.Value = 'true'
+					union
+					select tv.ea_guid
+					from t_objectproperties tv
+					where tv.Object_ID = o.Object_ID
+					and tv.Property = 'shared'
+					and tv.Value = 'true'
 					)";
             }
             var relatedElementIDs = this.model.getListFromQuery(sqlGetData);


remove timestamp

remove timestamp


Add examples

Add examples

--- Examples/Ranges.Examples/RangesExamples.cs
+++ Examples/Ranges.Examples/RangesExamples.cs
@@ -84,11 +84,17 @@
             Range<int> intRange = Range.Ints(10);
             Console.WriteLine($"Integer Range: {intRange}");

-            intRange = intRange.Transform((i) => i * 2);
+            intRange = intRange.Transform(Range.MultiplyBy(2));
             Console.WriteLine($"Integer Range (each element multiplied by 2): {intRange}");

-            intRange |= (i) => i + 2;
+            intRange |= Range.MultiplyBy(4);
+            Console.WriteLine($"Integer Range (each element multiplied by 4): {intRange}");
+
+            intRange = intRange.Transform((i) => i + 2);
             Console.WriteLine($"Integer Range (each element incremented by 2): {intRange}");
+
+            intRange |= (i) => i + 4;
+            Console.WriteLine($"Integer Range (each element incremented by 4): {intRange}");
         }

         internal static void RangeFilter()
@@ -100,11 +106,19 @@
             Range<int> intRange = Range.Ints(10);
             Console.WriteLine($"Integer Range: {intRange}");

-            intRange = intRange.Filter((i) => i % 2 == 0);
+            intRange = intRange.Filter(Range.IsEven());
             Console.WriteLine($"Integer Range (only even numbers): {intRange}");

             intRange |= (i) => i % 4 == 0;
             Console.WriteLine($"Integer Range (only numbers divisible by 4): {intRange}");
+
+            Console.WriteLine("--------------------------------------");
+
+            intRange = Range.Ints(10);
+            Console.WriteLine($"Integer Range: {intRange}");
+
+            intRange |= Range.IsEven();
+            Console.WriteLine($"Integer Range (only even numbers): {intRange}");
         }
     }
 }