Пример #1
0
        public void PersistentActor_should_support_a_mix_of_persist_calls_sync_async_and_persist_calls()
        {
            var pref = ActorOf(Props.Create(() => new AsyncPersistAndPersistMixedSyncAsyncActor(Name)));

            pref.Tell(new Cmd("a"));
            pref.Tell(new Cmd("b"));
            pref.Tell(new Cmd("c"));

            ExpectMsg("a");
            ExpectMsg("a-e1-1");    // persist, must be before next command

            var expected = new HashSet <string> {
                "b", "a-ea2-2"
            };
            var found = ExpectMsgAnyOf(expected.Cast <object>().ToArray());  // ea2 is PersistAsync, b can be processed before it

            expected.Remove(found.ToString());
            ExpectMsgAnyOf(expected.Cast <object>().ToArray());

            ExpectMsg("b-e1-3");        // persist, must be before next command

            var expected2 = new HashSet <string> {
                "c", "b-ea2-4"
            };
            var found2 = ExpectMsgAnyOf(expected2.Cast <object>().ToArray());

            expected.Remove(found2.ToString());
            ExpectMsgAnyOf(expected2.Cast <object>().ToArray());

            ExpectMsg("c-e1-5");
            ExpectMsg("c-ea2-6");

            ExpectNoMsg(TimeSpan.FromMilliseconds(100));
        }
Пример #2
0
            //.......................................................

            //sorting the hashset
            private static HashSet <T> pass <T>(HashSet <T> data, string name, bool selection)
            {
                var ar = new ArrayList(data.Cast <T>().ToList());// convert hastset to ArrayList

                switch (name)
                {
                case "bubble":
                    ar = bubbleSort(ar, selection);
                    break;

                case "selection":
                    ar = selectionSort(ar, selection);
                    break;

                case "insert":
                    ar = inerstionSort(ar, selection);
                    break;

                case "gnome":
                    ar = gnomeSort(ar, selection);
                    break;
                }

                return(new HashSet <T>(ar.Cast <T>().ToList()));
            }
Пример #3
0
        public override HashSet <AtomicRITE> GetAtomicRites()
        {
            if (!IsDerived)
            {
                HashSet <CoverageAtomicRITE> ARITEs = new HashSet <CoverageAtomicRITE>();

                foreach (ExposureType expType in ExposureTypes)
                {
                    var RITChars = Schedule.RITChars.Where(RitChar => RitChar.ExpType == expType || ExposureTypeCollection.GetMappedType(RitChar.ExpType) == expType);
                    foreach (RITCharacteristic RITChar in RITChars)
                    {
                        foreach (string subperil in CauseOfLossSet.GetSubperils())
                        {
                            ARITEs.Add(new CoverageAtomicRITE(subperil, ExposureTypeCollection.GetMappedType(RITChar.ExpType), RITChar.ParentRITE, RITChar.ID));
                            //IEnumerable<RITCharacteristic> RITChars;
                            //RITChars = rite.RiskCharacteristics.Where(RitChar => RitChar.ExpType == expType || ExposureTypeCollection.GetMappedType(RitChar.ExpType) == expType);
                            //foreach (RITCharacteristic RitChar in RITChars)
                            //{
                            //    ARITEs.Add(new CoverageAtomicRITE(subperil, ExposureTypeCollection.GetMappedType(RitChar.ExpType), rite, RitChar.ID));
                            //}
                        }
                    }
                }

                return(new HashSet <AtomicRITE>(ARITEs.Cast <AtomicRITE>()));
            }
            else
            {
                throw new InvalidOperationException("Cannot get Atomic Rites for derived subjects!");
            }
        }
