public FileTypeInfo(string description, IEnumerable <string> extensions)
        {
            if (string.IsNullOrWhiteSpace(description))
            {
                throw new ArgumentException();
            }
            if (extensions == null)
            {
                throw new ArgumentNullException();
            }

            _extensions = extensions.ToList().AsReadOnly();

            if (_extensions.Any(string.IsNullOrWhiteSpace))
            {
                throw new ArgumentException();
            }
            if (_extensions.Count == 0)
            {
                throw new ArgumentException();
            }
            if (_extensions.Any(e => e[0] != '.'))
            {
                throw new ArgumentException();
            }

            _description = description;
            Groups       = new string[0];
        }
        private static bool TryGetCollectionValues(IObjectReference objectReference, out ReadOnlyCollection <IValue> values, out IType elementType)
        {
            IArrayReference arrayReference = objectReference as IArrayReference;

            if (arrayReference == null)
            {
                int size;
                if (TryGetCollectionSize(objectReference, out size))
                {
                    IClassType classType = objectReference.GetReferenceType() as IClassType;
                    if (classType != null)
                    {
                        IObjectReference collectionObject = null;

                        ReadOnlyCollection <IInterfaceType> interfaces = classType.GetInterfaces(true);
                        if (interfaces.Any(i => i.GetName() == "java.util.Collection"))
                        {
                            collectionObject = objectReference;
                        }
                        else if (interfaces.Any(i => i.GetName() == "java.util.Map"))
                        {
                            IMethod entrySetMethod             = classType.GetConcreteMethod("entrySet", "()Ljava/util/Set;");
                            IStrongValueHandle <IValue> result = objectReference.InvokeMethod(null, entrySetMethod, InvokeOptions.None);
                            if (result != null)
                            {
                                collectionObject = result.Value as IObjectReference;
                            }
                        }

                        if (collectionObject != null)
                        {
                            IClassType collectionObjectType = collectionObject.GetReferenceType() as IClassType;
                            if (collectionObjectType != null)
                            {
                                IMethod toArrayMethod = collectionObjectType.GetConcreteMethod("toArray", "()[Ljava/lang/Object;");
                                IStrongValueHandle <IValue> result = collectionObject.InvokeMethod(null, toArrayMethod, InvokeOptions.None);
                                if (result != null)
                                {
                                    arrayReference = result.Value as IArrayReference;
                                }
                            }
                        }
                    }
                }
            }

            if (arrayReference != null)
            {
                values = arrayReference.GetValues();
                IArrayType arrayType = (IArrayType)arrayReference.GetReferenceType();
                elementType = arrayType.GetComponentType();
                return(true);
            }

            values      = null;
            elementType = null;
            return(false);
        }
Exemple #3
0
        private void CreateEdges()
        {
            edges = new Dictionary <MachineTransition, Tuple <int, int> >();
            bool loopsExist = false;

            foreach (var transition in transitions)
            {
                int idStart = transition.InitialStateId;
                int idEnd   = transition.ResultingStateId;

                if (idStart == idEnd)
                {
                    loopsExist = true;
                    continue;
                }

                var start = vertices[idStart];
                var end   = vertices[idEnd];

                int startAngle = 0;
                int endAngle   = 0;

                startAngle = (int)start.Angle(end);
                endAngle   = startAngle + (startAngle >= 180 ? -180 : +180);

                if (transitions.Any(x => x.InitialStateId == idEnd &&
                                    x.ResultingStateId == idStart))
                {
                    startAngle += 10;
                    endAngle   -= 10;
                }

                var angles = new Tuple <int, int>(startAngle, endAngle);
                edges.Add(transition, angles);
            }

            if (!loopsExist)
            {
                return;
            }

            foreach (var transition in transitions)
            {
                int idStart = transition.InitialStateId;
                int idEnd   = transition.ResultingStateId;

                if (idStart != idEnd)
                {
                    continue;
                }

                int angle = (int)FindMostFreeAngle(idStart, true, true, 0);

                var angles = new Tuple <int, int>(angle, angle);
                edges.Add(transition, angles);
            }
        }
        private static bool IsMastStream(IDictionary <string, string> streamAttributes)
        {
            StreamType result;
            string     type    = streamAttributes.GetEntryIgnoreCase(TypeAttribute);
            string     subType = streamAttributes.GetEntryIgnoreCase(SubTypeAttribute);

            return(type.EnumTryParse(true, out result) && result == StreamType.Text &&
                   AllowedStreamSubTypes.Any(i => string.Equals(i, subType, StringComparison.CurrentCultureIgnoreCase)));
        }
        public bool CandidateExamAdded(ReadOnlyCollection<HtmlTableCell> candidateExamsGridFirstRowData,
            CandidateExam candidateExam)
        {
            var isCandidateCountSame =
                candidateExamsGridFirstRowData.Any(d => d.InnerText == candidateExam.CandidatesCountLimit);
            var isStartDateSame = candidateExamsGridFirstRowData.Any(d => d.InnerText == candidateExam.StartTime);
            var isTrainingRoomSame = candidateExamsGridFirstRowData.Any(d => d.InnerText == candidateExam.TrainingRoom);

            var isCandidateExamAdded = isCandidateCountSame && isStartDateSame && isTrainingRoomSame;

            return isCandidateExamAdded;
        }
