Exemple #1
0
        public override IEntity Decode(MultiKey islandKey, Dictionary <MultiKey, IEntity> entities)
        {
            double totalDistance = 0.0;
            var    entity        = entities[Key] as TSPEntity;
            var    chromosome    = entity.Chromosomes[Key[0]] as PermutationChromosome;
            var    firstPoint    = TSPPoints[chromosome.Genes[0]];
            var    previousPoint = firstPoint;

            for (int i = 1; i < chromosome.Genes.Length; i++)
            {
                var point = TSPPoints[chromosome.Genes[i]];
                totalDistance += GetDistance(previousPoint, point);
                entity.Phenotype.Add(previousPoint);
                previousPoint = point;
            }

            totalDistance += GetDistance(previousPoint, firstPoint);
            entity.Phenotype.Add(previousPoint);

            MultiObjectiveFitness fitness = new MultiObjectiveFitness(new double[] { -1 * totalDistance });

            entity.SetFitness(fitness);
            entity.TotalDistance = totalDistance;

            EntityCount++;

            return(entity);
        }
Exemple #2
0
 public override IList <IEntity> Combine(MultiKey islandKey, Dictionary <MultiKey, IEntity> entities)
 {
     return(new List <IEntity>()
     {
         entities[Key]
     });
 }
 public void ProcessJoin(ISet <MultiKey <EventBean> > newEvents, ISet <MultiKey <EventBean> > oldEvents)
 {
     if (_processor.Prototype.OptionalHavingExpr == null)
     {
         if (newEvents != null && !newEvents.IsEmpty())
         {
             _outputLastIStreamBufJoin = EventBeanUtility.GetLastInSet(newEvents);
         }
         if (oldEvents != null && !oldEvents.IsEmpty())
         {
             _outputLastRStreamBufJoin = EventBeanUtility.GetLastInSet(oldEvents);
         }
     }
     else
     {
         if (newEvents != null && newEvents.Count > 0)
         {
             foreach (MultiKey <EventBean> theEvent in newEvents)
             {
                 EvaluateParams eParams = new EvaluateParams(theEvent.Array, true, _processor.ExprEvaluatorContext);
                 if (InstrumentationHelper.ENABLED)
                 {
                     InstrumentationHelper.Get().QHavingClauseJoin(theEvent.Array);
                 }
                 var passesHaving = _processor.Prototype.OptionalHavingExpr.Evaluate(eParams);
                 if (InstrumentationHelper.ENABLED)
                 {
                     InstrumentationHelper.Get().AHavingClauseJoin(passesHaving.AsBoxedBoolean());
                 }
                 if ((passesHaving == null) || (false.Equals(passesHaving)))
                 {
                     continue;
                 }
                 _outputLastIStreamBufJoin = theEvent;
             }
         }
         if (oldEvents != null && oldEvents.Count > 0)
         {
             foreach (MultiKey <EventBean> theEvent in oldEvents)
             {
                 EvaluateParams eParams = new EvaluateParams(theEvent.Array, false, _processor.ExprEvaluatorContext);
                 if (InstrumentationHelper.ENABLED)
                 {
                     InstrumentationHelper.Get().QHavingClauseJoin(theEvent.Array);
                 }
                 var passesHaving = _processor.Prototype.OptionalHavingExpr.Evaluate(eParams);
                 if (InstrumentationHelper.ENABLED)
                 {
                     InstrumentationHelper.Get().AHavingClauseJoin(passesHaving.AsBoxedBoolean());
                 }
                 if ((passesHaving == null) || (false.Equals(passesHaving)))
                 {
                     continue;
                 }
                 _outputLastRStreamBufJoin = theEvent;
             }
         }
     }
 }
Exemple #4
0
 public static ISet <MultiKey <EventBean> > ToSingletonSetIfNotNull(MultiKey <EventBean> row)
 {
     if (row == null)
     {
         return(null);
     }
     return(Collections.SingletonSet(row));
 }
