Exemple #1
0
        /// <summary>
        /// Moves an item up among its siblings. Returns False if the item is already first in the list, otherwise true.
        /// </summary>
        public static async Task <bool> MoveUp(ISortable item, SaveBehaviour saveBehaviour = SaveBehaviour.Default)
        {
            using (await AsyncLock.Lock())
            {
                var above = await FindItemAbove(item);

                if (above == null)
                {
                    return(false);
                }

                if (above.Order == item.Order)
                {
                    above.Order--;
                }

                await Swap(item, above, saveBehaviour);

                item = await Database.Reload(item);

                above = await Database.Reload(above);
            }

            await JustifyOrders(item, saveBehaviour);

            return(true);
        }
        public static IQueryable <T> SortBy <T>(
            this IQueryable <T> query,
            ISortable sort,
            SortFields <T> fields)
        {
            if (string.IsNullOrEmpty(sort.SortBy) || !fields.HasField(sort.SortBy))
            {
                return(query);
            }

            var field = fields[sort.SortBy];

            for (var i = 0; i < field.Expressions.Count; i++)
            {
                var sortExpr = field.Expressions[i];
                if (i == 0)
                {
                    query = sort.Desc ? query.OrderByDescending(sortExpr) : query.OrderBy(sortExpr);
                    continue;
                }

                if (query is IOrderedQueryable <T> )
                {
                    query = ((IOrderedQueryable <T>)query).ThenBy(sortExpr);
                }
            }

            return(query);
        }
Exemple #3
0
 public void Remove(ISortable item)
 {
     lock (_locker)
     {
         _items.Remove(item);
     }
 }
Exemple #4
0
        private static void TestDesc(IList <int> enumerable, ISortable sortClass)
        {
            var sortedArray  = enumerable.OrderByDescending(x => x).ToArray();
            var arrayToCheck = sortClass.SortDesc(enumerable).ToArray();

            CollectionAssert.AreEqual(sortedArray, arrayToCheck);
        }
Exemple #5
0
        /// <summary>
        /// Moves an item up among its siblings. Returns False if the item is already first in the list, otherwise true.
        /// </summary>
        public static bool MoveUp(ISortable item, SaveBehaviour saveBehaviour = SaveBehaviour.Default)
        {
            lock (SyncLock)
            {
                var above = FindItemAbove(item);

                if (above == null)
                {
                    return(false);
                }

                if (above.Order == item.Order)
                {
                    above.Order--;
                }

                Swap(item, above, saveBehaviour);

                Database.Reload(ref item);
                Database.Reload(ref above);

                JustifyOrders(item, saveBehaviour);

                return(true);
            }
        }
Exemple #6
0
        /// <summary>
        /// Justifies the order of a specified item and its siblings.
        /// The value of the "Order" property in those objects will be 10, 20, 30, ...
        /// </summary>
        public static async Task JustifyOrders(ISortable item, SaveBehaviour saveBehaviour = SaveBehaviour.Default)
        {
            using (await AsyncLock.Lock())
            {
                var changed = new List <Entity>();

                var order = 0;

                foreach (var sibling in (await FindSiblings(item)).OrderBy(i => i.Order).Distinct().ToArray())
                {
                    order += INCREMENT;
                    if (sibling.Order == order)
                    {
                        continue;
                    }

                    var clone = sibling.Clone() as Entity;
                    (clone as ISortable).Order = order;
                    //changed.Add(clone);
                    try
                    {
                        await Database.Save(clone, saveBehaviour);
                    }
                    catch
                    {
                    }
                }

                //await Database.Save(changed, saveBehaviour);
            }
        }
Exemple #7
0
 public void Remove(ISortable item)
 {
     lock (this)
     {
         _items.Remove(item);
     }
 }
Exemple #8
0
 public void Add(ISortable item)
 {
     lock (this)
     {
         _items.Add(item);
     }
 }