Exemple #6
0
        public void DoActionConditionalMultipleChoices()
        {
            Login();
            br.TogglePopups(true);
            br.ClickAction("ProductRepository-FindProductsByCategory");
            IWebElement categories = br.GetField("ProductRepository-FindProductsByCategory-Categories").AssertIsEmpty();

            //categories.SelectListBoxItems(br, "Bikes");
            // selected by default
            br.WaitForAjaxComplete();

            IWebElement subcategories = br.GetField("ProductRepository-FindProductsByCategory-Subcategories").AssertIsEmpty();
            ReadOnlyCollection <IWebElement> options = subcategories.FindElements(By.TagName("option"));

            Assert.AreEqual(4, options.Count);

            Assert.IsTrue(options.Any(we => we.Text == ""));
            Assert.IsTrue(options.Any(we => we.Text == "Mountain Bikes"));
            Assert.IsTrue(options.Any(we => we.Text == "Road Bikes"));
            Assert.IsTrue(options.Any(we => we.Text == "Touring Bikes"));

            categories.SelectListBoxItems(br, "Bikes", "Components"); // unselect bikes select components

            options = subcategories.FindElements(By.TagName("option"));
            Assert.AreEqual(15, options.Count);

            Assert.IsFalse(options.Any(we => we.Text == "Mountain Bikes"));
            Assert.IsTrue(options.Any(we => we.Text == "Handlebars"));

            categories.SelectListBoxItems(br, "Components", "Clothing", "Accessories"); // unselect components

            options = subcategories.FindElements(By.TagName("option"));
            Assert.AreEqual(21, options.Count);

            Assert.IsFalse(options.Any(we => we.Text == "Mountain Bikes"));
            Assert.IsFalse(options.Any(we => we.Text == "Handlebars"));
            Assert.IsTrue(options.Any(we => we.Text == "Caps"));
            Assert.IsTrue(options.Any(we => we.Text == "Lights"));

            subcategories.SelectListBoxItems(br, "Jerseys", "Shorts", "Socks", "Tights", "Vests");

            br.ClickOk();

            br.AssertPageTitleEquals("20 Products");
            Assert.AreEqual("Find Products By Category: Query Result: Viewing 20 of 25 Products", br.GetTopObject().Text);

            br.ClickLast();
            br.AssertPageTitleEquals("5 Products");
            Assert.AreEqual("Find Products By Category: Query Result: Viewing 5 of 25 Products", br.GetTopObject().Text);
            IWebElement pageNo = br.FindElement(By.ClassName("nof-page-number"));

            Assert.AreEqual("Page 2 of 2", pageNo.Text);
        }
        public IElementSearchStrategy RelativeTo(IWebElement relative, SearchDirection direction, bool orthogonalOnly, int xTolerance = 5, int yTolerance = 5)
        {
            //var candidates = new ReadOnlyCollection<IWebElement>(new List<IWebElement>() {relative});

            var candidates = _query;

            var results = new List <IBufferedElement>();

            {
                if (direction == SearchDirection.RightFromAnotherElementInclusiveOrAnywhereNextTo &&
                    _query.Any(q => q.Equals(relative)))
                {
                    results.AddRange(_query.Where(q => q.Equals(relative)).Select(q => new BufferedElement(q)));
                }

                var domNeighbours = _seleniumAdapter.WebDriver.FilterDomNeighbours(candidates, relative);
                //if (domNeighbours.Any())
                //{
                //    if (domNeighbours.Count() == 1)
                //    {
                //        results.Add(new BufferedElement(domNeighbours.First()));
                //    }
                //}

                IEnumerable <IBufferedElement> bufferedElements;
                if (orthogonalOnly)
                {
                    var orthogonalInputs = _seleniumAdapter.WebDriver.FilterOrthogonalElements(candidates, relative, xTolerance, yTolerance);
                    bufferedElements = _seleniumAdapter.WebDriver.SelectWithLocation(orthogonalInputs);
                }
                else
                {
                    bufferedElements = _seleniumAdapter.WebDriver.SelectWithLocation(candidates);
                }

                bufferedElements = SortByDistance(bufferedElements, relative.Location.X, relative.Location.Y);

                bufferedElements = PutNeighborsToFront(bufferedElements, domNeighbours);

                bufferedElements = FilterOtherDirections(direction, bufferedElements, relative);

                results.AddRange(bufferedElements);

                //Highlighter.HighlightElements(bufferedElements.Select(x=>x.WebElement), Selenium);
            }

            return(new LocationHeuristictSearchStrategy(_seleniumAdapter, new ReadOnlyCollection <IWebElement>(results.Select(x => x.WebElement).ToList())));
        }
        public static bool IsVisible(this ISearchContext driver, By locator)
        {
            ReadOnlyCollection <IWebElement> elements = driver.FindElements(locator);
            bool result = elements.Any(IsVisible);

            return(result);
        }
		/// <summary>
		/// Creates a CSS element. In CSS files, the name should be prefixed with "ewf".
		/// </summary>
		public CssElement( string name, params string[] selectors ) {
			if( !selectors.Any() )
				throw new ApplicationException( "There must be at least one selector." );

			this.name = name;
			this.selectors = selectors.ToList().AsReadOnly();
		}
        public GetBonusAndBettingBalancesResponse GetBonusAndBettingBalances()
        {
            ReadOnlyCollection <BonusAndBettingBalanceDto> bonusAndBettingBalances =
                _balanceApiProxy.GetBonusAndBettingBalances(CultureCode, _userContext.UserId);

            if (!bonusAndBettingBalances.Any())
            {
                return(new GetBonusAndBettingBalancesResponse
                {
                    Code = ResponseCode.BonusAndBettingBalancesNotFound
                });
            }

            var response = new GetBonusAndBettingBalancesResponse
            {
                Code     = ResponseCode.Success,
                Balances = bonusAndBettingBalances.Select(bonusAndBettingBalance => new BonusAndBettingBalancesModel
                {
                    Product     = ProductMapping.ReverseMappings[bonusAndBettingBalance.ProductIds],
                    Bonus       = bonusAndBettingBalance.Bonus,
                    Betting     = bonusAndBettingBalance.Betting,
                    BonusStatus = FormatBonusStatus(bonusAndBettingBalance.BonusStatus)
                }).ToArray()
            };

            return(response);
        }
