Ejemplo n.º 1
0
        public override void Update(DBObject dbobject)
        {
            string sqlcmd = "UPDATE " + dbobject.GetType().Name + " SET ";
            ParallelQuery <PropertyInfo> pinfo = dbobject.GetType().GetProperties().AsParallel().Where(x => WhereNotNull(x, dbobject));

            pinfo.ForAll(x => sqlcmd += x.Name + " = " + x.GetValue(dbobject, null) + ", ");
            sqlcmd = sqlcmd.Substring(0, sqlcmd.Length - ", ".Length) + " WHERE ";
            pinfo.ForAll(x => sqlcmd += x.Name + " = " + x.GetValue(dbobject, null) + " AND ");
            sqlcmd = sqlcmd.Substring(0, sqlcmd.Length - " AND ".Length);
        }
Ejemplo n.º 2
0
 public static void WriteLines <TSource>(
     this ParallelQuery <TSource> source, Func <TSource, string> messageFactory = null)
 {
     if (messageFactory == null)
     {
         source.ForAll(value => Trace.WriteLine(value));
     }
     else
     {
         source.ForAll(value => Trace.WriteLine(messageFactory(value)));
     }
 }
Ejemplo n.º 3
0
        private static void DoParallel()
        {
            ParallelQuery <string> pEnumerable = Paths().AsParallel();

            pEnumerable.ForAll(ProcessFile);                     // простая PLINQ-операция с помощью метода расширения.
            IEnumerable <string> p = pEnumerable.AsSequential(); // конвертируем параллельную последовательноть (!!) в обычный энумерабл.
        }
Ejemplo n.º 4
0
        public ActionResult <List <SeriesSearchResult> > StartsWith(string query, int limit = int.MaxValue)
        {
            query = query.ToLowerInvariant();

            List <SeriesSearchResult> seriesList = new List <SeriesSearchResult>();
            ConcurrentDictionary <SVR_AnimeSeries, string> tempSeries = new ConcurrentDictionary <SVR_AnimeSeries, string>();
            ParallelQuery <SVR_AnimeSeries> allSeries = RepoFactory.AnimeSeries.GetAll()
                                                        .Where(a => a?.Contract?.AniDBAnime?.AniDBAnime != null &&
                                                               !a.Contract.AniDBAnime.Tags.Select(b => b.TagName)
                                                               .FindInEnumerable(User.GetHideCategories()))
                                                        .AsParallel();

            #region Search_TitlesOnly
            allSeries.ForAll(a => CheckTitlesStartsWith(a, query, ref tempSeries, limit));
            Dictionary <SVR_AnimeSeries, string> series =
                tempSeries.OrderBy(a => a.Value).ToDictionary(a => a.Key, a => a.Value);

            foreach (KeyValuePair <SVR_AnimeSeries, string> ser in series)
            {
                seriesList.Add(new SeriesSearchResult(HttpContext, ser.Key, ser.Value, 0));
                if (seriesList.Count >= limit)
                {
                    break;
                }
            }

            #endregion

            return(seriesList);
        }
        private static void ExceptionHandlingInsideDelegate()
        {
            var             range          = ParallelEnumerable.Range(1, 20);
            Func <int, int> selectDivision = (i) =>
            {
                try
                {
                    return(i / (i - 10));
                }
                catch (DivideByZeroException ex)
                {
                    Console.WriteLine("Divide by zero exception for {0}", i);
                    return(-1);
                }
            };
            ParallelQuery <int> query = range.Select(i => selectDivision(i)).WithDegreeOfParallelism(2);

            try
            {
                query.ForAll(i => Console.WriteLine(i));
            }
            catch (AggregateException aggregateException)
            {
                foreach (var ex in aggregateException.InnerExceptions)
                {
                    Console.WriteLine(ex.Message);
                    if (ex is DivideByZeroException)
                    {
                        Console.WriteLine("Attempt to divide by zero. Query stopped.");
                    }
                }
            }
        }
