Example #1
0
        /// <summary>
        /// Zadeh Max Min Implication Operator
        /// </summary>
        /// <param name="elementA">FuzzyElement A</param>
        /// <param name="elementB">FuzzyElement B</param>
        /// <returns>FuzzyElement</returns>
        public static IFuzzyElement ZadehMaxMinImplication(this IFuzzyElement elementA, IFuzzyElement elementB)
        {
            var fuzzy = elementA.Clone();
            fuzzy.Value = elementA.Min(elementB).Max(elementA.Clone(x => x.Value = 1 - elementA.Value)).Value;

            return fuzzy;
        }
Example #2
0
        public static List<NimState> GetPossibleStates(this NimState state)
        {
            List<NimState> states = new List<NimState>();

            for (int i = 1; i <= state.XReal; i++) {

                NimState tempState = state.Clone();
                tempState.XReal -= i;
                if (tempState.HasValidMoves())
                    states.Add(tempState);
            }

            for (int i = 1; i <= state.YReal; i++) {

                NimState tempState = state.Clone();
                tempState.YReal -= i;
                if (tempState.HasValidMoves())
                    states.Add(tempState);
            }

            for (int i = 1; i <= state.ZReal; i++) {

                NimState tempState = state.Clone();
                tempState.ZReal -= i;
                if (tempState.HasValidMoves())
                    states.Add(tempState);
            }

            return states;
        }
Example #3
0
        public static Bitmap CropWhitespace(this Bitmap bmp)
        {
            int bitPerPixel = Image.GetPixelFormatSize(bmp.PixelFormat);

            if(bitPerPixel != 24 && bitPerPixel != 32)
                throw new InvalidOperationException($"Invalid PixelFormat: {bitPerPixel}b");

            var bottom = 0;
            var left = bmp.Width;
            var right = 0;
            var top = bmp.Height;

            BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, bmp.PixelFormat);
            unsafe
            {
                byte* dataPtr = (byte*)bmpData.Scan0;

                for(var y = 0; y < bmp.Height; y++) {
                    for(var x = 0; x < bmp.Width; x++) {
                        var rgbPtr = dataPtr + (x * (bitPerPixel / 8));

                        var b = rgbPtr[0];
                        var g = rgbPtr[1];
                        var r = rgbPtr[2];

                        byte? a = null;
                        if(bitPerPixel == 32) {
                            a = rgbPtr[3];
                        }

                        if(b != 0xFF || g != 0xFF || r != 0xFF || (a.HasValue && a.Value != 0xFF)) {
                            if(x < left)
                                left = x;

                            if(x >= right)
                                right = x + 1;

                            if(y < top)
                                top = y;

                            if(y >= bottom)
                                bottom = y + 1;
                        }
                    }

                    dataPtr += bmpData.Stride;
                }
            }
            bmp.UnlockBits(bmpData);

            if(left < right && top < bottom) {
                var width = right - left;
                var height = bottom - top;

                var croppedImg = bmp.Clone(new Rectangle(left, top, width, height), bmp.PixelFormat);
                return croppedImg;
            } else {
                return bmp; // Entire image should be cropped, it is empty
            }
        }