Exemple #5
0
        /**
         * Is the key equal to the combined key.
         *
         * @param entry  the entry to compare to
         * @param key1  the first key
         * @param key2  the second key
         * @return true if the key matches
         */
        protected bool isEqualKey(AbstractHashedMap.HashEntry entry, Object key1, Object key2)
        {
            MultiKey multi = (MultiKey)entry.getKey();

            return
                (multi.size() == 2 &&
                 (key1 == null ? multi.getKey(0) == null : key1.equals(multi.getKey(0))) &&
                 (key2 == null ? multi.getKey(1) == null : key2.equals(multi.getKey(1))));
        }
Exemple #6
0
        public override IEntity Decode(MultiKey islandKey, Dictionary <MultiKey, IEntity> entities)
        {
            EntityCount++;
            SortedSubsetChromosomeValidator.EntityCount = EntityCount;

            var entity     = entities[Key] as VehicleSchedulingEntity;
            var chromosome = entity.Chromosomes[Key[0]] as SortedSubsetChromosome;

            entity.VehiclesCount = chromosome.Sections.Length;

            for (int s = 0; s < chromosome.Sections.Length; s++)
            {
                //int DailyFirstTime = InitData.Trips[chromosome.Sections[s][0]].ArrivalTime;
                //int length = chromosome.Sections[s].Length;
                //int DailyLastTime = InitData.Trips[chromosome.Sections[s][length-1]].DepartureTime;
                //int? AMLastTime = null;
                //int? PMFirstTime = null;

                for (int p = 0; p < chromosome.Sections[s].Length - 1; p++)
                {
                    if (ConflictDetector.ConflictDetected(chromosome.Sections[s][p], chromosome.Sections[s][p + 1]))
                    {
                        throw new ApplicationException("Shit happend");
                        //return null;    //hard conflict
                    }

                    var trip1 = InitData.Trips[chromosome.Sections[s][p]];
                    var trip2 = InitData.Trips[chromosome.Sections[s][p + 1]];

                    double distance = InitData.GetDistance(trip1.LastStopId, trip2.FirstStopId);
                    entity.TotalDeadMileage += distance;

                    //if ((trip1.DepartureTime <= 720) && (!AMLastTime.HasValue || trip1.DepartureTime > AMLastTime)) AMLastTime = trip1.DepartureTime;
                    //if ((trip1.ArrivalTime >= 720) && (!PMFirstTime.HasValue || trip1.ArrivalTime < PMFirstTime)) PMFirstTime = trip1.ArrivalTime;
                }

                //var lastTrip = InitData.Trips[chromosome.Sections[s][length-1]];
                //if ((lastTrip.DepartureTime <= 720) && (!AMLastTime.HasValue || lastTrip.DepartureTime > AMLastTime)) AMLastTime = lastTrip.DepartureTime;
                //if ((lastTrip.ArrivalTime >= 720) && (!PMFirstTime.HasValue || lastTrip.ArrivalTime < PMFirstTime)) PMFirstTime = lastTrip.ArrivalTime;

                //entity.TotalActiveTime += DailyLastTime - DailyFirstTime;
                //if (AMLastTime.HasValue) entity.TotalActiveTime -= (720 - AMLastTime.Value);
                //if (PMFirstTime.HasValue) entity.TotalActiveTime -= (PMFirstTime.Value - 720);
            }

            var fitness0 = 1 / (1 + entity.TotalDeadMileage);
            var fitness1 = 1 / (1 + (double)entity.VehiclesCount);
            MultiObjectiveFitness fitness = new MultiObjectiveFitness(new double[] { fitness0, fitness1 });

            //fitness.Value[2] = 1 / (1 + (double) entity.TotalActiveTime);
            //GetAverageLengthOfLongSections(chromosome.Sections);

            entity.SetFitness(fitness);

            return(entity);
        }