Exemple #9
0
        private static void Sort(ISortable sortable, IGeneratorItems generatorItems, int amount, FileService fileService)
        {
            fileService.Save(path, sortable.ToString());

            Console.WriteLine("---- Analyze " + amount + " ----" + sortable.ToString());
            TimeWatch timer = new TimeWatch();

            timer.Start();
            List <int> list = generatorItems.GetData(amount);

            Console.WriteLine("Time Loading List: " + timer.GetEllapsedMilliSeconds());

            timer.Restart();
            List <int> listOrderAsc  = new List <int>(list);
            List <int> listOrderDesc = new List <int>(list);

            Console.WriteLine("Time Loading List to Order Asc or Desc:" + timer.GetEllapsedMilliSeconds());

            timer.Restart();
            List <int> orderedList = OrderAsc(sortable, listOrderAsc);
            long       timeAsc     = timer.GetEllapsedMilliSeconds();

            Console.WriteLine("Time Ordering Asc:" + timer.GetEllapsedMilliSeconds());

            timer.Restart();
            List <int> orderedDescList = OrderDesc(sortable, listOrderDesc);
            long       timeDesc        = timer.GetEllapsedMilliSeconds();

            Console.WriteLine("Time Ordering Desc:" + timer.GetEllapsedMilliSeconds());

            fileService.Save(path, Environment.NewLine + $"Amount:{amount},TimeAsc:{timeAsc}, TimeDesc:{timeDesc}");
        }
        public static IQueryable <T> Sort <T>(this IQueryable <T> query, ISortable request, string?defaultProperty = default)
        {
            string?property = null;

            if (!string.IsNullOrWhiteSpace(request.SortBy))
            {
                // Json formatters converts PascalCase to camelCase so we need to put it back to PascalCase
                char[] a = request.SortBy !.ToCharArray();
                a[0]     = char.ToUpper(a[0]);
                property = new string(a);
            }
            else if (!string.IsNullOrWhiteSpace(defaultProperty))
            {
                property = defaultProperty;
            }
            else
            {
                return(query);
            }

            if (typeof(T).GetProperty(property) == null)
            {
                return(query);
            }

            return(query = request.Ascending ?
                           query.OrderBy(o => EF.Property <object>(o, property)) :
                           query.OrderByDescending(o => EF.Property <object>(o, property)));
        }
Exemple #11
0
        public ISortable <T> GetSortStrategy <T>(SortStrategy sortStrategy, IComparer <T> comparer, IList <T> sortArray)
        {
            ISortable <T> sorter = null;

            switch (sortStrategy)
            {
            case SortStrategy.BubbleSort:
                sorter = new BubbleSort <T>(comparer, sortArray);
                break;

            case SortStrategy.InsertionSort:
                sorter = new InsertionSort <T>(comparer, sortArray);
                break;

            case SortStrategy.SelectionSort:
                sorter = new SelectionSort <T>(comparer, sortArray);
                break;

            case SortStrategy.HeapSort:
                sorter = new HeapSort <T>(comparer, sortArray);
                break;

            default:
                sorter = new HeapSort <T>(comparer, sortArray);
                break;
            }

            return(sorter);
        }
Exemple #12
0
 private void qsortRadio_CheckedChanged(object sender, EventArgs e)
 {
     if (qsortRadio.Checked)
     {
         sortingAlgorithm = new QuickSort <Double> ();
     }
 }
Exemple #13
0
 public void Add(ISortable item)
 {
     lock (_locker)
     {
         _items.Add(item);
     }
 }
Exemple #14
0
        /// <summary>
        /// Moves this item after a specified other item. If null is specified, it will be moved to the beginning of its siblings.
        /// </summary>
        public static async Task MoveAfter(ISortable item, ISortable after, SaveBehaviour saveBehaviour = SaveBehaviour.Default)
        {
            var newOrder = (after == null ? 0 : after.Order) + 1;

            item = await Database.Update(item, o => o.Order = newOrder, saveBehaviour);

            await JustifyOrders(item, saveBehaviour);
        }
Exemple #15
0
 public static ISortable Mutate(this ISortable sortable, IRando rando, float replacementRate)
 {
     if (rando.NextDouble() < replacementRate)
     {
         return(rando.ToPermutation(sortable.Order).ToSortable());
     }
     return(sortable);
 }
Exemple #16
0
 private static T[] Sort <T>(
     this T[] items, ISortable sortableStrategy) where T : IComparable <T>
 {
     T[] copy = items.CopyArray();
     StopWatch.Start();
     sortableStrategy.Sort(copy);
     StopWatch.Stop();
     return(copy);
 }