Пример #4
0
        DisjunctiveExamplesSpec WitnessRegexFunction_iTH(GrammarRule rule, ExampleSpec spec, ExampleSpec regexSpec)
        {
            var result = new Dictionary <State, IEnumerable <object> >();

            // Die erste Spec ist die "äußere spec", die die beispiele enthält
            foreach (var example in spec.Examples)
            {
                var functionInput  = (string)example.Key[rule.Body[2]]; //TODO funktioniert das so? 0 -> der index zeigt die position in der ganzen grammatik an, und 0 ist der input. oder muss hier eine 2 hin? -> index zeigt die position in der parameterliste an. TESTEN!
                var regex          = new Regex("");                     // (Regex)regexSpec.Examples[example.Key];
                var completeString = "";
                var programOutput  = (string)example.Value;             // TODO ?

                //TODO match regex to input and write back, which match-indices have a match, where the output starts, too
                var possibleNs = new HashSet <int>();
                var matches    = regex.Matches(functionInput);

                var possibleStartPositions = new List <int?>();
                for (int i = functionInput.IndexOf(programOutput); i >= 0; i = completeString.IndexOf(programOutput, i + 1))
                {
                    possibleStartPositions.Add(i);
                }


                if (possibleNs.Count == 0)
                {
                    return(null);
                }
                result[example.Key] = possibleNs.Cast <object>();
            }
            return(new DisjunctiveExamplesSpec(result));
        }
Пример #5
0
        public IEnumerable <T> ExecuteMany <T>(QueryDescription query, ObjectBinder objectBinder)
        {
            //// Check if the container-scoped cache already has results for this exact query in which case return the same
            //return ContainerScopedCache.GetOrCreateTyped<IEnumerable<T>>(
            //    CacheKey.Create(new HiveQueryCacheKey(query)),
            //    () =>
            //        {
            var totalOutput = new HashSet <T>();

            foreach (var reader in _repositoryPool)
            {
                reader.ExecuteMany <T>(query, objectBinder)
                .Cast <IReferenceByHiveId>()
                .SkipWhile(RepositoryGroupExtensions.SkipAndMergeFromProviders(reader.ProviderMetadata, totalOutput.Cast <IReferenceByHiveId>()))
                .ForEach(x => totalOutput.Add((T)x));
            }
            var results = totalOutput.Cast <IReferenceByHiveId>().DistinctBy(x => x.Id)
                          .Select(x => RepositoryGroupExtensions.ProcessIdsAndGroupRelationProxyDelegate(_groupRepo, _idRoot, x))
                          .Cast <T>();

            // Raise event with the result of the query
            FrameworkContext.TaskManager.ExecuteInContext(TaskTriggers.Hive.PostQueryResultsAvailable, this, new TaskEventArgs(FrameworkContext, new HiveQueryResultEventArgs(results, query, ContainerScopedCache)));

            // Return
            return(results);
            //});
        }
Пример #6
0
        public EnvironmentSimulator(ConstantSet constants, Arm arm, HashSet <Food> food)
        {
            this.arm = arm;

            nodes = arm.Nodes.Concat(food.Cast <Node>()).ToArray();

            IInfluence gravity  = new GravityInfluence(constants);
            IInfluence buoyancy = new BuoyancyInfluence(constants);
            IInfluence friction = new SphericalFrictionInfluence(constants);

            // The spherical friction is added to food particles only
            foreach (Food f in food)
            {
                f.AddInfluence(friction);
                AddPart(f);
            }

            foreach (Node node in arm.Nodes)
            {
                node.AddInfluence(gravity);
                node.AddInfluence(buoyancy);
                IInfluence repulsion = new RepulsionInfluence(constants, node);
                foreach (Node j in nodes)
                {
                    if (node != j)
                    {
                        j.AddInfluence(repulsion);
                    }
                }

                // We add all of the ODE parts to this aggregate
                AddPart(node);
            }
        }
        protected override void ResetMatches(string searchKey)
        {
            using (new WaitCursor(this))
            {
                if (m_oldSearchKey == searchKey)
                {
                    return;                     // Nothing new to do, so skip it.
                }
                // disable Go button until we rebuild our match list.
                m_btnOK.Enabled = false;
                m_oldSearchKey  = searchKey;

                var wsObj = (IWritingSystem)m_cbWritingSystems.SelectedItem;
                if (wsObj == null)
                {
                    return;
                }

                ITsString tss   = m_tsf.MakeString(searchKey, wsObj.Handle);
                var       field = new SearchField(ReversalIndexEntryTags.kflidReversalForm, tss);

                if (!Controls.Contains(m_searchAnimation))
                {
                    Controls.Add(m_searchAnimation);
                    m_searchAnimation.BringToFront();
                }

                m_matchingObjectsBrowser.Search(new[] { field }, m_filteredReversalEntries.Cast <ICmObject>());

                if (Controls.Contains(m_searchAnimation))
                {
                    Controls.Remove(m_searchAnimation);
                }
            }
        }