Ejemplo n.º 6
0
 public static void UpdateBoundingSpheres(ParallelQuery <Module> allModules)
 {
     allModules.ForAll(module =>
     {
         Module.UpdateFurthestPoints(module);
         module.boundingSphere = Module.GetBoundingSphere(module, module.furthestA, module.furthestB, module.pose);
     });
 }
Ejemplo n.º 7
0
        public static void ForAll(Labeled <ParallelQuery <int> > labeled, int count)
        {
            ParallelQuery <int> query = labeled.Item;
            IntegerRangeSet     seen  = new IntegerRangeSet(0, count);

            query.ForAll <int>(x => seen.Add(x));
            seen.AssertComplete();
        }
Ejemplo n.º 8
0
        private LandmarkCollection(ParallelQuery <ILandmark> query)
        {
            var list = new List <ILandmark>();

            query.ForAll(landmark => { lock (_syncLock) list.Add(landmark); });

            _fastList = list.ToArray().ToFastList();
        }
Ejemplo n.º 9
0
        /// <summary>
        /// <paramref name="source"/>를 모두 병렬로 실행하여, 결과를 <paramref name="target"/> 컬렉션에 요소로 추가한다.
        /// </summary>
        /// <typeparam name="TSource">요소의 수형</typeparam>
        /// <param name="source">병렬 시퀀스</param>
        /// <param name="target">공급자/소비자 패턴의 컬렉션</param>
        public static void OutputToProducerConsumerCollection <TSource>(this ParallelQuery <TSource> source,
                                                                        IProducerConsumerCollection <TSource> target)
        {
            source.ShouldNotBeNull("source");
            target.ShouldNotBeNull("target");

            // 병렬로 수행한 결과를 모두 컬렉션에 추가한다.
            source.ForAll(item => target.TryAdd(item));
        }
Ejemplo n.º 10
0
 public static void UpdatePhysiologicalAge(ParallelQuery <Module> allModules, float dt)
 {
     allModules.ForAll(module =>
     {
         module.physiologicalAge += dt * PlantUtil.ChangeInPhysiologicalAge(module.root.v,
                                                                            module.plant.plantConfig.vigorRootMin,
                                                                            module.plant.plantConfig.vigorRootMax,
                                                                            module.plant.plantConfig.growthRate);
     });
 }
Ejemplo n.º 11
0
        static void Main(string[] args)
        {
            IEnumerable <int> numbers = Enumerable.Range(0, 20);

            ParallelQuery <int> parallelResults = numbers
                                                  .AsParallel()
                                                  .Where(i => i % 2 == 0);

            parallelResults.ForAll(i => Console.WriteLine(i));
        }
Ejemplo n.º 12
0
        /// <summary>
        /// 扩展一个 forAll 方法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="query"></param>
        /// <param name="action"></param>
        public static void ForAll <T>(this ParallelQuery <T> query, Action <T, int> action)
        {
            var index = 0;

            query.ForAll((item) =>
            {
                var inner = Interlocked.Increment(ref index);
                action(item, inner);
            });
        }
Ejemplo n.º 13
0
        public static void OptimizeRotation(ParallelQuery <Module> allModules, int optimizationSteps, float eps)
        {
            var allSpheres = allModules.Select(module => module.boundingSphere);

            for (int step = 0; step < optimizationSteps; step++)
            {
                // Find a better orientation
                allModules.ForAll(module =>
                {
                    float lowestFDistr = Module.ComputeFDistribution(module, module.pose, allSpheres);
                    Pose betterPose    = module.pose;
                    for (int k = 0; k < 4; k++)
                    {
                        // This does euler angles (eps, 0, 0), (-eps, 0, 0), (0, 0, eps), (0, 0, -eps)
                        float rotAngle = eps;
                        if (k % 2 == 1)
                        {
                            rotAngle = -eps;
                        }
                        Quaternion rot = Quaternion.Euler(rotAngle, 0, 0);
                        if (k / 2 == 1)
                        {
                            rot = Quaternion.Euler(0, 0, rotAngle);
                        }
                        Pose nextPose       = new Pose(module.pose.position, module.pose.rotation * rot); // according to https://answers.unity.com/questions/1353333/how-to-add-2-quaternions.html, multiplying in this order means that rot will be relative to the reference frame of module.orientation.rotation, so x axis is right, y axis is up, z axis is forward. We should double check this.
                        float fDistribution = Module.ComputeFDistribution(module, nextPose, allSpheres);
                        if (fDistribution < lowestFDistr)
                        {
                            betterPose   = nextPose;
                            lowestFDistr = fDistribution;
                        }
                    }
                    module.nextPose = betterPose;
                });

                // Update orientation
                allModules.ForAll(module =>
                {
                    module.pose = module.nextPose;
                });
            }
        }