Exemple #11
0
 public UnionDef(DefinitionManager manager, JObject src)
     : base(manager, src)
 {
     elementDefs        = JsonHelpers.Defs <ElementDef>(manager, src, "elements");
     decider            = JsonHelpers.Decider(manager, src);
     _canContainFormIds = elementDefs.Any(d => d.canContainFormIds);
 }
Exemple #12
0
 public MembersDef(DefinitionManager manager, JObject src)
     : base(manager, src)
 {
     memberDefs         = JsonHelpers.Defs <ElementDef>(manager, src, "members");
     signatures         = GetSignatures();
     _canContainFormIds = memberDefs.Any(d => d.canContainFormIds);
 }
        public ReadOnlyCollection <Action> GetAvailableActions(BattleState battleState)
        {
            AttackState attackState = new AttackState();

            attackState.SetTags(TagScope.Attacker, Tags);
            attackState.SetTags(TagScope.Battle, battleState.Tags);
            var workspace = new TagCollection(this);

            attackState.SetDynamicTags(TagScope.TemporaryWorkspace, workspace);

            ReadOnlyCollection <ConditionTagBase> entityLimitTags = Tags.Tags
                                                                    .Concat(battleState.Tags.Tags)
                                                                    .OfType <ConditionTagBase>()
                                                                    .Where(x => x.Key == SystemTagUtility.ActionLimitKey)
                                                                    .ToList()
                                                                    .AsReadOnly();

            return(m_actions.Where(action =>
            {
                attackState.SetTags(TagScope.CurrentAction, action.Tags);

                if (entityLimitTags.Count != 0 && entityLimitTags.Any(x => !x.IsTrue(attackState)))
                {
                    return false;
                }

                ReadOnlyCollection <ConditionTagBase> actionLimitTags = action.Tags.OfType <ConditionTagBase>().Where(x => x.Key == SystemTagUtility.ActionLimitKey).ToList().AsReadOnly();
                return actionLimitTags.Count == 0 || actionLimitTags.All(x => x.IsTrue(attackState));
            }).ToList().AsReadOnly());
        }
Exemple #14
0
 private Result <ReadOnlyCollection <int> > ValidatePositiveNumbers(ReadOnlyCollection <int> input, string argName)
 {
     return(input.Any(x => x <= 0)
         ? Result.Fail <ReadOnlyCollection <int> >
                ($"Argument '{argName}' should contain only positive numbers (Entered value: '{string.Join(" ", input)}')")
         : Result.Ok(input));
 }
Exemple #15
0
        public void ZipMultipleFiles()
        {
            ICompressor     compressor      = new Zip();
            List <FileInfo> filesToCompress = new List <FileInfo>
            {
                new FileInfo(_testFilePath),
                new FileInfo(Path.Combine(_workingDirectory.FullName, "TestData.xml"))
            };

            _compressedFile = compressor.Compress(filesToCompress, new FileInfo(Path.Combine(_workingDirectory.FullName, _targetZipFileName))).DefaultIfEmpty(new FileInfo("mock")).Single();

            Assert.AreEqual(Path.GetExtension(_compressedFile.FullName), ".zip");
            Assert.IsTrue(File.Exists(_compressedFile.FullName));

            using (ZipArchive zip = ZipFile.Open(_compressedFile.FullName, ZipArchiveMode.Read))
            {
                ReadOnlyCollection <ZipArchiveEntry> zipEntries = zip.Entries;
                Assert.IsTrue(zipEntries.Count == filesToCompress.Count);

                foreach (FileInfo file in filesToCompress)
                {
                    Assert.IsTrue(zipEntries.Any(x => x.Name == file.Name));
                }
            }
        }