Пример #8
0
            public ISet <IBoardPosition> GetPossibleMoves(IBoard board)
            {
                int yIncrement = piece.Player.Color.Equals(PlayerColor.WHITE) ? SINGLE_INCREMENT
                        : -SINGLE_INCREMENT;

                Predicate <IBoardPosition> OnlyIfEnemyIsPresent = (x) => board.GetPieceAtPosition(x) != null &&
                                                                  !board.GetPieceAtPosition(x).Player.Equals(piece.Player);

                ISet <IBoardPosition> possibleDestinations = new HashSet <IBoardPosition>();

                possibleDestinations.UnionWith(AbstractPieceMovementStrategies.DestinationsFromFunction(
                                                   pos => new BoardPosition(pos.X + SINGLE_INCREMENT, pos.Y + yIncrement), piece, board, SINGLE_INCREMENT));
                possibleDestinations.UnionWith(AbstractPieceMovementStrategies.DestinationsFromFunction(
                                                   pos => new BoardPosition(pos.X + -SINGLE_INCREMENT, pos.Y + yIncrement), piece, board, SINGLE_INCREMENT));

                ISet <IBoardPosition> finalDestinations = possibleDestinations.Cast <IBoardPosition>().Where(pos => OnlyIfEnemyIsPresent(pos)).ToHashSet();

                BoardPosition front = new BoardPosition(piece.PiecePosition.X,
                                                        piece.PiecePosition.Y + yIncrement);

                if (board.Contains(front) && board.GetPieceAtPosition(front) == null)
                {
                    finalDestinations.Add(front);
                }

                if (!piece.HasMoved && board.GetPieceAtPosition(front) == null && board
                    .GetPieceAtPosition(new BoardPosition(front.X, front.Y + yIncrement)) == null)
                {
                    finalDestinations.UnionWith(AbstractPieceMovementStrategies.DestinationsFromFunction(
                                                    pos => new BoardPosition(pos.X, pos.Y + yIncrement), piece, board, DOUBLE_INCREMENT));
                }
                return(finalDestinations);
            }
Пример #9
0
        public virtual IEnumerable <TEntity> ExecuteSearch(string query, string language)
        {
            var queryParsers = new[]
            {
                SearchQueryParsers.MetaQueryParser,
                SearchQueryParsers.UserNameQueryParser
            };

            var hits = new HashSet <IDbEntity>();

            foreach (var parser in queryParsers)
            {
                var searchConfig = parser.MapToFieldName(query, language);
                if (searchConfig != null)
                {
                    var findResponse = _repository.Find(searchConfig.Item1, searchConfig.Item2, MatchingStrategy.Equals);
                    if (findResponse.Code == AppStatusCode.Ok)
                    {
                        foreach (var d in findResponse.Data)
                        {
                            if (!hits.Contains(d))
                            {
                                hits.Add(d);
                            }
                        }
                    }
                }
            }

            return(hits.Cast <TEntity>().ToList());
        }