Exemple #17
0
 public SortResult(ISorter sorter, double sortedness, bool[] stageUse,
                   ISortable sortable, IPermutation result)
 {
     Sortedness = sortedness;
     StageUse   = stageUse;
     Sortable   = sortable;
     Result     = result;
     Sorter     = sorter;
 }
Exemple #18
0
        public void SetSortable(ISortable sortable)
        {
            var p = new Progress <int>(m =>
            {
                Progress?.Report(sendValue(m));
            });

            Sortable = sortable;
            Sortable.SetCallBackMethodByOrderedElement(p);
        }
Exemple #19
0
        public virtual void SetModel(IListModel <T> value, double vpos)
        {
            if (model == value)
            {
                return;
            }

            if (model != null)
            {
                model.Cleared  -= OnModelClearedHandler;
                model.Reloaded -= OnModelReloadedHandler;
            }

            model = value;

            if (model != null)
            {
                model.Cleared            += OnModelClearedHandler;
                model.Reloaded           += OnModelReloadedHandler;
                selection_proxy.Selection = model.Selection;
                IsEverReorderable         = model.CanReorder;
            }

            if (ViewLayout != null)
            {
                ViewLayout.Model = Model;
            }

            ISortable sortable = model as ISortable;

            if (sortable != null && ColumnController != null)
            {
                ISortableColumn sort_column = ColumnController.SortColumn ?? ColumnController.DefaultSortColumn;
                if (sort_column != null)
                {
                    if (sortable.Sort(sort_column))
                    {
                        model.Reload();
                    }
                    RecalculateColumnSizes();
                    RegenerateColumnCache();
                    InvalidateHeader();
                    IsReorderable = sortable.SortColumn == null || sortable.SortColumn.SortType == SortType.None;
                }
            }

            RefreshViewForModel(vpos);

            var handler = ModelChanged;

            if (handler != null)
            {
                handler(this, EventArgs.Empty);
            }
        }
Exemple #20
0
        private async Task Sort(ISortable sortable, IGeneratorItems generatorItems, int amount, IProgress <SortingCore.Services.TimeWatchSortable.TimeAndValue> p, CancellationTokenSource cts)
        {
            SortingCore.Services.TimeWatchSortable timeWatchSortable = new SortingCore.Services.TimeWatchSortable();
            timeWatchSortable.SetProgress(p);
            timeWatchSortable.SetSortable(sortable);

            List <int> list = generatorItems.GetData(amount);

            timeWatchSortable.Start();
            await Task.Run(() => sortable.SortAscending(list));
        }
Exemple #21
0
        /// <summary>
        /// Moves an item up to last among its siblings. Always returns true.
        /// </summary>
        public static bool MoveLast(ISortable item, SaveBehaviour saveBehaviour = SaveBehaviour.Default)
        {
            lock (SyncLock)
            {
                var last = FindSiblings(item).Max(o => o.Order);

                Database.Update(item, o => o.Order = last + 1, saveBehaviour);
                JustifyOrders(item, saveBehaviour);
                return(true);
            }
        }