Exemple #16
0
        /// <summary>
        /// Convert a .vtt subtitle file into a compatible .srt subtitle file.
        /// </summary>
        /// <param name="file">
        /// The source .vtt subtitle file.
        /// </param>
        public void Convert(string file)
        {
            string convertedFile = file.Replace("vtt", "srt");

            if (!File.Exists(convertedFile))
            {
                using (StreamReader reader = new StreamReader(file))
                {
                    String line;
                    int    curLineNum = 1;
                    while (!reader.EndOfStream)
                    {
                        if (!string.IsNullOrEmpty(line = reader.ReadLine()) && !badContents.Any(badItem => line.Contains(badItem, StringComparison.OrdinalIgnoreCase)))
                        {
                            using (StreamWriter writer = new StreamWriter(string.Format("{0}{1}", convertedFile, Program.isDebugging ? ".test" : string.Empty), true))
                            {
                                writer.Write(string.Format("{0}\n", line.Contains("-->") && line.Contains(":") ? string.Format("\n{0}\n{1}", curLineNum++, line.Replace('.', ',')) : string.Join(" ", line.Split(null).Select(text => CheckFormatting(text)))));
                                writer.Close();
                            }
                        }
                        if (Program.isDebugging)
                        {
                            Console.WriteLine(string.Format("{0}", line));                                              //Console.Read();
                        }
                    }
                    reader.Close();
                }
            }
            else
            {
                Console.WriteLine(string.Format("{0} already exists.", convertedFile));
            }
        }
Exemple #17
0
        private static bool EpmPropertyExistsInDeclaredProperties(EntityPropertyMappingAttribute epmAttr, ReadOnlyCollection <ResourceProperty> declaredProperties)
        {
            int    index             = epmAttr.SourcePath.IndexOf('/');
            string propertyToLookFor = (index == -1) ? epmAttr.SourcePath : epmAttr.SourcePath.Substring(0, index);

            return(declaredProperties.Any <ResourceProperty>(p => (p.Name == propertyToLookFor)));
        }
Exemple #18
0
        ////////////////////////////////////////////////////////////////////////////////////////////////////
        /// <summary>
        /// IsInvalidMake verifies that a motorcycle is from an valid manufacturer.
        /// </summary>
        ///
        /// <param name="make"> The make is the same as the manufacturer's name. </param>
        ///
        /// <returns>   Returns null if the make is a valid manufacturer, otherwise an Error. </returns>
        ////////////////////////////////////////////////////////////////////////////////////////////////////
        private static IError IsInvalidMake(string make)
        {
            var error = new Error();

            if (string.IsNullOrEmpty(make))
            {
                error.Add("A make cannot be empty.");
            }

            if (make?.Length > 20)
            {
                error.Add("A make cannot contain more than 20 characters.");
            }

            var invalidMake = new ReadOnlyCollection <string>(new List <string>
            {
                "Ford"
            });

            if (invalidMake.Any(x => x.Equals(make, StringComparison.CurrentCultureIgnoreCase)))
            {
                error.Add($"Make '{make}' is not a valid motorcycle manufacturer.");
            }

            return(error.Messages.Count > 0
                ? error
                : null);
        }
        // Contains whether the given StorageEntityContainerName
        internal bool ContainsStorageEntityContainer(string storageEntityContainerName)
        {
            ReadOnlyCollection <StorageEntityContainerMapping> entityContainerMaps =
                this.GetItems <StorageEntityContainerMapping>();

            return(entityContainerMaps.Any(map => map.StorageEntityContainer.Name.Equals(storageEntityContainerName, StringComparison.Ordinal)));
        }
Exemple #20
0
        public void RandomVoice(String pUsername)
        {
            var settings = UserManager.GetUserSettings(pUsername);

            if (settings != null && _voices.Any(w => w.VoiceInfo.Name.ToLower().Contains(settings.Voice.Trim().ToLower())))
            {
                var voice = _voices.FirstOrDefault(w => w.VoiceInfo.Name.ToLower().Contains(settings.Voice.Trim().ToLower()));
                Synth.SelectVoice(voice.VoiceInfo.Name);
            }
            else
            {
                _index++;
                if (_index >= _voices.Count)
                {
                    _index = 0;
                }

                try
                {
                    var voice = _voices[_index];
                    Synth.SelectVoice(voice.VoiceInfo.Name);
                }
                catch (Exception ex)
                {
                    Logger.Log(ex.ToString());
                }
            }
        }
 internal Comparison(IList <TValue> matches, IList <TValue> onlyOnLeft, IList <TValue> onlyOnRight)
 {
     Matches       = new ReadOnlyCollection <TValue>(matches);
     OnlyOnLeft    = new ReadOnlyCollection <TValue>(onlyOnLeft);
     OnlyOnRight   = new ReadOnlyCollection <TValue>(onlyOnRight);
     AreEquivalent = !OnlyOnLeft.Any() && !OnlyOnRight.Any();
 }
 /// <summary>
 /// Creates an instance from a collection of flow identifiers.
 /// </summary>
 /// <param name="flowIdentifiers">
 /// Indicating a registered FID.
 /// One or more FID fields can be included in this option.
 /// </param>
 public IpV6MobilityOptionFlowSummary(ReadOnlyCollection<ushort> flowIdentifiers)
     : base(IpV6MobilityOptionType.FlowSummary)
 {
     if (!flowIdentifiers.Any())
         throw new ArgumentOutOfRangeException("flowIdentifiers", flowIdentifiers, "Must not be empty.");
     FlowIdentifiers = flowIdentifiers;
 }