Ejemplo n.º 14
0
        internal static void QueryExpression()
        {
            int[] values = { 4, 3, 2, 1, 0, -1 };
            ParallelQuery <int>    source = values.AsParallel(); // Get source.
            ParallelQuery <double> query  = from int32 in source
                                            where int32 > 0
                                            orderby int32
                                            select Math.Sqrt(int32); // Create query.

            query.ForAll(result => Trace.WriteLine(result));         // Execute query.
        }
Ejemplo n.º 15
0
        internal static void QueryMethods()
        {
            int[] values = { 4, 3, 2, 1, 0, -1 };
            ParallelQuery <int>    source = values.AsParallel(); // Get source.
            ParallelQuery <double> query  = source
                                            .Where(int32 => int32 > 0)
                                            .OrderBy(int32 => int32)
                                            .Select(int32 => Math.Sqrt(int32)); // Create query.

            query.ForAll(result => Trace.WriteLine(result));                    // Execute query.
        }
        private void CheckPosAgainstData(Point positionInData)
        {
            ParallelQuery <LineGraph> lineGraphs = null;

            // There's going to be some threading issues with dynamic data, so this shouldn't be used on dynamic data
            _dispatcher.Invoke(() =>
            {
                lineGraphs = _children?.OfType <LineGraph>().Where(lg => CursorFollowYGraph.GetSnapTo(lg) || CursorFollowXGraph.GetSnapTo(lg)).ToArray().AsParallel();
            });

            if (lineGraphs == null)
            {
                return;
            }

            ConcurrentDictionary <LineGraph, List <Point> > _filteredPointsByGraph   = new ConcurrentDictionary <LineGraph, List <Point> >();
            ConcurrentDictionary <LineGraph, double>        interpolatedCursorPoints = new ConcurrentDictionary <LineGraph, double>();

            lineGraphs.ForAll((lineGraph) =>
            {
                IEnumerable <Point> allPoints = null;
                _dispatcher.Invoke(() =>
                {
                    allPoints = lineGraph.GetPoints();
                });
                var filteredPoints = allPoints.ToList();
                _filteredPointsByGraph[lineGraph] = filteredPoints;
            });

            lineGraphs.ForAll((lineGraph) =>
            {
                var filteredPoints     = _filteredPointsByGraph[lineGraph];
                var interpoloatedPoint = GetInterpolatedValue(filteredPoints, positionInData);
                if (interpoloatedPoint.HasValue)
                {
                    interpolatedCursorPoints[lineGraph] = interpoloatedPoint.Value;
                }
            });

            OnNearestPointUpdated(interpolatedCursorPoints.Values.ToArray());
        }
Ejemplo n.º 17
0
 /// <summary>Runs the query and outputs its results into the target collection.</summary>
 /// <typeparam name="TSource">Specifies the type of elements output from the query.</typeparam>
 /// <param name="source">The source query.</param>
 /// <param name="target">The target collection.</param>
 public static void OutputToProducerConsumerCollection <TSource>(this ParallelQuery <TSource> source,
                                                                 IProducerConsumerCollection <TSource> target)
 {
     if (source == null)
     {
         throw new ArgumentNullException(nameof(source));
     }
     if (target == null)
     {
         throw new ArgumentNullException(nameof(target));
     }
     source.ForAll(item => target.TryAdd(item));
 }