Exemple #22
0
        public VoteResult Vote(VoteParams voteParams)
        {
            Log.WriteWarning("Vote: Username={0},globalId={1},type={2}", SecurityInfo.SessionData.Profile.UserName, voteParams.GlobalId, voteParams.ObjectType);

            var session = Session;

            using (var tx = session.BeginSaveTransaction())
            {
                var  dbProfile   = session.Load <Profile>(SecurityInfo.SessionData.Profile.GlobalId);
                bool sendMessage = false;

                ISortable planFromDb = null;
                if (voteParams.ObjectType == VoteObject.SupplementCycleDefinition)
                {
                    planFromDb  = session.Get <SupplementCycleDefinition>(voteParams.GlobalId);
                    sendMessage = true;
                }
                else if (voteParams.ObjectType == VoteObject.Exercise)
                {
                    planFromDb  = session.Get <Exercise>(voteParams.GlobalId);
                    sendMessage = true;
                }
                else if (voteParams.ObjectType == VoteObject.WorkoutPlan)
                {
                    planFromDb  = session.Get <TrainingPlan>(voteParams.GlobalId);
                    sendMessage = true;
                }
                else if (voteParams.ObjectType == VoteObject.Supplement)
                {
                    planFromDb = session.Get <Suplement>(voteParams.GlobalId);
                }
                ProfileNotification notificationType = planFromDb.Profile != null ? planFromDb.Profile.Settings.NotificationVoted : ProfileNotification.None;
                VoteResult          result           = new VoteResult();
                result.Rating = saveRating(SecurityInfo, voteParams, dbProfile, planFromDb);


                try
                {
                    //send message only when someone else vote
                    if (planFromDb.Profile != null && planFromDb.Profile != dbProfile && sendMessage)
                    {
                        //SendMessage(notificationType, dbProfile, planFromDb.Profile, messageFormat, messageTypeToSend.Value, "VoteEMailSubject", "VoteEMailMessage", DateTime.Now, dbProfile.UserName, planFromDb.Name, voteParams.UserRating);
                        NewSendMessageEx(notificationType, dbProfile, planFromDb.Profile, "VoteEMailSubject", "VoteEMailMessage", DateTime.Now, dbProfile.UserName, planFromDb.Name, voteParams.UserRating);
                    }
                }
                catch (Exception ex)
                {
                    ExceptionHandler.Default.Process(ex);
                }

                tx.Commit();
                return(result);
            }
        }
 public Task <TResult[]> HandleAsync <TEntity, TResult>(Expression <Func <TEntity, bool> > filter,
                                                        Expression <Func <TEntity, TResult> > selector,
                                                        ISortable pagingData
                                                        )
     where TEntity : class
     where TResult : class
 => _context.Value.Set <TEntity>().Where(filter)
 .Select(selector)
 .Distinct()
 .ApplyPaging(pagingData)
 .ToArrayAsync();
Exemple #24
0
        /// <summary>
        /// Moves an item up to last among its siblings. Always returns true.
        /// </summary>
        public static async Task <bool> MoveLast(ISortable item, SaveBehaviour saveBehaviour = SaveBehaviour.Default)
        {
            using (await AsyncLock.Lock())
            {
                var last = (await FindSiblings(item)).Max(o => o.Order);

                await Entity.Database.Update(item, o => o.Order = last + 1, saveBehaviour);
                await JustifyOrders(item, saveBehaviour);

                return(true);
            }
        }
Exemple #25
0
        /// <summary>
        /// Gets the Next order for an ISortable entity.
        /// The result will be 10 plus the largest order of its siblings.
        /// </summary>
        public static int GetNewOrder(ISortable item)
        {
            lock (SyncLock)
            {
                if (!item.IsNew)
                {
                    throw new ArgumentException("item", "Sorter.GetNewOrder() method needs a new ISortable argument (with IsNew set to true).");
                }

                return(INCREMENT + (FindSiblings(item).LastOrDefault()?.Order ?? 0));
            }
        }
Exemple #26
0
        /// <summary>
        /// Gets the Next order for an ISortable entity.
        /// The result will be 10 plus the largest order of its siblings.
        /// </summary>
        public static async Task <int> GetNewOrder(ISortable item)
        {
            using (await AsyncLock.Lock())
            {
                if (!item.IsNew)
                {
                    throw new ArgumentException("Sorter.GetNewOrder() method needs a new ISortable argument (with IsNew set to true).", nameof(item));
                }

                return(INCREMENT + ((await FindSiblings(item)).LastOrDefault()?.Order ?? 0));
            }
        }
        /// <summary> This is a generic version of C.A.R Hoare's Quick Sort algorithm.
        /// This will handle Sortable objects that are already
        /// sorted, and Sortable objects with duplicate keys.
        /// <p>
        /// </summary>
        /// <param name="sortable">A <code>Sortable</code> object.
        /// </param>
        /// <param name="lo0">Left boundary of partition.
        /// </param>
        /// <param name="hi0">Right boundary of partition.
        /// </param>
        public static void  QuickSort(ISortable sortable, int lo0, int hi0)
        {
            int      lo = lo0;
            int      hi = hi0;
            IOrdered mid;
            IOrdered test;

            if (hi0 > lo0)
            {
                // arbitrarily establish partition element as the midpoint of the vector
                mid  = sortable.Fetch((lo0 + hi0) / 2, null);
                test = null;

                // loop through the vector until indices cross
                while (lo <= hi)
                {
                    // find the first element that is greater than or equal to
                    // the partition element starting from the left index
                    while ((lo < hi0) && (0 > (test = sortable.Fetch(lo, test)).Compare(mid)))
                    {
                        ++lo;
                    }

                    // find an element that is smaller than or equal to
                    // the partition element starting from the right index
                    while ((hi > lo0) && (0 < (test = sortable.Fetch(hi, test)).Compare(mid)))
                    {
                        --hi;
                    }

                    // if the indexes have not crossed, swap
                    if (lo <= hi)
                    {
                        sortable.Swap(lo++, hi--);
                    }
                }

                // if the right index has not reached the left side of array
                // must now sort the left partition
                if (lo0 < hi)
                {
                    QuickSort(sortable, lo0, hi);
                }

                // if the left index has not reached the right side of array
                // must now sort the right partition
                if (lo < hi0)
                {
                    QuickSort(sortable, lo, hi0);
                }
            }
        }