Exemple #7
0
        /// <summary>
        ///     Convert the multi-key to an object array
        /// </summary>
        /// <param name="mk">to convert</param>
        /// <returns>object-array</returns>
        public static object[] ToObjectArray(this MultiKey mk)
        {
            var keys = new object[mk.NumKeys];

            for (var i = 0; i < keys.Length; i++)
            {
                keys[i] = mk.GetKey(i);
            }

            return(keys);
        }
Exemple #8
0
        private static MultiKey CreateIslandKey(Configuration.Implementation.PeaSettings settings)
        {
            var key = new string[settings.SubProblemList.Count];

            for (int i = 0; i < settings.SubProblemList.Count; i++)
            {
                key[i] = settings.SubProblemList[i].Encoding.Key;
            }
            var islandKey = new MultiKey(key);

            return(islandKey);
        }
        public UniformPair <EventBean[]> OutputJoin(bool isSynthesize)
        {
            if (_outputLastIStreamBufJoin == null && _outputLastRStreamBufJoin == null)
            {
                return(null);
            }
            UniformPair <EventBean[]> pair = _processor.ProcessJoinResult(EventBeanUtility.ToSingletonSetIfNotNull(_outputLastIStreamBufJoin), EventBeanUtility.ToSingletonSetIfNotNull(_outputLastRStreamBufJoin), isSynthesize);

            _outputLastIStreamBufJoin = null;
            _outputLastRStreamBufJoin = null;
            return(pair);
        }
Exemple #10
0
        /**
         * Is the key equal to the combined key.
         *
         * @param entry  the entry to compare to
         * @param key1  the first key
         * @param key2  the second key
         * @param key3  the third key
         * @param key4  the fourth key
         * @param key5  the fifth key
         * @return true if the key matches
         */
        protected bool isEqualKey(AbstractHashedMap.HashEntry entry, Object key1, Object key2, Object key3, Object key4, Object key5)
        {
            MultiKey multi = (MultiKey)entry.getKey();

            return
                (multi.size() == 5 &&
                 (key1 == null ? multi.getKey(0) == null : key1.equals(multi.getKey(0))) &&
                 (key2 == null ? multi.getKey(1) == null : key2.equals(multi.getKey(1))) &&
                 (key3 == null ? multi.getKey(2) == null : key3.equals(multi.getKey(2))) &&
                 (key4 == null ? multi.getKey(3) == null : key4.equals(multi.getKey(3))) &&
                 (key5 == null ? multi.getKey(4) == null : key5.equals(multi.getKey(4))));
        }
Exemple #11
0
        public void SimpleTest()
        {
            using (TestSqlDataSource testDataSource = new TestSqlDataSource("default"))
            {
                testDataSource.Open();

                using (SoodaTransaction tran = new SoodaTransaction())
                {
                    tran.RegisterDataSource(testDataSource);
                    Console.WriteLine(MultiKey.Load(1, 1).Value);
                    Console.WriteLine(MultiKey.Load(1, 1).Value);
                }
            }
        }
Exemple #12
0
        public override bool Equals(object obj)
        {
            MultiKey other = obj as MultiKey;

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

            return(this.KeyB == other.KeyB &&
                   this.Keya == other.Keya &&
                   this.KeyA == other.KeyA &&
                   this.NonKey == other.NonKey);
        }
Exemple #13
0
        public EvaluationWorkerActor(MultiKey islandKey, Type evaluatorType, ParameterSet parameters)
        {
            IslandKey = islandKey;

            ActorPathName = Self.Path.Name;
            //Calculator = (IEvaluation)Activator.CreateInstance(settings.Fitness);
            //Calculator.Init(initData);

            Evaluation = (EvaluationBase)TypeLoader.CreateInstance(evaluatorType, parameters);
            Parameters = parameters;

            Receive <InitEvaluator>(m => Init(m.InitData));
            Receive <IEntity>(e => Evaluate(e));
        }