Ejemplo n.º 18
0
 public static void ParallelLinqFuzzyMatch()
 {
     BenchPerformance.Time("Parallel Linq Fuzzy Match",
                           iterations: Data.Iterations, operation: () =>
     {
         ParallelQuery <string> matches = (from word in WordsToSearch.AsParallel()
                                           from match in FuzzyMatch.JaroWinklerModule.bestMatch(Words, word)
                                           select match.Word);
         matches.ForAll(match =>
         {
             Log(match);
         });
     });
 }
Ejemplo n.º 19
0
        public static void UpdateVigor(ParallelQuery <Plant> allPlants)
        {
            allPlants.ForAll(plant =>
            {
                // trickle light from leaves down to root
                Node.TrickleQ(plant.root.root);
                // clamp vigior at vigor root max
                plant.root.root.v = Min(plant.root.root.q, plant.plantConfig.vigorRootMax);
                // trickle vigor from root out to leaves, according to extended Borchert-Honda model
                Node.TrickleV(plant.root.root, plant.plantConfig.lambda);

                Log("Vigor for plant is " + plant.root.root.v);
            });
        }
Ejemplo n.º 20
0
        static void Main(string[] args)
        {
            ParallelQuery <Result> results = null;

            results = from e in BuildData().AsParallel().WithDegreeOfParallelism(4)
                      where Func(e.Dept)
                      select new Result {
                Name     = e.Name,
                ThreadID = Thread.CurrentThread.ManagedThreadId
            };

            Console.WriteLine("----- PLINQ Results -----");
            results.ForAll((r) => Console.WriteLine("{0} found by thread {1}", r.Name, r.ThreadID));
        }
Ejemplo n.º 21
0
 internal static void Visualize <TSource>(
     this ParallelQuery <TSource> source, Action <TSource> action, string span = Parallel, int category = 1)
 {
     using (Markers.EnterSpan(category, span))
     {
         MarkerSeries markerSeries = Markers.CreateMarkerSeries(span);
         source.ForAll(value =>
         {
             using (markerSeries.EnterSpan(Thread.CurrentThread.ManagedThreadId, value.ToString()))
             {
                 action(value);
             }
         });
     }
 }
Ejemplo n.º 22
0
 static void Main(string[] args)
 {
     try
     {
         IEnumerable <int>   numbers         = Enumerable.Range(0, 20);
         ParallelQuery <int> parallelResults = numbers
                                               .AsParallel()
                                               .Where(i => IsEven(i));
         parallelResults.ForAll(i => Console.WriteLine(i));
     }
     catch (AggregateException ex)
     {
         Console.WriteLine($"There were {ex.InnerExceptions.Count} exceptions");
     }
 }
    /// <summary>
    /// Creates a single sorted dictionary containing the sum of the values grouped by cacheKey.
    /// </summary>
    /// <param name="values">The source enumerable</param>
    /// <param name="autoPrecision">True is more accurate but less performant.  False uses default double precision math.</param>
    public static SortedDictionary <TKey, double> SumValuesOrdered <TKey>(this ParallelQuery <IDictionary <TKey, double> > values, bool autoPrecision = true)
        where TKey : IComparable
    {
        if (values is null)
        {
            throw new NullReferenceException();
        }
        Contract.EndContractBlock();

        var result = new ConcurrentDictionary <TKey, double>();

        values.ForAll(autoPrecision ? result.AddValuesAccurate : result.AddValues);

        return(new SortedDictionary <TKey, double>(result));
    }