Пример #10
0
        /// <summary>
        /// Notifies that the specified setting has changed (for internal use only).
        /// </summary>
        /// <param name="setting">The setting that has changed.</param>
        internal override void ProcessSettingChanged(IUntypedSettingProxy setting)
        {
            // enqueue changed setting
            lock (mChangedSettings)
            {
                mChangedSettings.Add(setting);
            }

            // schedule calling OnSettingsChanged()
            if (!mSettingChangedScheduled)
            {
                mSettingChangedScheduled = true;
                ThreadPool.QueueUserWorkItem(
                    obj =>
                {
                    mSettingChangedScheduled = false;
                    IUntypedProcessingPipelineStageSetting[] settings = null;
                    lock (mChangedSettings)
                    {
                        if (mChangedSettings.Count > 0)
                        {
                            settings = mChangedSettings.Cast <IUntypedProcessingPipelineStageSetting>().ToArray();
                            mChangedSettings.Clear();
                        }
                    }

                    if (settings != null)
                    {
                        OnSettingsChanged(settings);
                    }
                });
            }
        }
Пример #11
0
        public void Slot_Sanitize_When_A_Sub_Slot_Is_Missing_Link()
        {
            var sourceOfLink = ScriptableObject.CreateInstance <VFXInlineOperator>();

            sourceOfLink.SetSettingValue("m_Type", (SerializableType)typeof(Vector3));

            var sphere = ScriptableObject.CreateInstance <VFXInlineOperator>();

            sphere.SetSettingValue("m_Type", (SerializableType)typeof(Sphere));

            Assert.AreEqual("radius", sphere.inputSlots[0][1].name);
            sourceOfLink.outputSlots[0].Link(sphere.inputSlots[0][0]);

            Assert.AreEqual("center", sphere.inputSlots[0][0].name);
            Assert.AreEqual("radius", sphere.inputSlots[0][1].name);
            Assert.IsTrue(sphere.inputSlots[0][0].HasLink());

            HackRemoveSlotNamed(sphere.inputSlots[0], "radius");
            HackRemoveSlotNamed(sphere.outputSlots[0], "radius");

            sphere.Sanitize(-123);
            var objs = new HashSet <ScriptableObject>();

            sphere.CollectDependencies(objs);
            foreach (var obj in objs.Cast <VFXModel>())
            {
                obj.Sanitize(-123);
            }

            Assert.AreEqual("center", sphere.inputSlots[0][0].name);
            Assert.AreEqual("radius", sphere.inputSlots[0][1].name);
            Assert.IsTrue(sphere.inputSlots[0][0].HasLink());
        }
Пример #12
0
        private void SearchAndReport(string searchValue)
        {
            OnSearcherChangeStateEvent(new EventsThreads.ThreadStringEventArgs($"Searching links in {this.Name} using '{searchValue}' ...."));
            HashSet <string> results           = Query(searchValue);
            List <object>    lstCurrentResults = results.Cast <object>().ToList();

            OnSearcherLogEvent(new EventsThreads.ThreadStringEventArgs(String.Format("[{0}] Found {1} links", strName, lstCurrentResults.Count)));
            OnSearcherLinkFoundEvent(new EventsThreads.ThreadListDataFoundEventArgs(lstCurrentResults));
        }
Пример #13
0
        //-----------------------------------------------------------------------------------------------------------------------------------------------------

        public TInfo[] TakeNotImplementedMembers <TInfo>(TInfo[] members) where TInfo : MemberInfo
        {
            var membersToImplement = new HashSet <MemberInfo>(members);

            membersToImplement.IntersectWith(m_NotImplementedMembers);

            m_NotImplementedMembers.ExceptWith(membersToImplement);

            return(membersToImplement.Cast <TInfo>().ToArray());
        }