Exemple #14
0
        /// <summary>
        /// Adds a new collision to the dictionary.
        /// </summary>
        /// <returns>True if no key was found previously, false if an entry was already found.</returns>
        public bool Add(Rigidbody po1, Rigidbody po2)
        {
            MultiKey <Rigidbody> key = new MultiKey <Rigidbody>(po1, po2);

            if (triggers.ContainsKey(key) == false)
            {
                triggers.Add(key, true);
                return(true);
            }
            else
            {
                triggers[key] = true;
                return(false);
            }
        }
Exemple #15
0
        public static IslandEngine Create(MultiKey islandKey, PeaSettings settings, int seed)
        {
            if (seed == 0)
            {
                seed = islandKey.GetHashCode() + Environment.TickCount;
            }

            var random       = (IRandom)Activator.CreateInstance(settings.Random, seed);
            var parameterSet = CreateParameters(settings);

            var fitness         = (IFitnessFactory)Activator.CreateInstance(settings.Fitness);
            var fitnessComparer = fitness.GetFitnessComparer();

            var engine = new IslandEngine()
            {
                Random     = random,
                Settings   = settings,
                Parameters = parameterSet
            };

            var algorithm         = CreateAlgorithm(engine, settings);
            var conflictDetectors = CreateConflictDetectors(settings.SubProblemList);

            var chromosomeFactories = CreateChromosomeFactories(engine, settings, conflictDetectors, random);
            var defaultCreator      = new EntityCreator(settings.EntityType, chromosomeFactories, random);

            engine.EntityCreators = CreateEntityCreators(settings.SubProblemList, defaultCreator, random);

            IMigrationStrategy migrationStrategy = CreateMigrationStrategy(engine, random, fitnessComparer, parameterSet, settings);

            engine.Algorithm         = algorithm.GetAlgorithm(engine);
            engine.FitnessComparer   = fitnessComparer;
            engine.ConflictDetectors = conflictDetectors;
            engine.Selections        = CreateSelections(algorithm, settings, parameterSet, random, fitnessComparer);
            engine.Replacements      = CreateReinsertions(algorithm, settings, parameterSet, random, fitnessComparer);
            engine.MigrationStrategy = migrationStrategy;

            engine.Reduction = new Population.Reduction.CleanOutTournamentLosers(random, parameterSet);
            //engine.Reduction = new Population.Reduction.DoNothingReduction();

            engine.Parameters.SetValueRange(algorithm.GetParameters());

            engine.EntityMutation  = new EntityMutation(chromosomeFactories, random);
            engine.EntityCrossover = new EntityCrossover(chromosomeFactories, random);
            engine.StopCriteria    = settings.StopCriteria;

            return(engine);
        }
Exemple #16
0
        public void MultiTableGetListTestWithWhere()
        {
            using (TestSqlDataSource testDataSource = new TestSqlDataSource("default"))
            {
                testDataSource.Open();

                using (SoodaTransaction tran = new SoodaTransaction())
                {
                    tran.RegisterDataSource(testDataSource);
                    foreach (MultiKey mk in MultiKey.GetList(new SoodaWhereClause("Contact = {0}", 1)))
                    {
                        Console.WriteLine("mk: {0},{1} = {2},{3},{4}", mk.Contact, mk.Group, mk.Value, mk.Value2, mk.Value3);
                    }
                }
            }
        }
Exemple #17
0
        public void GetListTest()
        {
            using (TestSqlDataSource testDataSource = new TestSqlDataSource("default"))
            {
                testDataSource.Open();

                using (SoodaTransaction tran = new SoodaTransaction())
                {
                    tran.RegisterDataSource(testDataSource);
                    foreach (MultiKey mk in MultiKey.GetList(SoodaWhereClause.Unrestricted))
                    {
                        Console.WriteLine("mk: {0},{1} = {2}", mk.Contact, mk.Group, mk.Value);
                    }
                }
            }
        }