Example #4
0
        /// <summary>
        /// 行列の LU 分解をおこないます。
        /// 対角要素を除く下三角の要素が行列 L (対角要素はすべて 1), 上三角の要素が行列 U を表す行列を返します。
        /// </summary>
        /// <param name="A">対象とする行列</param>
        /// <returns>対角要素を除く下三角の要素が行列 L (対角要素はすべて 1), 上三角の要素が行列 U を表す行列を返します。</returns>
        public static Matrix LUDecomposition(this Matrix A)
        {
            if ((A.Rows == 0) || (A.Columns == 0) || (A.Rows != A.Columns))
                throw new Exception("LU 分解できません。");

            var mat = A.Clone();
            var n = mat.Rows;

            for (int k = 0; k < n; k++)
            {
                var temp = 1.0 / mat[k, k];
                for (int i = k + 1; i < n; i++)
                {
                    mat[i, k] = mat[i, k] * temp;
                }

                for (int j = k + 1; j < n; j++)
                {
                    var Akj = mat[k, j];
                    for (int i = k + 1; i < n; i++)
                    {
                        mat[i, j] -= mat[i, k] * Akj;
                    }
                }
            }

            return mat;
        }
 public static Bitmap Correlation(this Bitmap input, byte[,] mask, int maskWidth, int maskHeight)
 {
     Bitmap clone = input.Clone() as Bitmap;
     int total = 0;
     int a = (maskWidth - 1) >> 1;
     int b = (maskHeight - 1) >> 1;
     for(int x = 0; x < input.Width; x++)
     {
         for(int y = 0; y < input.Height; y++)
         {
             for(int s = 0, _s = -a; s < maskWidth; s++, _s++)
             {
                 int wX = x + _s;
                 if(wX < 0 || wX >= input.Width)
                     continue;
                 for(int t = 0, _t = -b; t < maskHeight; t++, _t++)
                 {
                     int wY = y + _t;
                     if(wY < 0 || wY >= input.Height)
                         continue;
                     int w = mask[s, t];
                     int f = input.GetPixel(wX, wY).R;
                     total += (w * f);
                 }
             }
             byte value = (byte)total;
             clone.SetPixel(x,y, Color.FromArgb(255, value, value, value));
             total = 0;
         }
     }
     return clone;
 }
Example #6
0
        /// <summary>
        /// Resizes the specified image.
        /// </summary>
        /// <param name="image">The image.</param>
        /// <param name="size">The size.</param>
        /// <returns></returns>
        public static Image Resize(this Image image, Size size)
        {
            Size newSize = new Size(size.Width, size.Height);

            if (image.Size.Width > image.Size.Height)
            {
                newSize.Height = (image.Size.Height * size.Width) / image.Size.Width;
            }
            else
            {
                newSize.Width = (image.Size.Width * size.Height) / image.Size.Height;
            }

            Rectangle   rectangle   = new Rectangle(0, 0, newSize.Width, newSize.Height);
            Image       resized     = new Bitmap(newSize.Width, newSize.Height, image.PixelFormat);

            using (Graphics graphic = Graphics.FromImage(resized))
            {
                graphic.CompositingQuality  = CompositingQuality.HighQuality;
                graphic.SmoothingMode       = SmoothingMode.HighQuality;
                graphic.InterpolationMode   = InterpolationMode.HighQualityBicubic;

                graphic.DrawImage((System.Drawing.Image)image.Clone(), rectangle);
            }

            return resized;
        }
        /// <summary>
        /// This is used to get the inner XML of a node without changing the spacing
        /// </summary>
        /// <param name="node">The node from which to get the inner XML</param>
        /// <returns>The inner XML as a string with its spacing preserved</returns>
        /// <exception cref="ArgumentNullException">This is thrown if the <paramref name="node"/> parameter
        /// is null.</exception>
        public static string GetInnerXml(this XPathNavigator node)
        {
            if(node == null)
                throw new ArgumentNullException("node");

            // Clone the node so that we don't change the input
            XPathNavigator current = node.Clone();

            XmlWriterSettings settings = new XmlWriterSettings();
            settings.ConformanceLevel = ConformanceLevel.Fragment;
            settings.OmitXmlDeclaration = true;

            StringBuilder builder = new StringBuilder();

            using(XmlWriter writer = XmlWriter.Create(builder, settings))
            {
                // write the output
                bool writing = current.MoveToFirstChild();

                while(writing)
                {
                    current.WriteSubtree(writer);
                    writing = current.MoveToNext();
                }
            }

            return builder.ToString();
        }
Example #8
0
		public static XPathNavigator GetParent(this XPathNavigator navigator)
		{
			navigator = navigator.Clone();
			if (!navigator.MoveToParent())
				throw Error.InvalidOperation();
			return navigator;
		}