Пример #14
0
        /// <summary>
        /// Get thread info.
        /// </summary>
        /// <returns></returns>
        internal string GetThreadInfo()
        {
            var  sb = new StringBuilder();
            bool newThreadChecker = false;

            lock (threadHashSetLock)
            {
                if (theProcess == null)
                {
                    theProcess = Process.GetCurrentProcess();
                }
                if (managedThreadIds.Add(Thread.CurrentThread.ManagedThreadId))
                {
                    managedThreads.Add(Thread.CurrentThread);
                    newThreadChecker = true;
                }
            }
            if (newThreadChecker)
            {
                // Display managed threads
                // Note that there is NOT a 1:1 ratio between managed threads
                // and system (native) threads.
                var nonLiveManagedThreadIds = managedThreads.Cast <Thread>().Where(x => !x.IsAlive).Select(x => x.ManagedThreadId).OrderBy(x => x).ToArray();
                AppendIds(sb, "Managed", nonLiveManagedThreadIds);
                // Managed threads below are still being used now.
                if (nonLiveManagedThreadIds.Length > 0)
                {
                    sb.AppendLine();
                }
                var liveManagedThreadIds = managedThreads.Cast <Thread>().Where(x => x.IsAlive).Select(x => x.ManagedThreadId).OrderBy(x => x).ToArray();
                AppendIds(sb, "ManagedLive", liveManagedThreadIds);
                // Display system threads
                // Note that there is NOT a 1:1 ratio between managed threads
                // and system (native) threads.
                if (liveManagedThreadIds.Length > 0)
                {
                    sb.AppendLine();
                }
                var liveThreadIds = theProcess.Threads.Cast <ProcessThread>().Select(x => x.Id).OrderBy(x => x).ToArray();
                AppendIds(sb, "System", liveThreadIds);
            }
            return(sb.ToString());
        }
Пример #15
0
        void IRelationInternal.CascadedDelete(
            HashSet <object> entities,
            IDeletePrimitive delete)
        {
            if (!this.Options.CascadedDeletion)
            {
                return;
            }

            delete.Delete <TForeign>(entities.Cast <TForeign>().ToList());
        }
Пример #16
0
    public HashSet <T> AllEntityComponents <T>() where T : ComponentBase
    {
        HashSet <ComponentBase> coll = null;

        if (ComponentDic.TryGetValue(typeof(T), out coll))
        {
            return(new HashSet <T>(coll.Cast <T>()));
        }

        return(null);
    }
Пример #17
0
        private void RetroactiveKernelAssignment()
        {
            HashSet <IMyEntity> entities = new HashSet <IMyEntity>();

            MyAPIGateway.Entities.GetEntities(entities, x => x is TEntity);

            foreach (TEntity entity in entities.Cast <TEntity>())
            {
                HandleEntity(entity);
            }
        }
Пример #18
0
 //------------ Methods:
 public IEnumerable <ISelectable> GetSelectedPoints()
 {
     if (MeshEdit.selectionMode == 0)
     {
         return(selVerts.Cast <ISelectable>());
     }
     else
     {
         return(selFaces.Cast <ISelectable>());
     }
 }
Пример #19
0
 public override IEnumerator <ProbabilityItem <T> > GetEnumerator()
 {
     if (curLevel != -1)
     {
         return(currentPool.GetEnumerator());
     }
     else
     {
         return(prototypePool.Cast <ProbabilityItem <T> >().GetEnumerator());
     }
 }