Exemple #23
0
        public override bool IsWinner(Player player)
        {
            bool kingOnBackRank = IsKingOnBackRank(player);

            if (!kingOnBackRank)
            {
                return(kingOnBackRank);
            }

            if (player == Player.Black)
            {
                return(!IsDraw());
            }
            else if (WhoseTurn == Player.White)
            {
                if (FindKing(Player.Black).Rank != 8)
                {
                    return(!IsDraw());
                }
                else
                {
                    return(false);
                }
            }
            else
            {
                ReadOnlyCollection <Move> validKingMoves = GetValidMoves(FindKing(Player.Black));
                if (validKingMoves.Any(x => x.NewPosition.Rank == 8))
                {
                    return(false);
                }
                return(!IsDraw());
            }
        }
Exemple #24
0
        public void UseVoice(string voiceHint)
        {
            GetInstalledVoices();

            if (!installedVoices.Any())
            {
                logger.Error("Could not find any installed TTS voices.  TTS will be disabled.");
                VoiceSelected = false;
                return;
            }

            if (HaveVoiceHint(voiceHint))
            {
                logger.Trace("Selecing voice from hint " + voiceHint);
                SelectRandomFavouredVoice(voiceHint);
            }

            if (NoVoiceSelected())
            {
                logger.Trace("No voice selected will use random voice");
                SmartSelectRandomVoice();
            }

            AutoClearSpeechTrackingOnComplete();
            VoiceSelected = true;
        }
Exemple #25
0
        private void InitializeVoice()
        {
            ReadOnlyCollection <InstalledVoice> voices =
                _speechSynthesizer.GetInstalledVoices();

            if (!string.IsNullOrWhiteSpace(Settings.Default.VoiceName) &&
                voices.Any(v => v.VoiceInfo.Name == Settings.Default.VoiceName))
            {
                _speechSynthesizer.SelectVoice(Settings.Default.VoiceName);
            }
            else
            {
                if (Settings.Default.VoiceGender.Equals("Male",
                                                        StringComparison.CurrentCultureIgnoreCase))
                {
                    _speechSynthesizer.SelectVoiceByHints(VoiceGender.Male);
                }
                else if (Settings.Default.VoiceGender.Equals("Female",
                                                             StringComparison.CurrentCultureIgnoreCase))
                {
                    _speechSynthesizer.SelectVoiceByHints(VoiceGender.Female);
                }
                else
                {
                    _speechSynthesizer.SelectVoiceByHints(VoiceGender.Neutral);
                }
            }

            _speechSynthesizer.Rate   = Settings.Default.VoiceRate;
            _speechSynthesizer.Volume = Settings.Default.VoiceVolume;
        }
Exemple #26
0
        public IEnumerable <MetadataObject> GetMetaDataObjects()
        {
            var metadataObjects = new List <MetadataObject>();

            foreach (KeyValuePair <string, Dictionary <string, Operation> > path in _serviceDefinition.Paths)
            {
                var currentPath = path.Key;
                if (BlacklistedPaths.Any(subString => currentPath.IndexOf(subString, StringComparison.OrdinalIgnoreCase) >= 0))
                {
                    continue;
                }
                foreach (KeyValuePair <string, Operation> methodNameOperationPair in path.Value)
                {
                    var method    = methodNameOperationPair.Key;
                    var operation = methodNameOperationPair.Value;

                    var metadataObject = new MetadataObject
                    {
                        MethodName      = GetMethodNameFromHttpVerb(method),
                        HttpMethod      = method.ToUpper(),
                        Url             = "https://management.azure.com" + currentPath,
                        ResponseBody    = new JObject(),
                        ResponseBodyDoc = new JObject(),
                        RequestBody     = GetRequestBodyForOperation(operation, false),
                        RequestBodyDoc  = GetRequestBodyForOperation(operation, true),
                        ApiVersion      = GetApiVersionForOperation(methodNameOperationPair.Value),
                    };
                    metadataObjects.Add(metadataObject);
                }
            }
            return(metadataObjects);
        }