Example #9
0
        internal static Image RGBToBGR(this Image bmp)
        {
            Image newBmp;
            if ((bmp.PixelFormat & Imaging.PixelFormat.Indexed) != 0)
            {
                newBmp = new Bitmap(bmp.Width, bmp.Height, Imaging.PixelFormat.Format32bppArgb);
            }
            else
            {
                // Need to clone so the call to Clear() below doesn't clear the source before trying to draw it to the target.
                newBmp = (Image)bmp.Clone();
            }

            try
            {
                System.Drawing.Imaging.ImageAttributes ia = new System.Drawing.Imaging.ImageAttributes();
                System.Drawing.Imaging.ColorMatrix cm = new System.Drawing.Imaging.ColorMatrix(rgbtobgr);

                ia.SetColorMatrix(cm);
                using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(newBmp))
                {
                    g.Clear(Color.Transparent);
                    g.DrawImage(bmp, new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height), 0, 0, bmp.Width, bmp.Height, System.Drawing.GraphicsUnit.Pixel, ia);
                }
            }
            finally
            {
                if (newBmp != bmp)
                {
                    bmp.Dispose();
                }
            }

            return newBmp;
        }
 public static Style AlignTopRight(this Style style)
 {
     return style
             .Clone ()
             .Set (Label.YAlignProperty, TextAlignment.Start)
             .Set (Label.XAlignProperty, TextAlignment.End);
 }
 public static Style AlignCenterLeft(this Style style)
 {
     return style
             .Clone ()
             .Set (Label.YAlignProperty, TextAlignment.Center)
             .Set (Label.XAlignProperty, TextAlignment.Start);
 }
 public static Style AlignBottomLeft(this Style style)
 {
     return style
             .Clone ()
             .Set (Label.YAlignProperty, TextAlignment.End)
             .Set (Label.XAlignProperty, TextAlignment.Start);
 }
 public static Style AlignBottomCenter(this Style style)
 {
     return style
             .Clone ()
             .Set (Label.YAlignProperty, TextAlignment.End)
             .Set (Label.XAlignProperty, TextAlignment.Center);
 }
 public static BrokeredMessage CloneWithMessageId(this BrokeredMessage toSend)
 {
     var clone = toSend.Clone();
     clone.MessageId = toSend.MessageId;
     toSend = clone;
     return toSend;
 }
Example #15
0
 /// <summary>
 /// REplaces the current where clause with the passed clause
 /// </summary>
 /// <param name="queryBuilder"></param>
 /// <param name="where"></param>
 /// <returns></returns>
 public static IQueryBuilder WhereAll(this IQueryBuilder queryBuilder, IWhere where)
 {
     var qb = queryBuilder.Clone();
     qb.QueryDef.Where.Clear();
     qb.QueryDef.Where.Add(where);
     return qb;
 }