Пример #20
0
        void FloodSelectByColor()
        {
            var targetColor =
                StrokesForTransforms(Selection.transforms).First().m_Color;
            var selection = new HashSet <GameObject>(new ReferenceComparer <GameObject>());

            selection.UnionWith(from stroke in SketchMemoryScript.AllStrokes()
                                where stroke.m_Color == targetColor
                                select TransformForStroke(stroke).gameObject);
            Selection.objects = selection.Cast <UObject>().ToArray();
        }
        //Calculate the heuristic value of a given assembly A
        protected static double H(HashSet <Component> A)
        {
            if (A.Count <= 1)
            {
                return(0);
            }

            if (Memo.ContainsKey(A))
            {
                return(Memo[A].Value);
            }

            var    L            = Math.Log(A.Count, 2);
            double MinTreeDepth = Math.Ceiling(L);
            var    hy           = Graph.addHyperArc(A.Cast <node>().ToList());

            List <double> Values = new List <double>();

            foreach (Connection arc in hy.IntraArcs.Where(a => a is Connection))
            {
                HashSet <Component> arcnodes = new HashSet <Component>(new Component[] { (Component)arc.From, (Component)arc.To });
                Values.Add(Memo[arcnodes].Value);
            }
            Graph.removeHyperArc(hy);
            Values.Sort();

            double total = 0;

            for (int x = 0; x < MinTreeDepth; x++)
            {
                total = total + Values[x];
            }

            return(Math.Max(total, Values.Last()));

            /*
             *          var intraArcs = new List<arc>();
             *          foreach (var Component in subassemblyNodes)
             *          {
             *              foreach (arc arc in Component.arcs)
             *              {
             *                  if (Component == arc.From)
             *                  {
             *                      if (subassemblyNodes.Contains(arc.To))
             *                          intraArcs.Add(arc);
             *                  }
             *                  else
             *                      if (subassemblyNodes.Contains(arc.From))
             *                          intraArcs.Add(arc);
             *              }
             *          }
             */
        }
Пример #22
0
 public UpdatedPermissionsEventAudit(long accountId, long accountLegalEntityId, long accountProviderId, long accountProviderLegalEntityId, long ukprn, Guid?userRef, HashSet <Operation> grantedOperations, DateTime updated)
 {
     AccountId                    = accountId;
     AccountLegalEntityId         = accountLegalEntityId;
     AccountProviderId            = accountProviderId;
     AccountProviderLegalEntityId = accountProviderLegalEntityId;
     Ukprn             = ukprn;
     UserRef           = userRef;
     GrantedOperations = string.Join(",", grantedOperations.Cast <short>());
     Updated           = updated;
     Logged            = DateTime.UtcNow;
 }
Пример #23
0
        public ISchedule RepeatingScheduleFor(HashSet <Month> months = null, HashSet <DayOfWeek> days = null, HashSet <int> hours = null, HashSet <int> minutes = null,
                                              HashSet <int> seconds  = null)
        {
            months  = months ?? AllMonths;
            days    = days ?? AllDays;
            hours   = hours ?? AllHours;
            minutes = minutes ?? AllMinutes;
            seconds = seconds ?? AllSeconds;

            return(new RepeatingSchedule(_metronome.TimeEverySecond,
                                         new HashSet <int>(months.Cast <int>()), days, hours, minutes, seconds));
        }
Пример #24
0
        private void NavigateTo(HashSet <object> list)
        {
            if (list.Count == 0)
            {
                return;
            }
            object first = list.FirstOrDefault();

            if (first is Transaction)
            {
                navigator.ViewTransactions(list.Cast <Transaction>());
            }
        }
Пример #25
0
        public object Backup()
        {
            Profiler.BeginSample("VFXGraph.Backup");
            var dependencies = new HashSet <ScriptableObject>();

            dependencies.Add(this);
            CollectDependencies(dependencies);

            var result = VFXMemorySerializer.StoreObjectsToByteArray(dependencies.Cast <ScriptableObject>().ToArray(), CompressionLevel.Fastest);

            Profiler.EndSample();

            return(result);
        }
Пример #26
0
        public void BasicIterIsCorrect()
        {
            var             fixture   = new Fixture();
            var             expecteds = new HashSet <string>(fixture.CreateMany <string>(100));
            var             runcount  = 0;
            Action <string> act       = x =>
            {
                Assert.Contains(x, expecteds.Cast <object>());
                runcount++;
            };

            expecteds.Iter(act);
            Assert.Equal(runcount, expecteds.Count);
        }