Exemple #18
0
        //-----------------------------------------------------------------------

        /**
         * Removes all mappings where the first key is that specified.
         * <p>
         * This method removes all the mappings where the <code>MultiKey</code>
         * has one or more keys, and the first matches that specified.
         *
         * @param key1  the first key
         * @return true if any elements were removed
         */
        public bool removeAll(Object key1)
        {
            bool        modified = false;
            MapIterator it       = mapIterator();

            while (it.hasNext())
            {
                MultiKey multi = (MultiKey)it.next();
                if (multi.size() >= 1 &&
                    (key1 == null ? multi.getKey(0) == null : key1.equals(multi.getKey(0))))
                {
                    it.remove();
                    modified = true;
                }
            }
            return(modified);
        }
Exemple #19
0
        /// <summary>Analyze multiple event types and determine common property sets that form property groups. </summary>
        /// <param name="allProperties">property names to look at</param>
        /// <param name="deltaEventTypes">all types contributing</param>
        /// <param name="names">names of properies</param>
        /// <returns>groups</returns>
        public static PropertyGroupDesc[] AnalyzeGroups(String[] allProperties, EventType[] deltaEventTypes,
                                                        String[] names)
        {
            if (deltaEventTypes.Length != names.Length)
            {
                throw new ArgumentException("Delta event type number and name number of elements don't match");
            }
            allProperties = CopyAndSort(allProperties);

            var result          = new LinkedHashMap <MultiKey <String>, PropertyGroupDesc>();
            var currentGroupNum = 0;

            for (int i = 0; i < deltaEventTypes.Length; i++)
            {
                MultiKey <String> props = GetPropertiesContributed(deltaEventTypes[i], allProperties);
                if (props.Array.Length == 0)
                {
                    Log.Warn("Event type named '" + names[i] +
                             "' does not contribute (or override) any properties of the revision event type");
                    continue;
                }

                PropertyGroupDesc propertyGroup = result.Get(props);
                IDictionary <EventType, String> typesForGroup;
                if (propertyGroup == null)
                {
                    typesForGroup = new Dictionary <EventType, String>();
                    propertyGroup = new PropertyGroupDesc(currentGroupNum++, typesForGroup, props.Array);
                    result.Put(props, propertyGroup);
                }
                else
                {
                    typesForGroup = propertyGroup.Types;
                }
                typesForGroup.Put(deltaEventTypes[i], names[i]);
            }

            PropertyGroupDesc[] array = Collections.ToArray(result.Values);

            if (Log.IsDebugEnabled)
            {
                Log.Debug(".analyzeGroups " + array.Render());
            }
            return(array);
        }
Exemple #20
0
                internal override bool TryCreateKeyFromValues(object[] values, out MultiKey <V1, V2> k)
                {
                    V2     local;
                    object obj2 = values[this.offset];

                    if ((obj2 == null) && typeof(V1).IsValueType)
                    {
                        k = new MultiKey <V1, V2>();
                        return(false);
                    }
                    if (!this.next.TryCreateKeyFromValues(values, out local))
                    {
                        k = new MultiKey <V1, V2>();
                        return(false);
                    }
                    k = new MultiKey <V1, V2>((V1)obj2, local);
                    return(true);
                }
Exemple #21
0
        public EvaluationSupervisorActor(MultiKey islandKey, Type evaluatorType, ParameterSet parameters)
        {
            IslandKey     = islandKey;
            EvaluatorType = evaluatorType;
            Parameters    = parameters;

            var props           = EvaluationWorkerActor.CreateProps(IslandKey, EvaluatorType, Parameters);
            var evaluatorsCount = Parameters.GetInt(ParameterNames.EvaluatorsCount);

            EvaluationWorkers = CreateWorkers(props, evaluatorsCount);

            var paths       = EvaluationWorkers.Select(w => w.Path.ToString());
            var routerProps = Props.Empty.WithRouter(new RoundRobinGroup(paths));

            EvaluationRouter = Context.ActorOf(routerProps, "Evaluators");

            Become(Idle);
        }