Example #16
0
        public static void MoveUp(this TreeNode node)
        {            
            TreeNode parent = node.Parent;            
            TreeView treeview = node.TreeView;

            int orindex = node.Index;
            
            TreeNode tr = (TreeNode)node.Clone();
            
            if (node.Index == 0)
            {
                if (parent != null)
                    node.Remove();
                else
                    return;
                                
                if (parent.Parent == null)
                    treeview.Nodes.Insert(treeview.Nodes.Count - 1, tr);
                else
                    parent.Parent.Nodes.Insert(parent.Parent.Nodes.Count, tr);
            }
            else
            {
                node.Remove();
                if (parent != null)
                    parent.Nodes.Insert(orindex - 1, tr);
                else
                    treeview.Nodes.Insert(orindex - 1, tr);
            }

            treeview.SelectedNode = tr;            
        }
        /// <summary>
        ///     对DataTable分页
        /// </summary>
        /// <param name="dt">源表</param>
        /// <param name="pageSize">每页显示的记录数</param>
        /// <param name="pageIndex">页码</param>
        /// <returns></returns>
        public static DataTable Split(this DataTable dt, int pageSize = 20, int pageIndex = 1)
        {
            if (pageIndex < 1) { pageIndex = 1; }
            if (pageSize < 1) { pageSize = 1; }
            var dtNew = dt.Clone();

            int firstIndex;

            #region 计算 开始索引

            if (pageIndex == 1) { firstIndex = 0; }
            else
            {
                firstIndex = pageSize * (pageIndex - 1);
                //索引超出记录总数时,返回空的表格
                if (firstIndex > dt.Rows.Count) { return dtNew; }
            }

            #endregion

            #region 计算 结束索引

            var endIndex = pageSize + firstIndex;
            if (endIndex > dt.Rows.Count) { endIndex = dt.Rows.Count; }

            #endregion

            for (var i = firstIndex; i < endIndex; i++) { dtNew.ImportRow(dt.Rows[i]); }
            return dtNew;
        }
        // Perturb an orbit by a deltaV vector
        public static void Perturb(this Orbit orbit, Vector3d deltaVV, double universalTime, double deltaTime)
        {
            // If there is a deltaV, perturb orbit
            if (deltaVV.magnitude <= 0) return;

            // Transpose deltaVV Y and Z to match orbit frame
            Vector3d deltaVV_orbit = deltaVV.xzy;
            Vector3d position = orbit.getRelativePositionAtUT(universalTime);
            Orbit orbit2 = orbit.Clone();
            orbit2.UpdateFromStateVectors(position, orbit.getOrbitalVelocityAtUT(universalTime) + deltaVV_orbit, orbit.referenceBody, universalTime);
            if (!double.IsNaN(orbit2.inclination) && !double.IsNaN(orbit2.eccentricity) && !double.IsNaN(orbit2.semiMajorAxis) && orbit2.timeToAp > deltaTime)
            {
                orbit.inclination = orbit2.inclination;
                orbit.eccentricity = orbit2.eccentricity;
                orbit.semiMajorAxis = orbit2.semiMajorAxis;
                orbit.LAN = orbit2.LAN;
                orbit.argumentOfPeriapsis = orbit2.argumentOfPeriapsis;
                orbit.meanAnomalyAtEpoch = orbit2.meanAnomalyAtEpoch;
                orbit.epoch = orbit2.epoch;
                orbit.referenceBody = orbit2.referenceBody;
                orbit.Init();
                orbit.UpdateFromUT(universalTime);
            }
            else
            {
                orbit.UpdateFromStateVectors(position, orbit.getOrbitalVelocityAtUT(universalTime) + deltaVV_orbit, orbit.referenceBody, universalTime);
                orbit.Init();
                orbit.UpdateFromUT(universalTime);
            }
        }
Example #19
0
        /// <summary>
        /// add Gaussian noise to bitmap, RGB respectively
        /// </summary>
        /// <param name="b"></param>
        /// <param name="mean"></param>
        /// <param name="deviation"></param>
        /// <returns></returns>
        public static unsafe Bitmap GaussianNoiseRGB(this Bitmap b, double mean, double deviation)
        {
            b = b.Clone() as Bitmap;
            BitmapData data = b.LockBits(new Rectangle(0, 0, b.Width, b.Height), ImageLockMode.ReadWrite
                , PixelFormat.Format24bppRgb);
            int width = b.Width, height = b.Height, stride = data.Stride;
            int x, y;
            double noise, re;
            byte* p = (byte*)data.Scan0, p0;
            for (y = 0; y < height; y++)
            {
                p0 = p + y * stride;
                for (x = 0; x < stride; x++)
                {
                    noise = GaussRandom(mean, deviation);

                    re = *p0 + noise;
                    re = (re > 255) ? 255 : re;
                    re = (re < 0) ? 0 : re;
                    *p0 = (byte)re;

                    p0++;
                }
            }
            b.UnlockBits(data);
            return b;
        }
Example #20
0
 public static DataTable SelectNewTable(this DataTable src, string cond, string sort)
 {
     DataRow[] rows = src.Select(cond, sort);
     DataTable res = src.Clone();
     foreach (DataRow row in rows) res.ImportRow(row);
     return res;
 }
Example #21
0
        /// <summary>
        /// Larsen Product Implication Operator
        /// </summary>
        /// <param name="elementA">FuzzyElement A</param>
        /// <param name="elementB">FuzzyElement B</param>
        /// <returns>FuzzyElement</returns>
        public static IFuzzyElement LarsenProductImplication(this IFuzzyElement elementA, IFuzzyElement elementB)
        {
            var fuzzy = elementA.Clone();
            fuzzy.Value = elementA.Value * elementB.Value;

            return fuzzy;
        }