Exemple #27
0
        public Loop(IEnumerable <Expression> initialValue, ConditionFunction condition, NewValueFunction body)
        {
            if (condition == null)
            {
                throw new ArgumentNullException(nameof(condition));
            }
            State     = initialValue.Select((v, i) => new State(i, 0, v)).ToList().AsReadOnly();
            Body      = new ReadOnlyCollection <Expression>(body(State).ToArray());
            Condition = condition(State);
            if (Body.Any(e => e == null))
            {
                throw new ArgumentException("An operand was null");
            }

            if (State.Count != Body.Count)
            {
                throw new ArgumentException("Collection counts were different");
            }

            // Increment the scope number if there's nested loops
            var scope = Body.SelectMany(n => n.AllDependent)
                        .Concat(Condition.AllDependent)
                        .OfType <State>()
                        .OrderBy(s => s.Scope)
                        .FirstOrDefault();

            if (scope != null)
            {
                State     = initialValue.Select((v, i) => new State(i, scope.Id + 1, v)).ToList().AsReadOnly();
                Body      = new ReadOnlyCollection <Expression>(body(State).ToArray());
                Condition = condition(State);
            }
        }
 public static void ModifyTooltipMetrics(ReadOnlyCollection <BaseTooltipLine> lines, ref int X, ref int Y, ref float width, ref float height)
 {
     X      -= 8;
     Y      -= 8;
     width  += 16f;
     height += 16f + (lines.Any(line => line is Tooltip.Common.TooltipLine) ? 8f : 0f);
 }
Exemple #29
0
        bool GoTo(DotNetMethodBodyReference bodyRef, ReadOnlyCollection <object> options)
        {
            bool newTab = options.Any(a => StringComparer.Ordinal.Equals(PredefinedReferenceNavigatorOptions.NewTab, a));
            var  module = GetModule(bodyRef.Module, options);

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

            var method = module.ResolveToken(bodyRef.Token) as MethodDef;

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

            uint offset = bodyRef.Offset;

            if (offset == DotNetMethodBodyReference.PROLOG)
            {
                offset = PROLOG;
            }
            else if (offset == DotNetMethodBodyReference.EPILOG)
            {
                offset = EPILOG;
            }

            var tab = documentTabService.GetOrCreateActiveTab();

            GoToLocation(tab, method, new ModuleTokenId(bodyRef.Module, bodyRef.Token), offset);
            return(true);
        }
        /// <summary> Determines if this user can edit this item, based on several different criteria </summary>
        /// <param name="Item">SobekCM Item to check</param>
        /// <returns>TRUE if the user can edit this item, otherwise FALSE</returns>
        public bool Can_Delete_This_Item(SobekCM_Item Item)
        {
            if ((Can_Delete_All) || (Is_System_Admin))
            {
                return(true);
            }

            if (aggregations.Can_Delete("i" + Item.Bib_Info.Source.Code))
            {
                return(true);
            }

            if (Item.Bib_Info.hasLocationInformation)
            {
                if (aggregations.Can_Delete("i" + Item.Bib_Info.Location.Holding_Code))
                {
                    return(true);
                }
            }

            if (Item.Behaviors.Aggregation_Count > 0)
            {
                ReadOnlyCollection <Aggregation_Info> colls = Item.Behaviors.Aggregations;
                if (colls.Any(ThisCollection => aggregations.Can_Delete(ThisCollection.Code)))
                {
                    return(true);
                }
            }

            return(false);
        }
Exemple #31
0
 public static List <string> GetPhotos(string directoryPath)
 {
     return(Directory.EnumerateFiles(directoryPath)
            .Where(path => Extensions
                   .Any(ext => ext.Equals(Path.GetExtension(path), StringComparison.InvariantCultureIgnoreCase)))
            .Select(Path.GetFullPath)
            .ToList());
 }
Exemple #32
0
 void SetCommands(string currentText, ReadOnlyCollection <CommandExecutor> commands)
 {
     if (CommandText == currentText)
     {
         GeneratedCommands = commands;
         SelectedCommand   = commands.Any() ? commands[0] : null;
     }
 }
Exemple #33
0
        ///<summary>Creates a new AggregateDependency.</summary>
        public AggregateDependency(IEnumerable<Dependency> dependencies)
        {
            if (dependencies == null) throw new ArgumentNullException("dependencies");

            Dependencies = new ReadOnlyCollection<Dependency>(dependencies.ToArray());
            RequiresDataContext = Dependencies.Any(d => d.RequiresDataContext);

            foreach (var child in dependencies) {
                child.RowInvalidated += (sender, e) => OnRowInvalidated(e);
            }
        }
Exemple #34
0
		/// <summary> Creates a new literal conversion. </summary>
		/// <param name="components"> The components that can be successfully parsed. </param>
		/// <param name="result"> The result domain of the conversion. </param>
		public LiteralConversion(Domain result, ReadOnlyCollection<Domain> components)
		{
			Contract.Requires(components != null);
			Contract.Requires(components.Any(domain => domain.ToKind().IsLiteral()), "At least one literal must be present");
			Contract.Requires(Contract.ForAll(components, domain => Enum.IsDefined(typeof(Domain), domain)), "Undefined domain kind");
			Contract.Requires(Contract.ForAll(components, domain => domain.ToKind().IsOperand() || domain.ToKind().IsLiteral()), "No operators are allowed in the literal conversion");
			Contract.Requires(Enum.IsDefined(typeof(Domain), result));

			this.Components = components;
			this.Key = components.First(domain => domain.ToKind().IsLiteral());
			this.Result = result;
		}
 // <summary>
 // Returns a delegate indicating (when called) whether a change has been identified
 // requiring a complete recompile of the query.
 // </summary>
 internal Func<bool> GetRecompileRequiredFunction()
 {
     // assign list to local variable to avoid including the entire Funcletizer
     // class in the closure environment
     var recompileRequiredDelegates = new ReadOnlyCollection<Func<bool>>(_recompileRequiredDelegates);
     return () => recompileRequiredDelegates.Any(d => d());
 }