Exemple #22
0
        /**
         * Removes all mappings where the first four keys are those specified.
         * <p>
         * This method removes all the mappings where the <code>MultiKey</code>
         * has four or more keys, and the first four match those specified.
         *
         * @param key1  the first key
         * @param key2  the second key
         * @param key3  the third key
         * @param key4  the fourth key
         * @return true if any elements were removed
         */
        public bool removeAll(Object key1, Object key2, Object key3, Object key4)
        {
            bool        modified = false;
            MapIterator it       = mapIterator();

            while (it.hasNext())
            {
                MultiKey multi = (MultiKey)it.next();
                if (multi.size() >= 4 &&
                    (key1 == null ? multi.getKey(0) == null : key1.equals(multi.getKey(0))) &&
                    (key2 == null ? multi.getKey(1) == null : key2.equals(multi.getKey(1))) &&
                    (key3 == null ? multi.getKey(2) == null : key3.equals(multi.getKey(2))) &&
                    (key4 == null ? multi.getKey(3) == null : key4.equals(multi.getKey(3))))
                {
                    it.remove();
                    modified = true;
                }
            }
            return(modified);
        }
Exemple #23
0
        public void InsertTest()
        {
            using (TestSqlDataSource testDataSource = new TestSqlDataSource("default"))
            {
                testDataSource.Open();

                using (SoodaTransaction tran = new SoodaTransaction())
                {
                    tran.RegisterDataSource(testDataSource);
                    MultiKey mk = new MultiKey();
                    mk.Contact = 99;
                    mk.Group   = 123;
                    mk.Value   = 44;
                    mk.Value2  = 55;
                    mk.Value3  = 66;
                    Console.WriteLine(tran.Serialize());
                    tran.Commit();
                }

                using (SoodaTransaction tran = new SoodaTransaction())
                {
                    tran.RegisterDataSource(testDataSource);
                    MultiKey mk2 = MultiKey.Load(99, 123);
                    Assert.AreEqual(44, mk2.Value);
                    Assert.AreEqual(55, mk2.Value2);
                    Assert.AreEqual(66, mk2.Value3);
                    mk2.Value2 = 99;
                    tran.Commit();
                }

                using (SoodaTransaction tran = new SoodaTransaction())
                {
                    tran.RegisterDataSource(testDataSource);
                    MultiKey mk2 = MultiKey.Load(99, 123);
                    Assert.AreEqual(44, mk2.Value);
                    Assert.AreEqual(99, mk2.Value2);
                    Assert.AreEqual(66, mk2.Value3);
                    tran.Commit();
                }
            }
        }
Exemple #24
0
        public PeaResult Run(PeaSettings settings, IEvaluationInitData initData, LaunchTravelersDelegate launchTravelers = null)
        {
            string[] keys = new string[settings.SubProblemList.Count];
            for (int i = 0; i < settings.SubProblemList.Count; i++)
            {
                keys[i] = settings.SubProblemList[i].Encoding.Key;
            }
            Key = new MultiKey(keys);

            var islandEngine = IslandEngineFactory.Create(Key, settings, settings.Seed);

            AddCallbackEvents(islandEngine, settings.NewEntityMergedToBest);

            Evaluator = (EvaluationBase)TypeLoader.CreateInstance(settings.Evaluation, settings.ParameterSet);
            Evaluator.Init(initData);

            islandEngine.Algorithm.SetEvaluationCallback(Evaluate);
            islandEngine.Init(initData);
            if (launchTravelers != null)
            {
                islandEngine.LaunchTravelers += launchTravelers;
            }

            var          c = 0;
            StopDecision stopDecision;

            while (true)
            {
                islandEngine.Algorithm.RunOnce();
                stopDecision = islandEngine.StopCriteria.MakeDecision(islandEngine, islandEngine.Algorithm.Population);
                if (stopDecision.MustStop)
                {
                    Debug.WriteLine(stopDecision.Reasons[0]);
                    break;
                }
                c++;
            }

            return(new PeaResult(stopDecision.Reasons, islandEngine.Algorithm.Population.Bests));
        }