Ejemplo n.º 24
0
        public static void ParallelLinqPartitionerFuzzyMatch()
        {
            BenchPerformance.Time("Parallel PLinq  partitioner Fuzzy Match",
                                  iterations: Data.Iterations, operation: () =>
            {
                var partitioner = Partitioner.Create(WordsToSearch, EnumerablePartitionerOptions.NoBuffering);

                ParallelQuery <string> matches = (from word in WordsToSearch.AsParallel()
                                                  from match in FuzzyMatch.JaroWinklerModule.bestMatch(Words, word)
                                                  select match.Word);
                matches.ForAll(match =>
                {
                    Log(match);
                });
            });
        }
Ejemplo n.º 25
0
        public static void UpdateLight(ParallelQuery <Module> allModules)
        {
            var allSpheres = allModules.Select(module => module.boundingSphere);

            allModules.ForAll(module =>
            {
                if (!module.isShed)
                {
                    module.qFromSun = PlantUtil.CalculateLight(module.boundingSphere, allSpheres);
                }
                else
                {
                    module.qFromSun = 0;
                }
            });
        }
Ejemplo n.º 26
0
        internal static void ParallelLinq()
        {
            int[] values = { 4, 3, 2, 1, 0, -1 };
            ParallelQuery <int>    source = values.AsParallel(); // Get source.
            ParallelQuery <double> query  =
                from int32 in source
                where int32 > 0
                orderby int32
                select Math.Sqrt(int32); // Define query.

            // Equivalent to:
            // ParallelQuery<double> query = source
            //    .Where(int32 => int32 > 0)
            //    .OrderBy(int32 => int32)
            //    .Select(int32 => Math.Sqrt(int32));
            query.ForAll(result => Trace.WriteLine(result)); // Execute query.
        }
Ejemplo n.º 27
0
        /// <summary>Runs the query and outputs its results into the target collection.</summary>
        /// <typeparam name="TSource">Specifies the type of elements output from the query.</typeparam>
        /// <param name="source">The source query.</param>
        /// <param name="target">The target collection.</param>
        public static void OutputToProducerConsumerCollection <TSource>(
            this ParallelQuery <TSource> source,
            IProducerConsumerCollection <TSource> target)
        {
            // Validate arguments
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }
            if (target == null)
            {
                throw new ArgumentNullException("target");
            }

            // Store all results into the collection
            source.ForAll(item => target.TryAdd(item));
        }
Ejemplo n.º 28
0
        public static void ShedBranches(ParallelQuery <Plant> allPlants, ParallelQuery <Module> allModules)
        {
            // Set as pruned
            allModules.ForAll(module =>
            {
                // Branches are shed if vigor is less than vigorRootMin
                if (module.root.v < module.plant.plantConfig.vigorRootMin)
                {
                    //module.isShed = true;
                }
            });

            // Remove all sheded modules from plants
            allPlants.ForAll(plant =>
            {
                plant.modules = ParallelEnumerable.AsParallel(plant.modules).Where(module => !module.isShed).ToList();
            });
        }
Ejemplo n.º 29
0
        public static void Do()
        {
            var sw = Stopwatch.StartNew();

            var numbers = Enumerable.Range(0, 100);

            try
            {
                // It will fail at 0, but will continue a bit longer...
                ParallelQuery <int> parallelResult = numbers.AsParallel().Where(i => IsEven(i));
                parallelResult.ForAll(e => Console.WriteLine(e));
            }
            catch (AggregateException e)
            {
                Console.WriteLine("exceptions: {0}", e.InnerExceptions.Count);
            }

            Console.ReadKey();
        }
        public static void RunExceptionTestForAll1()
        {
            int[] xx = new int[1024];
            for (int i = 0; i < xx.Length; i++)
            {
                xx[i] = i;
            }
            ParallelQuery <int> q = xx.AsParallel().Select <int, int>(
                delegate(int x) { if ((x % 250) == 249)
                                  {
                                      throw new Exception("Fail!");
                                  }
                                  return(x); });

            Assert.Throws <AggregateException>(() =>
            {
                q.ForAll <int>(delegate(int x) { });
            });
        }