Example #22
0
        public static Image KaMagnify(
            this Image self,
            int rate,
            InterpolationMode im = InterpolationMode.Default)
        {
            if ( !self.KaIs() )
            {
                return null;
            }

            var src = self.Clone() as Image;
            var w = src.Width * rate;
            var h = src.Height * rate;

            var res = new Bitmap( w, h );

            Graphics g = null;
            using ( g = Graphics.FromImage( res ) )
            {
                g.InterpolationMode = im;
                g.DrawImage( src, 0, 0, w, h );
            }

            return res;
        }
Example #23
0
        /// <summary>
        /// Mamdani Min Implication Operator
        /// </summary>
        /// <param name="elementA">FuzzyElement A</param>
        /// <param name="elementB">FuzzyElement B</param>
        /// <returns>FuzzyElement</returns>
        public static IFuzzyElement MamdaniMinImplication(this IFuzzyElement elementA, IFuzzyElement elementB)
        {
            var fuzzy = elementA.Clone();
            fuzzy.Value = elementA.Min(elementB).Value;

            return fuzzy;
        }
        private static GlueProjectSave ConvertToPartial(this GlueProjectSave glueProjectSave, string tag)
        {
            GlueProjectSave returnValue;
            if (tag == "GLUE")
            {
                //Remove other elements
                returnValue = glueProjectSave.Clone();

                //Entities
                returnValue.Entities.RemoveAll(t => !t.Tags.Contains(tag) && t.Tags.Count != 0);

                //Screens
                returnValue.Screens.RemoveAll(t => !t.Tags.Contains(tag) && t.Tags.Count != 0);
            }
            else
            {
                returnValue = new GlueProjectSave();

                //Entities
                returnValue.Entities.RemoveAll(t => !t.Tags.Contains(tag));

                //Screens
                returnValue.Screens.RemoveAll(t => !t.Tags.Contains(tag));
            }

            return returnValue;


        }
        /// <summary>
        /// Tries to build areas of similar coloured connected pixels
        /// (this Function assumes a grayscale image as imput(
        /// </summary>
        /// <param name="buffer"></param>
        /// <returns></returns>
        public static ImageBuffer CreepArea(this ImageBuffer buffer)
        {
            byte[] source = buffer.Bytes;

            ImageBuffer output = buffer.Clone();
            byte[] target = output.Bytes;

            for (int y = 0 ; y < output.Height - 1 ; y++)
            {
                for (int x = 1 ; x < output.Width - 1 ; x++)
                {
                    int ix = y * output.Stride + x * 4;

                    if (ix % 2 == 0)
                    {
                        int il = ix - 4;
                        ImageCreep.AverageOut(target, ix, il);
                    }
                    else
                    {
                        int ir = ix + 4;
                        ImageCreep.AverageOut(target, ix, ir);
                    }
                    
                    int id = (y + 1) * output.Stride + x * 4;

                    ImageCreep.AverageOut(target, ix, id);


                }
            }

            return output;
        }
Example #26
0
        public static ContentItem CloneForVersioningRecursive(this ContentItem item, StateChanger stateChanger = null, bool asPreviousVersion = true)
        {
            ContentItem clone = item.Clone(false);
            if (stateChanger != null)
            {
                if (item.State == ContentState.Published && asPreviousVersion)
                    stateChanger.ChangeTo(clone, ContentState.Unpublished);
                else if (item.State != ContentState.Unpublished || asPreviousVersion == false)
                    stateChanger.ChangeTo(clone, ContentState.Draft);
            }
            clone.Updated = Utility.CurrentTime().AddSeconds(-1);
            clone.Parent = null;
            clone.AncestralTrail = "/";
            clone.VersionOf = item.VersionOf.Value ?? item;

            CopyAutoImplementedProperties(item, clone);

            foreach (var child in item.Children.Where(c => !c.IsPage))
            {
                var childClone = child.CloneForVersioningRecursive(stateChanger, asPreviousVersion);
                childClone.AddTo(clone);
            }

            return clone;
        }