Exemple #25
0
        public PeaSettings GetIslandSettings(MultiKey key)
        {
            var islandSettings = new PeaSettings()
            {
                MigrationStrategy = this.MigrationStrategy,
                EntityType        = this.EntityType,
                Fitness           = this.Fitness,
                Evaluation        = this.Evaluation,
                Random            = this.Random,
                StopCriteria      = this.StopCriteria,
                ParameterSet      = this.ParameterSet
            };

            foreach (var subProblem in SubProblemList)
            {
                if (key.Contains(subProblem.Encoding.Key))
                {
                    islandSettings.SubProblemList.Add(subProblem);
                }
            }

            return(islandSettings);
        }
 public PeaSettingsNamedType(string key, Type valueType)
 {
     Keys      = new MultiKey(key);
     ValueType = valueType;
 }
 public PeaSettingsNamedType(MultiKey keys, Type valueType)
 {
     Keys      = keys;
     ValueType = valueType;
 }
Exemple #28
0
 /// <summary>
 /// This parameter makes sense only when multiselect option is set to true.
 /// Defines the key which will be pressed
 /// when we make a multiselection. The possible values are:
 /// 'shiftKey' - the user should press Shift Key
 /// 'altKey' - the user should press Alt Key
 /// 'ctrlKey' - the user should press Ctrl Key
 /// </summary>
 /// <param name="multiKey">Key to multiselect</param>
 public Grid SetMultiKey(MultiKey multiKey)
 {
     this.multiKey = multiKey;
     return this;
 }
        // returns a rectangle because it's possible that the top,left are outside of the 0,0 requested position.
        public static Rectangle Measure(String text, Graphics graphics, Font font, DrawMethod drawMethod = DrawMethod.Graphics, TextFormatFlags textFormatFlags = TextFormatFlags.Default, Rectangle?rect = null)
        {
            if (String.IsNullOrEmpty(text))
            {
                return(Rectangle.Empty);
            }


            MultiKey mk = new MultiKey(text, graphics.TextRenderingHint, font, drawMethod, textFormatFlags, rect);
            //if (drawMethod == DrawMethod.Graphics)
            //	mk = new MultiKey(text, graphics.TextRenderingHint, font, drawMethod);
            //else {
            //	mk = new

            Object o = ht[mk];

            if (o != null)
            {
                return((Rectangle)o);
            }

            Size size = Size.Empty;

            if (rect.HasValue)
            {
                var r2 = rect.Value;
                size        = r2.Size;
                r2.Location = Point.Empty;
                rect        = r2;
            }
            else
            {
                size = (drawMethod == DrawMethod.Graphics ? graphics.MeasureString(text, font).ToSize() : TextRenderer.MeasureText(graphics, text, font, Size.Empty, textFormatFlags));
            }

            int w = size.Width;
            int h = size.Height;

            if (w == 0 || h == 0)
            {
                return(Rectangle.Empty);
            }
            Bitmap bitmap = new Bitmap(w, h, graphics);

            Graphics g2 = Graphics.FromImage(bitmap);

            g2.TextRenderingHint = graphics.TextRenderingHint;
            g2.SmoothingMode     = graphics.SmoothingMode;
            g2.Clear(Color.White);
            if (drawMethod == DrawMethod.Graphics)
            {
                g2.DrawString(text, font, Brushes.Black, 0, 0);
            }
            else
            {
                // always specify a bounding rectangle. Otherwise if flags contains VerticalCenter it will be half cutoff above point (0,0)
                Rectangle r2 = (rect.HasValue ? rect.Value : new Rectangle(Point.Empty, size));
                TextRenderer.DrawText(g2, text, font, r2, Color.Black, Color.White, textFormatFlags);
            }

            int left, right, top, bottom;

            left = right = top = bottom = -1;

            // scanning saves about 50-60% of having to scan the entire image

            for (int i = 0; i < w; i++)
            {
                for (int j = 0; j < h; j++)
                {
                    Color c = bitmap.GetPixel(i, j);
                    if (c.R != 255 || c.G != 255 || c.B != 255)
                    {
                        left = i;
                        break;
                    }
                }
                if (left >= 0)
                {
                    break;
                }
            }

            if (left == -1)
            {
                return(Rectangle.Empty);
            }

            for (int i = w - 1; i >= 0; i--)
            {
                for (int j = 0; j < h; j++)
                {
                    Color c = bitmap.GetPixel(i, j);
                    if (c.R != 255 || c.G != 255 || c.B != 255)
                    {
                        right = i;
                        break;
                    }
                }
                if (right >= 0)
                {
                    break;
                }
            }

            for (int j = 0; j < h; j++)
            {
                for (int i = left; i <= right; i++)
                {
                    Color c = bitmap.GetPixel(i, j);
                    if (c.R != 255 || c.G != 255 || c.B != 255)
                    {
                        top = j;
                        break;
                    }
                }
                if (top >= 0)
                {
                    break;
                }
            }

            for (int j = h - 1; j >= 0; j--)
            {
                for (int i = left; i <= right; i++)
                {
                    Color c = bitmap.GetPixel(i, j);
                    if (c.R != 255 || c.G != 255 || c.B != 255)
                    {
                        bottom = j;
                        break;
                    }
                }
                if (bottom >= 0)
                {
                    break;
                }
            }

            g2.Dispose();
            bitmap.Dispose();

            var r = new Rectangle(left, top, (right - left) + 1, (bottom - top) + 1);

            ht[mk] = r;
            return(r);
        }