Пример #27
0
        public void CastingCollectionOfClassToAnotherThroughtInterfaceShouldWork()
        {
            var t = new GenericTestsClassT() { Id = 1, Name = "T", CustomT = "CustomT", UnexpectedCommonName = "Common" };

            var collection = new HashSet<GenericTestsClassT>() { t };

            var result = collection.Cast<GenericTestsClassT, GenericTestsClassU, GenericTestsInterfaceI>().SingleOrDefault();

            Assert.IsNotNull(result);
            Assert.AreEqual(1, result.Id);
            Assert.AreEqual("T", result.Name);
            Assert.IsNull(result.CustomU);
            Assert.IsNull(result.UnexpectedCommonName);
        }
Пример #28
0
        private HashSet <T1> HashSetUnion <T1, T2>(HashSet <T1> first, HashSet <T2> second)
        {
            /*
             * NOTE,
             *      first   :   Hashset from entity from State Manager
             *      second  :   Hashset from entity from Cache
             */
            // Create an empty hashset.
            HashSet <T1> union = new HashSet <T1>();

            // Add all elements from 'first' because they're more ~updated~.
            if (first != null)
            {
                if (first.Count > 0)
                {
                    union.UnionWith(first);
                }
            }
            else
            {
                first = new HashSet <T1>();
            }
            if (second != null)
            {
                if (second.Count > 0)
                {
                    // Remove the elements from 'second' that exist in 'first'.
                    Predicate <T2> predicate = delegate(T2 relElemSec)
                    {
                        return(first.Any(relElemStateManager => AreTheseEntitiesTheSame(relElemStateManager, relElemSec)));
                    };
                    second.RemoveWhere(predicate);

                    // If elements exist in 'second',
                    if (second.Count > 0)
                    {
                        // Add them into 'union' because they are missing from 'first'.
                        union.UnionWith(second.Cast <T1>());
                    }

                    first.Clear();
                    second.Clear();
                    first.UnionWith(union);
                    second.UnionWith(union.Cast <T2>());
                }
            }
            return(union);
        }
        // NOTE: Thanks to internal on the IWriter, you can't return IWriter here.
        public static IEnumerable <IReader> DoSomething()
        {
            var structs = new HashSet <IWriter>();

            structs.Add(new SomeObject());
            structs.Add(new SomeObject());
            structs.Add(new SomeObject());

            int i = 0;

            foreach (IWriter s in structs)
            {
                s.Property1 = ++i;
                s.Property2 = i.ToString();
            }

            return(structs.Cast <IReader>());
        }
Пример #30
0
 static DisjunctiveExamplesSpec WitnessK(GrammarRule rule, int parameter, DisjunctiveExamplesSpec spec)
 {
     var result = new Dictionary<State, IEnumerable<object>>();
     foreach (var example in spec.DisjunctiveExamples)
     {
         State inputState = example.Key;
         var ks = new HashSet<int?>();
         var inp = (string)inputState[rule.Body[0]];
         foreach (int? pos in example.Value)
         {
             ks.Add(pos);
             ks.Add(pos - inp.Length - 1);
         }
         if (ks.Count == 0) return null;
         result[inputState] = ks.Cast<object>();
     }
     return new DisjunctiveExamplesSpec(result);
 }
Пример #31
0
        private static void CheckSubreferences <T>(IEnumerable <JToken> token, Func <T, string>[] searchPaths, HashSet <T> forRemove)
            where T : class
        {
            var notForRemove = token.Cast <T>().Where(t => !forRemove.Contains(t)).Cast <JProperty>().ToList();
            var subReference = forRemove
                               .Cast <JProperty>()
                               .Where(i
                                      => searchPaths
                                      .Select(p => notForRemove.Any(t => t.SelectTokens(p(i as T)).Any())).Any(p => p))
                               .ToDictionary(p => p.Name, p => p);

            forRemove.RemoveWhere(p => subReference.ContainsKey((p as JProperty).Name));

            if (subReference.Count > 0)
            {
                CheckSubreferences(subReference.Values, searchPaths, forRemove);
            }
        }