Exemple #28
0
        /// <summary>
        /// Swaps the order of two specified items.
        /// </summary>
        static void Swap(ISortable one, ISortable two, SaveBehaviour saveBehaviour)
        {
            var somethingAboveAll = FindSiblings(one).Max(i => i.Order) + 20;

            Database.EnlistOrCreateTransaction(() =>
            {
                var order1 = two.Order;
                var order2 = one.Order;

                Database.Update(one, i => i.Order = order1, saveBehaviour);
                Database.Update(two, i => i.Order = order2, saveBehaviour);
            });
        }
Exemple #29
0
        /// <summary>
        /// Moves this item before a specified other item. If null is specified, it will be moved to the end of its siblings.
        /// </summary>
        public static async Task MoveBefore(ISortable item, ISortable before, SaveBehaviour saveBehaviour = SaveBehaviour.Default)
        {
            var newOrder = (before == null ? int.MaxValue : before.Order) - 1;

            if (newOrder < 0)
            {
                newOrder = 0;
            }

            item = await Database.Update(item, o => o.Order = newOrder, saveBehaviour);

            await JustifyOrders(item, saveBehaviour);
        }
Exemple #30
0
        /// <summary>
        /// Swaps the order of two specified items.
        /// </summary>
        static async Task Swap(ISortable one, ISortable two, SaveBehaviour saveBehaviour)
        {
            var somethingAboveAll = (await FindSiblings(one)).Max(i => i.Order) + 20;

            await Database.EnlistOrCreateTransaction(async() =>
            {
                var order1 = two.Order;
                var order2 = one.Order;

                await Database.Update(one, i => i.Order = order1, saveBehaviour);
                await Database.Update(two, i => i.Order = order2, saveBehaviour);
            });
        }
 private void Save( ISortable entity )
 {
     if ( entity is Store ) {
     ( (Store)entity ).Save();
       } else if ( entity is Campaign ) {
     ( (Campaign)entity ).Save();
       } else if ( entity is OrderStatus ) {
     ( (OrderStatus)entity ).Save();
       } else if ( entity is ShippingMethod ) {
     ( (ShippingMethod)entity ).Save();
       } else if ( entity is PaymentMethod ) {
     ( (PaymentMethod)entity ).Save();
       } else if ( entity is Country ) {
     ( (Country)entity ).Save();
       } else if ( entity is CountryRegion ) {
     ( (CountryRegion)entity ).Save();
       } else if ( entity is Currency ) {
     ( (Currency)entity ).Save();
       } else if ( entity is EmailTemplate ) {
     ( (EmailTemplate)entity ).Save();
       } else if ( entity is VatGroup ) {
     ( (VatGroup)entity ).Save();
       }
 }