Exemple #30
0
 /// <summary>
 /// This parameter makes sense only when multiselect option is set to true. 
 /// Defines the key which will be pressed 
 /// when we make a multiselection. The possible values are: 
 /// 'shiftKey' - the user should press Shift Key 
 /// 'altKey' - the user should press Alt Key 
 /// 'ctrlKey' - the user should press Ctrl Key
 /// </summary>
 /// <param name="multiKey">Key to multiselect</param>
 public Grid setMultiKey(MultiKey multiKey)
 {
     this._multiKey = multiKey;
     return this;
 }
Exemple #31
0
 public static Props CreateProps(MultiKey islandKey, Type evaluatorType, ParameterSet parameters)
 {
     return(Props.Create(() => new EvaluationSupervisorActor(islandKey, evaluatorType, parameters)));
 }
Exemple #32
0
 /// <summary>
 ///     启用或禁用多选,默认值:false
 /// </summary>
 /// <param name = "multiSelect">为 true 时显示多选列</param>
 /// <param name="multiBoxOnly">为 ture 时只有选择checkbox才会起作用</param>
 /// <param name="multiKey">定义使用那个key来做多选</param>
 /// <param name="multiSelectWidth">multiselect列宽度,默认值:20</param>
 /// <returns></returns>
 public Grid SetMultiSelect(bool multiSelect = true, bool multiBoxOnly = false, MultiKey multiKey = MultiKey.None, int multiSelectWidth = 20)
 {
     _multiSelect = multiSelect;
     _multiboxOnly = multiBoxOnly;
     _multiKey = multiKey;
     _multiSelectWidth = multiSelectWidth;
     return this;
 }
Exemple #33
0
        public static Props CreateProps(MultiKey islandKey, Type evaluatorType, ParameterSet parameters)
        {
            var props = Props.Create(() => new EvaluationWorkerActor(islandKey, evaluatorType, parameters));

            return(props);
        }