Example #27
0
 /// <summary>
 /// Replaces the current OrderBy clause
 /// </summary>
 /// <param name="queryBuilder"></param>
 /// <param name="or"></param>
 /// <returns></returns>
 public static IQueryBuilder OrderBy(this IQueryBuilder queryBuilder, IOrderBy orderBy)
 {
     var qb = queryBuilder.Clone();
     qb.QueryDef.OrderBy.Clear();
     qb.QueryDef.OrderBy.Add(orderBy);
     return qb;
 }
        /// <summary>Evaluate on the folds of a dataset split</summary>
        /// <param name="recommender">a rating predictor</param>
        /// <param name="split">a rating dataset split</param>
        /// <param name="compute_fit">if set to true measure fit on the training data as well</param>
        /// <param name="show_fold_results">set to true to print per-fold results to STDERR</param>
        /// <returns>a dictionary containing the average results over the different folds of the split</returns>
        public static RatingPredictionEvaluationResults DoCrossValidation(
			this RatingPredictor recommender,
			ISplit<IRatings> split,
			bool compute_fit = false,
			bool show_fold_results = false)
        {
            var fold_results = new RatingPredictionEvaluationResults[split.NumberOfFolds];

            Parallel.For(0, (int) split.NumberOfFolds, i =>
            {
                try
                {
                    var split_recommender = (RatingPredictor) recommender.Clone(); // to avoid changes in recommender
                    split_recommender.Ratings = split.Train[i];
                    if (recommender is ITransductiveRatingPredictor)
                        ((ITransductiveRatingPredictor) split_recommender).AdditionalFeedback = split.Test[i];
                    split_recommender.Train();
                    fold_results[i] = Ratings.Evaluate(split_recommender, split.Test[i]);
                    if (compute_fit)
                        fold_results[i]["fit"] = (float) split_recommender.ComputeFit();

                    if (show_fold_results)
                        Console.Error.WriteLine("fold {0} {1}", i, fold_results[i]);
                }
                catch (Exception e)
                {
                    Console.Error.WriteLine("===> ERROR: " + e.Message + e.StackTrace);
                    throw e;
                }
            });

            return new RatingPredictionEvaluationResults(fold_results);
        }
Example #29
0
        public static BaseCalendar GetUserCalendar(this BaseCalendar calendar, UserViewSettings userViewSettings)
        {
            var cal = (BaseCalendar)calendar.Clone();

            if (userViewSettings == null)
                return cal;
            
            //name             
            if (!String.IsNullOrEmpty(userViewSettings.Name))
                cal.Name = userViewSettings.Name;

            //backgroundColor
            if (!String.IsNullOrEmpty(userViewSettings.BackgroundColor))
                cal.Context.HtmlBackgroundColor = userViewSettings.BackgroundColor;

            //textColor
            if (!String.IsNullOrEmpty(userViewSettings.TextColor))
                cal.Context.HtmlTextColor = userViewSettings.TextColor;

            //TimeZoneInfo      
            if (userViewSettings.TimeZone!= null)
                cal.TimeZone = userViewSettings.TimeZone;

            //alert type            
            cal.EventAlertType = userViewSettings.EventAlertType;

            return cal;
        }
        /// <summary>
        /// Recorta una imagen en formato Bitmap
        /// </summary>
        /// <param name="localizacion">localizacion de la esquina izquierda de arriba</param>
        /// <param name="tamaño">tamaño del rectangulo</param>
        /// <param name="bitmapARecortar">bitmap para recortar</param>
        /// <returns>bitmap resultado del recorte</returns>
        public static Bitmap Recortar(this Bitmap bitmapARecortar, Point localizacion, Size tamaño)
        {

            Rectangle rect = new Rectangle(localizacion.X, localizacion.Y, tamaño.Width, tamaño.Height);
            Bitmap cropped = bitmapARecortar.Clone(rect, bitmapARecortar.PixelFormat);
            return cropped;

        }