Пример #32
0
        public void Reliable_deny_creation_of_actors_while_shutting_down()
        {
            var sys = ActorSystem.Create("DenyCreationWhileShuttingDown");

            sys.Scheduler.Advanced.ScheduleOnce(TimeSpan.FromMilliseconds(100), () =>
            {
                sys.Terminate();
            });
            var failing = false;
            var created = new HashSet <IActorRef>();

            while (!sys.WhenTerminated.IsCompleted)
            {
                try
                {
                    var t = sys.ActorOf <Terminater>();
                    Assert.False(failing); // because once failing => always failing (it’s due to shutdown)
                    created.Add(t);

                    if (created.Count % 1000 == 0)
                    {
                        Thread.Sleep(50); // in case of unfair thread scheduling
                    }
                }
                catch (InvalidOperationException)
                {
                    failing = true;
                }


                if (!failing && sys.Uptime.TotalSeconds >= 10)
                {
                    throw new AssertionFailedException(created.Last() + Environment.NewLine +
                                                       "System didn't terminate within 5 seconds");
                }
            }

            var nonTerminatedOrNonstartedActors = created.Cast <ActorRefWithCell>()
                                                  .Where(actor => !actor.IsTerminated && !(actor.Underlying is UnstartedCell)).ToList();

            Assert.Equal(0,
                         nonTerminatedOrNonstartedActors.Count);
        }
Пример #33
0
 static DisjunctiveExamplesSpec WitnessKForRegexPair(GrammarRule rule, int parameter,  DisjunctiveExamplesSpec spec, ExampleSpec rrSpec)
 {
     var result = new Dictionary<State, IEnumerable<object>>();
     foreach (var example in spec.DisjunctiveExamples)
     {
         State inputState = example.Key;
         var inp = (string)inputState[rule.Body[0]];
         var regexPair = (Tuple<Regex, Regex>)rrSpec.Examples[inputState];
         Regex left = regexPair.Item1;
         Regex right = regexPair.Item2;
         var rightMatches = right.Matches(inp).Cast<Match>().ToDictionary(m => m.Index);
         var matchPositions = new List<int>();
         foreach (Match m in left.Matches(inp))
         {
             if (rightMatches.ContainsKey(m.Index + m.Length))
                 matchPositions.Add(m.Index + m.Length);
         }
         var ks = new HashSet<int?>();
         foreach (int? pos in example.Value)
         {
             int occurrence = matchPositions.BinarySearch(pos.Value);
             if (occurrence < 0) continue;
             ks.Add(occurrence);
             ks.Add(occurrence - matchPositions.Count);
         }
         if (ks.Count == 0) return null;
         result[inputState] = ks.Cast<object>();
     }
     return new DisjunctiveExamplesSpec(result);
 }
Пример #34
0
        public void PersistentActor_should_support_a_mix_of_persist_calls_sync_async_and_persist_calls()
        {
            var pref = ActorOf(Props.Create(() => new AsyncPersistAndPersistMixedSyncAsyncActor(Name)));
            pref.Tell(new Cmd("a"));
            pref.Tell(new Cmd("b"));
            pref.Tell(new Cmd("c"));

            ExpectMsg("a");
            ExpectMsg("a-e1-1");    // persist, must be before next command

            var expected = new HashSet<string> { "b", "a-ea2-2" };
            var found = ExpectMsgAnyOf(expected.Cast<object>().ToArray());  // ea2 is PersistAsyn, b can be processed before it
            expected.Remove(found.ToString());
            ExpectMsgAnyOf(expected.Cast<object>().ToArray());

            ExpectMsg("b-e1-3");        // persist, must be before next command

            var expected2 = new HashSet<string> { "c", "b-ea2-4" };
            var found2 = ExpectMsgAnyOf(expected2.Cast<object>().ToArray());
            expected.Remove(found2.ToString());
            ExpectMsgAnyOf(expected2.Cast<object>().ToArray());

            ExpectMsg("c-e1-5");
            ExpectMsg("c-ea2-6");

            ExpectNoMsg(TimeSpan.FromMilliseconds(100));
        }