Exemple #36
0
        private IEnumerable<UIElement> GetChilds(ReadOnlyCollection<UIElement> elements)
        {
            if(elements.Any())
                return new UIElement[0];

            return elements.Select(GetChilds).Aggregate((all, next) => all.Concat(next)).ToArray();
        }
        /// <summary>
        /// The pick plugin from multiple supported plugins.
        /// </summary>
        /// <param name="pluginsToUse">
        /// The plugins to use.
        /// </param>
        /// <returns>
        /// The <see cref="IPlugin"/>.
        /// </returns>
        public IPlugin PickPluginFromMultipleSupportedPlugins(ReadOnlyCollection<IPlugin> pluginsToUse)
        {
            if (pluginsToUse != null && pluginsToUse.Any())
            {
                return pluginsToUse.First();
            }

            return null;
        }
Exemple #38
0
 private Expression<Action<FunctionContext>> CompileSingleLambda(ReadOnlyCollection<StatementAst> statements, ReadOnlyCollection<TrapStatementAst> traps, string funcName, IScriptExtent entryExtent, IScriptExtent exitExtent)
 {
     this._currentFunctionName = funcName;
     this._loopTargets.Clear();
     this._returnTarget = Expression.Label("returnTarget");
     List<Expression> exprs = new List<Expression>();
     this.GenerateFunctionProlog(exprs, entryExtent);
     List<Expression> list2 = new List<Expression>();
     List<ParameterExpression> temps = new List<ParameterExpression>();
     this.CompileStatementListWithTraps(statements, traps, list2, temps);
     exprs.AddRange(list2);
     exprs.Add(Expression.Label(this._returnTarget));
     Version version = Environment.Version;
     if (((version.Major == 4) && (version.Minor == 0)) && ((version.Build == 0x766f) && (version.Revision < 0x40d6)))
     {
         exprs.Add(Expression.Call(CachedReflectionInfo.PipelineOps_Nop, new Expression[0]));
     }
     this.GenerateFunctionEpilog(exprs, exitExtent);
     temps.Add(_outputPipeParameter);
     temps.Add(this.LocalVariablesParameter);
     Expression body = Expression.Block((IEnumerable<ParameterExpression>) temps, (IEnumerable<Expression>) exprs);
     if (!this._compilingTrap && (((traps != null) && traps.Any<TrapStatementAst>()) || (from stmt in statements
         where AstSearcher.Contains(stmt, ast => ast is TrapStatementAst, false)
         select stmt).Any<StatementAst>()))
     {
         body = Expression.Block(new ParameterExpression[] { _executionContextParameter }, new Expression[] { Expression.TryCatchFinally(body, Expression.Call(Expression.Field(_executionContextParameter, CachedReflectionInfo.ExecutionContext_Debugger), CachedReflectionInfo.Debugger_ExitScriptFunction), new CatchBlock[] { Expression.Catch(typeof(ReturnException), ExpressionCache.Empty) }) });
     }
     else
     {
         body = Expression.Block(new ParameterExpression[] { _executionContextParameter }, new Expression[] { Expression.TryFinally(body, Expression.Call(Expression.Field(_executionContextParameter, CachedReflectionInfo.ExecutionContext_Debugger), CachedReflectionInfo.Debugger_ExitScriptFunction)) });
     }
     return Expression.Lambda<Action<FunctionContext>>(body, funcName, new ParameterExpression[] { _functionContext });
 }