Exemple #32
0
        private void SerializeNavigatorRooms(ServerMessage reply, ISortable<RoomData>[] rooms, int count)
        {
            reply.AddString(string.Empty);
            reply.AddInt32(count);

            for (int i = 0; i < count; i++)
                rooms[i].GetValue().Serialize(reply, false);

            reply.AddBoolean(false);
        }
		/// <summary> This is a generic version of C.A.R Hoare's Quick Sort algorithm.
		/// This will handle Sortable objects that are already
		/// sorted, and Sortable objects with duplicate keys.
		/// <p>
		/// </summary>
		/// <param name="sortable">A <code>Sortable</code> object.
		/// </param>
		/// <param name="lo0">Left boundary of partition.
		/// </param>
		/// <param name="hi0">Right boundary of partition.
		/// </param>
		public static void  QuickSort(ISortable sortable, int lo0, int hi0)
		{
			int lo = lo0;
			int hi = hi0;
			IOrdered mid;
			IOrdered test;
			
			if (hi0 > lo0)
			{
				// arbitrarily establish partition element as the midpoint of the vector
				mid = sortable.Fetch((lo0 + hi0) / 2, null);
				test = null;
				
				// loop through the vector until indices cross
				while (lo <= hi)
				{
					// find the first element that is greater than or equal to
					// the partition element starting from the left index
					while ((lo < hi0) && (0 > (test = sortable.Fetch(lo, test)).Compare(mid)))
						++lo;
					
					// find an element that is smaller than or equal to
					// the partition element starting from the right index
					while ((hi > lo0) && (0 < (test = sortable.Fetch(hi, test)).Compare(mid)))
						--hi;
					
					// if the indexes have not crossed, swap
					if (lo <= hi)
						sortable.Swap(lo++, hi--);
				}
				
				// if the right index has not reached the left side of array
				// must now sort the left partition
				if (lo0 < hi)
					QuickSort(sortable, lo0, hi);
				
				// if the left index has not reached the right side of array
				// must now sort the right partition
				if (lo < hi0)
					QuickSort(sortable, lo, hi0);
			}
		}
		/// <summary> This is a generic version of C.A.R Hoare's Quick Sort algorithm.
		/// This will handle Sortable objects that are already
		/// sorted, and Sortable objects with duplicate keys.
		/// <p>
		/// Equivalent to:
		/// <pre>
		/// QuickSort (sortable, sortable.first (), sortable.last ());
		/// </pre>
		/// </summary>
		/// <param name="sortable">A <code>Sortable</code> object.
		/// </param>
		public static void  QuickSort(ISortable sortable)
		{
			QuickSort(sortable, sortable.First(), sortable.Last());
		}
Exemple #35
0
 private static void SortTheList(ISortable unsortedList)
 {
     unsortedList.Sort();
 }
		/// <summary> Binary search for an object</summary>
		/// <param name="set_Renamed">The collection of <code>Ordered</code> objects.
		/// </param>
		/// <param name="ref_Renamed">The name to search for.
		/// </param>
		/// <param name="lo">The lower index within which to look.
		/// </param>
		/// <param name="hi">The upper index within which to look.
		/// </param>
		/// <returns> The index at which reference was found or is to be inserted.
		/// </returns>
		public static int Bsearch(ISortable set_Renamed, IOrdered ref_Renamed, int lo, int hi)
		{
			int num;
			int mid;
			IOrdered ordered;
			int half;
			int result;
			int ret;
			
			ret = - 1;
			
			num = (hi - lo) + 1;
			ordered = null;
			while ((- 1 == ret) && (lo <= hi))
			{
				half = num / 2;
				mid = lo + ((0 != (num & 1))?half:half - 1);
				ordered = set_Renamed.Fetch(mid, ordered);
				result = ref_Renamed.Compare(ordered);
				if (0 == result)
					ret = mid;
				else if (0 > result)
				{
					hi = mid - 1;
					num = ((0 != (num & 1))?half:half - 1);
				}
				else
				{
					lo = mid + 1;
					num = half;
				}
			}
			if (- 1 == ret)
				ret = lo;
			
			return (ret);
		}
		/// <summary> Binary search for an object</summary>
		/// <param name="set_Renamed">The collection of <code>Ordered</code> objects.
		/// </param>
		/// <param name="ref_Renamed">The name to search for.
		/// </param>
		/// <returns> The index at which reference was found or is to be inserted.
		/// </returns>
		public static int Bsearch(ISortable set_Renamed, IOrdered ref_Renamed)
		{
			return (Bsearch(set_Renamed, ref_Renamed, set_Renamed.First(), set_Renamed.Last()));
		}