Exemple #39
0
        private Expression<Action<FunctionContext>> CompileSingleLambda(ReadOnlyCollection<StatementAst> statements,
                                             ReadOnlyCollection<TrapStatementAst> traps,
                                             string funcName,
                                             IScriptExtent entryExtent,
                                             IScriptExtent exitExtent,
                                             ScriptBlockAst rootForDefiningTypesAndUsings)
        {
            _currentFunctionName = funcName;

            _loopTargets.Clear();

            _returnTarget = Expression.Label("returnTarget");
            var exprs = new List<Expression>();
            var temps = new List<ParameterExpression>();

            GenerateFunctionProlog(exprs, temps, entryExtent);

            if (rootForDefiningTypesAndUsings != null)
            {
                GenerateTypesAndUsings(rootForDefiningTypesAndUsings, exprs);
            }

            var actualBodyExprs = new List<Expression>();

            if (CompilingMemberFunction)
            {
                temps.Add(_returnPipe);
            }

            CompileStatementListWithTraps(statements, traps, actualBodyExprs, temps);

            exprs.AddRange(actualBodyExprs);

            // We always add the return label even if it's unused - that way it doesn't matter what the last
            // expression is in the body - the full body will always have void type.
            exprs.Add(Expression.Label(_returnTarget));

            GenerateFunctionEpilog(exprs, exitExtent);

            temps.Add(LocalVariablesParameter);
            Expression body = Expression.Block(temps, exprs);

            // A return from a normal block is just that - a simple return (no exception).
            // A return from a trap turns into an exception because the trap is compiled into a different lambda, yet
            // the return from the trap must return from the function containing the trap.  So we wrap the full
            // body of regular begin/process/end blocks with a try/catch so a return from the trap returns
            // to the right place.  We can avoid also avoid generating the catch if we know there aren't any traps.
            if (!_compilingTrap &&
                ((traps != null && traps.Count > 0)
                || statements.Any(stmt => AstSearcher.Contains(stmt, ast => ast is TrapStatementAst, searchNestedScriptBlocks: false))))
            {
                body = Expression.Block(
                    new[] { _executionContextParameter },
                    Expression.TryCatchFinally(
                        body,
                        Expression.Call(
                            Expression.Field(_executionContextParameter, CachedReflectionInfo.ExecutionContext_Debugger),
                            CachedReflectionInfo.Debugger_ExitScriptFunction),
                        Expression.Catch(typeof(ReturnException), ExpressionCache.Empty)));
            }
            else
            {
                // Either no traps, or we're compiling a trap - either way don't catch the ReturnException.
                body = Expression.Block(
                    new[] { _executionContextParameter },
                    Expression.TryFinally(
                        body,
                        Expression.Call(
                            Expression.Field(_executionContextParameter, CachedReflectionInfo.ExecutionContext_Debugger),
                            CachedReflectionInfo.Debugger_ExitScriptFunction)));
            }

            return Expression.Lambda<Action<FunctionContext>>(body, funcName, new[] { _functionContext });
        }
Exemple #40
0
 private static bool EpmPropertyExistsInDeclaredProperties(EntityPropertyMappingAttribute epmAttr, ReadOnlyCollection<ResourceProperty> declaredProperties)
 {
     int index = epmAttr.SourcePath.IndexOf('/');
     string propertyToLookFor = (index == -1) ? epmAttr.SourcePath : epmAttr.SourcePath.Substring(0, index);
     return declaredProperties.Any<ResourceProperty>(p => (p.Name == propertyToLookFor));
 }
Exemple #41
0
        protected override bool OnInitialize(ReadOnlyCollection<string> args)
        {
            bool mockSoS = false;
            bool showSplash = true;
            _startMinimized = false;
            if (args.Any(s => s == "/nosplash"))
            {
                showSplash = false;
            }
            if (args.Any(s => s == "/mocksos"))
            {
                mockSoS = true;
            }
            if (args.Any(s => s == "/min"))
            {
                _startMinimized = true;
            }

            _log.Debug(string.Format("OnInitialize() starting; mockSos = {0}; showSplash = {1}, startMinimized = {2}", mockSoS, showSplash, _startMinimized));

            // todo: we shouldn't need to do this
            IocContainer.Instance.Register(typeof(AudioFileService), new AudioFileService());
            IocContainer.Instance.Register(typeof(LedFileService), new LedFileService());

            if (mockSoS)
            {
                IocContainer.Instance.Register(typeof(ISirenOfShameDevice), new MockSirenOfShameDevice());
            }
            else
            {
                IocContainer.Instance.Register(typeof(ISirenOfShameDevice), new SirenOfShameDevice());
            }
            IocContainer.Instance.GetExport<ISirenOfShameDevice>().TryConnect();

            IocContainer.Instance.TryLogAssemblyVersions();

            if (showSplash)
            {
                SplashScreen = new SplashScreen();
            }
            return base.OnInitialize(args);
        }
        /// <summary>
        /// An expectation for checking that all elements present on the web page that
        /// match the locator are visible. Visibility means that the elements are not
        /// only displayed but also have a height and width that is greater than 0.
        /// </summary>
        /// <param name="elements">list of WebElements</param>
        /// <returns>The list of <see cref="IWebElement"/> once it is located and visible.</returns>
        public static Func<IWebDriver, ReadOnlyCollection<IWebElement>> VisibilityOfAllElementsLocatedBy(ReadOnlyCollection<IWebElement> elements)
        {
            return (driver) =>
            {
                try
                {
                    if (elements.Any(element => !element.Displayed))
                    {
                        return null;
                    }

                    return elements.Any() ? elements : null;
                }
                catch (StaleElementReferenceException)
                {
                    return null;
                }
            };
        }
Exemple #43
0
		/// <summary> Allows to construct a set from a generic definition set. </summary>
		private Signature(ReadOnlyCollection<ISet> genericSetArguments, string description)
			: base(genericSignatureDefinition, genericSetArguments, description ?? GetDefaultSignatureDescription(genericSetArguments))
		{
			Contract.Requires(genericSetArguments != null);
			Contract.Requires(genericSetArguments.Any(NotNull));
			Contract.Assert(genericSignatureDefinition.Supersets(this));
		}
Exemple #44
0
		public static void RegisterModules(List<IModule> modules)
		{
			Modules = new ReadOnlyCollection<IModule>(modules);
			IsReportEnabled = Modules.Any(item => item.Name == "Отчёты");
		}