public override void AddContracts( ICSharpContextActionDataProvider provider, Func<IExpression, IExpression> getContractExpression, out ICollection<ICSharpStatement> firstNonContractStatements) { var contractInvariantMethodDeclaration = classLikeDeclaration.EnsureContractInvariantMethod(provider.PsiModule); if (contractInvariantMethodDeclaration.Body != null) { var factory = CSharpElementFactory.GetInstance(provider.PsiModule); var expression = factory.CreateExpression("$0", declaration.DeclaredElement); ICSharpStatement firstNonContractStatement; AddContract( ContractKind.Invariant, contractInvariantMethodDeclaration.Body, provider.PsiModule, () => getContractExpression(expression), out firstNonContractStatement); firstNonContractStatements = firstNonContractStatement != null ? new[] { firstNonContractStatement } : null; } else { firstNonContractStatements = null; } }
public Tweet() { _tweetReports = new HashSet<TweetReport>(); _favourites = new HashSet<Favourite>(); _retweets = new HashSet<Retweet>(); _replies = new HashSet<Tweet>(); }
//public IList<MergeField> AnnexMergeFields { get; private set; } public CustomsOfficeBlock(IList<MergeField> mergeFields, TransportRoute transportRoute) { CorrespondingMergeFields = MergeFieldLocator.GetCorrespondingFieldsForBlock(mergeFields, TypeName); data = new CustomsOfficeViewModel(transportRoute); AnnexMergeFields = MergeFieldLocator.GetAnnexMergeFields(mergeFields, TypeName); }
public override void AddRange(ICollection c) { if (c.GetType() != typeof(ForeignKey_1_n)) throw new CsDOException("Should add only ForeignKey"); base.AddRange(c); }
public User() { this.images = new HashSet<Image>(); this.clubs = new HashSet<Club>(); this.eventLikes = new HashSet<EventLike>(); this.CreatedOn = DateTime.Now; }
private static void ExcludeMultiples(ICollection<long> crossedOffList, long candidate, int max) { for (var i = candidate; i < max + 1; i += candidate) { crossedOffList.Add(i); } }
/// <summary> /// /// </summary> /// <param name="argumentName"></param> /// <param name="col"></param> public static void ArgumentHasLength(ICollection col, string argumentName) { if (col == null || col.Count <= 0) { throw new ArgumentException("参数不能空", argumentName); } }
public AttributeRoutingEngine(ICollection assemblies) { List<IEntryControllerBinding> controllers = new List<IEntryControllerBinding>(); System.Diagnostics.Debug.WriteLine("Init Routing Engine"); foreach (Assembly a in assemblies) { System.Diagnostics.Debug.WriteLine(a.FullName); Type[] types; try { types = a.GetTypes(); } catch { continue; } foreach (Type t in types) { if (t.GetCustomAttributes(typeof(IEntryControllerBinding), false).Length > 0) { IControllerBinding[] bindings = GetControllerBindings(t); if (bindings != null) foreach (IControllerBinding b in bindings) { IEntryControllerBinding eb = b as IEntryControllerBinding; if (eb != null) controllers.Add(eb); } } } } _controllers = controllers.ToArray(); }
public CreateActionPlanCommand(ICollection<Objective> objective, CoachingProcess coachingProcess, string Description = null) { this.CoachingProcess = new HashSet<CoachingProcess>(); this.CoachingProcess.Add(coachingProcess); this.Objective = objective; this.Description = Description; }
internal static bool AreComponentsRemovable(ICollection components) { if (components == null) { throw new ArgumentNullException("components"); } foreach (object obj2 in components) { Activity activity = obj2 as Activity; ConnectorHitTestInfo info = obj2 as ConnectorHitTestInfo; if ((activity == null) && (info == null)) { return false; } if (activity != null) { ActivityDesigner designer = ActivityDesigner.GetDesigner(activity); if ((designer != null) && designer.IsLocked) { return false; } } if ((info != null) && !(info.AssociatedDesigner is FreeformActivityDesigner)) { return false; } } return true; }
protected WorkflowAction(Guid actionId, string name, IEnumerable<Guid> sourceStateIds, IResourceString displayTitle) { _actionId = actionId; _name = name; _sourceStateIds = sourceStateIds == null ? null : new List<Guid>(sourceStateIds); _displayTitle = displayTitle; }
/// <summary> /// Executes the specified pipeline. /// </summary> /// <param name="pipelineName">The name.</param> /// <param name="pipeline">The pipeline.</param> /// <param name="translateRows">Translate the rows into another representation</param> public void Execute(string pipelineName, ICollection<IOperation> pipeline, Func<IEnumerable<Row>, IEnumerable<Row>> translateRows) { try { IEnumerable<Row> enumerablePipeline = PipelineToEnumerable(pipeline, new List<Row>(), translateRows); try { raiseNotifyExecutionStarting(); DateTime start = DateTime.Now; ExecutePipeline(enumerablePipeline); raiseNotifyExecutionCompleting(); Trace("Completed process {0} in {1}", pipelineName, DateTime.Now - start); } catch (Exception e) { string errorMessage = string.Format("Failed to execute pipeline {0}", pipelineName); Error(e, errorMessage); } } catch (Exception e) { Error(e, "Failed to create pipeline {0}", pipelineName); } DisposeAllOperations(pipeline); }
public DotExpression(IExpression expression, string name, ICollection<IExpression> arguments) { this.expression = expression; this.name = name; this.arguments = arguments; this.type = AsType(this.expression); }
public Card GetCardWithSuitThatEnemyDoesNotHave(bool enemyHasATrumpCard, CardSuit trumpSuit, ICollection<Card> playerCards) { if (!enemyHasATrumpCard) { // In case the enemy does not have any trump cards and Stalker has a trump, he should throw a trump. var myTrumpCards = playerCards.Where(c => c.Suit == trumpSuit).ToList(); if (myTrumpCards.Count() > 0) { return myTrumpCards.OrderBy(c => c.GetValue()).LastOrDefault(); } } var orderedCards = playerCards.OrderBy(c => c.GetValue()); foreach (var card in orderedCards) { if (this.cardHolder.EnemyCards.All(c => c.Suit != card.Suit)) { if (enemyHasATrumpCard) { return playerCards.Where(c => c.Suit == card.Suit).OrderBy(c => c.GetValue()).FirstOrDefault(); } return playerCards.Where(c => c.Suit == card.Suit).OrderByDescending(c => c.GetValue()).FirstOrDefault(); } } return null; }
protected CardPairGame(string name, Player player, ICollection<PictureWordPair> pairs) : base(name, player) { PictureCards = pairs.Randomize().Select(x => new PictureCard(x, this) {State = DefaultCardState}).ToList(); WordCards = pairs.Randomize().Select(x => new WordCard(x, this) {State = DefaultCardState}).ToList(); UnsolvedPairs = pairs.ToList(); }
public bool TryGetSubscribers(ICollection<Type> contracts, out ICollection<Address> subscribers) { Mandate.ParameterNotNull(contracts, "contracts"); locker.EnterReadLock(); var allSubscriptions = new List<Address>(); subscribers = allSubscriptions; try { foreach (var subscriptions in contracts.Select(GetSubscribers)) { if (subscriptions == null) continue; allSubscriptions.AddRange(subscriptions); } return allSubscriptions.Any(); } finally { locker.ExitReadLock(); } }
/// <summary> /// Initializes a new instance of the <see cref="AlfredSubsystemListModule" /> class. /// </summary> /// <exception cref="ArgumentNullException"> /// Thrown when one or more required arguments are null. /// </exception> /// <param name="container"> The container. </param> internal AlfredSubsystemListModule([NotNull] IObjectContainer container) : base(container) { if (container == null) { throw new ArgumentNullException(nameof(container)); } _widgets = container.ProvideCollection<WidgetBase>(); }
private string EncodeIds(ICollection<int> ids) { if (ids == null || !ids.Any()) return string.Empty; // Using {1},{2} format so it can be filtered with delimiters. return "{" + string.Join("},{", ids.ToArray()) + "}"; }
public ConfigSettingMetadata(string location, string text, string sort, string className, string helpText, ICollection<string> listenTo) : base(location, text, sort) { _className = className; _helpText = helpText; _listenTo = listenTo; }
public MembershipEvent(ICluster cluster, IMember member, int eventType, ICollection<IMember> members) : base(cluster) { this.member = member; this.eventType = eventType; this.members = members; }
public EmailNotification() { this.Recipients = new List<String>(); this.Attachments = new List<Attachment>(); this.CC = new List<String>(); this.BCC = new List<String>(); }
private IEnumerable<Window> EnumerateWindows() { _windows = new List<Window>(); EnumWindows(EnumerationCallback, IntPtr.Zero); return _windows; }
private static CheckResult CheckDataIfStartMenuIsExpectedToNotExist(ICollection<FileChange> fileChanges, ICollection<Registryhange> registryChanges, FileChange fileChange, StartMenuData startMenuData, Registryhange registryChange) { if (fileChange == null) { return CheckResult.Succeeded(startMenuData); } if (fileChange.Type != FileChangeType.Delete) { fileChanges.Remove(fileChange); if (registryChange != null) { registryChanges.Remove(registryChange); } return CheckResult.Failure("Found menu item:'" + startMenuData.Name + "' when is was not expected"); } // When uninstalling this key get changed const string startPageKey = @"HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\StartPage"; var uninstallStartMenuKey = registryChanges.FirstOrDefault(x => string.Equals(x.Key, startPageKey, StringComparison.InvariantCultureIgnoreCase) && x.ValueName == "FavoritesRemovedChanges" && x.Type == RegistryChangeType.SetValue); if (uninstallStartMenuKey == null) { fileChanges.Remove(fileChange); return CheckResult.Failure(""); } registryChanges.Remove(uninstallStartMenuKey); fileChanges.Remove(fileChange); return CheckResult.Succeeded(startMenuData); }
public override CheckResult DoCheck(BaseTestData data, ICollection<FileChange> fileChanges, ICollection<Registryhange> registryChanges) { if (!VerifyIfCorrectTestData(data)) { return CheckResult.NotCheckDone(); } var startMenuData = data as StartMenuData; var path = startMenuData.AllUsers ? GetAllUsersMenuFolder() : Environment.GetFolderPath(Environment.SpecialFolder.StartMenu); // To get the program folder var dirInfo = new DirectoryInfo(path); path = Path.Combine(path, dirInfo.GetDirectories()[0].Name); path = Path.Combine(path, startMenuData.Name + ".lnk"); // Find registry GlobalAssocChangedCounter key that is updated when creating a startmenu var globalAssocChangedCounterKey = @"HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\explorer"; if (Environment.Is64BitOperatingSystem) { globalAssocChangedCounterKey = @"HKLM\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\explorer"; } var registryChange = registryChanges.FirstOrDefault(x => string.Equals(x.Key, globalAssocChangedCounterKey, StringComparison.InvariantCultureIgnoreCase) && x.ValueName == "GlobalAssocChangedCounter" && x.Type == RegistryChangeType.SetValue); var fileChange = fileChanges.FirstOrDefault(x => x.Path == path); return startMenuData.Exist ? CheckDataIfStartMenuIsExpectedToExist(fileChanges, registryChanges, fileChange, startMenuData, registryChange) : CheckDataIfStartMenuIsExpectedToNotExist(fileChanges, registryChanges, fileChange, startMenuData, registryChange); }
/// <summary> /// Where a field value is one in a set. /// </summary> public static iCondition In(this iCondition pCon, string pFieldName, ICollection<string> pValues) { IEnumerable<string> strings = from str in pValues select string.Format("'{0}'", str); return pValues.Count == 0 ? pCon : Expression(pCon, pFieldName, string.Format("IN ({0})", string.Join(",", strings))); }
private static void AddProperty(ICollection<SearchResult> results, string field, string searchTerm) { if (field.ToLowerInvariant().Contains(searchTerm.ToLowerInvariant().Trim())) { results.Add(new SearchResult { id = field, name = field }); } }
/// <summary> /// Creates a new GoToEvent using the given locations. /// </summary> /// <param name="locations">List of MarkerID's</param> public GoToEvent(ICollection<Point> locations) { if (locations == null) this.locations = new List<Point>(); else this.locations = new List<Point>(locations); }
/// <summary> /// Initializes the loggly logger /// </summary> /// <param name="session">Current encompass session, used to load the config file</param> /// <param name="config">Config file to load. Will re-initialize when this is used.</param> /// <param name="tags">Collection of loggly tags. If null, we will load the Loggly.Tags element from the config.</param> public static void Init(Session session, IEncompassConfig config, ICollection<string> tags = null) { config.Init(session); if (tags != null) { foreach (string tag in tags) { AddTag(tag); } } foreach (var tag in config.GetValue(LOGGLY_TAGS, string.Empty).Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) { AddTag(tag); } string configLogglyUrl = config.GetValue(LOGGLY_URL); if (configLogglyUrl != null) { SetPostUrl(configLogglyUrl); } bool allEnabled = config.GetValue(LOGGLY_ALL, false); bool errorEnabled = config.GetValue(LOGGLY_ERROR, false); bool warnEnabled = config.GetValue(LOGGLY_WARN, false); bool infoEnabled = config.GetValue(LOGGLY_INFO, false); bool debugEnabled = config.GetValue(LOGGLY_DEBUG, false); bool fatalEnabled = config.GetValue(LOGGLY_FATAL, false); Instance.ErrorEnabled = allEnabled || errorEnabled; Instance.WarnEnabled = allEnabled || warnEnabled; Instance.InfoEnabled = allEnabled || infoEnabled; Instance.DebugEnabled = allEnabled || debugEnabled; Instance.FatalEnabled = allEnabled || fatalEnabled; }
public Vendor(int id, string name) { this.Id = id; this.Name = name; this.parts = new HashSet<Part>(); }
public Vector3 getSteering(Rigidbody2D target, ICollection<Rigidbody2D> obstacles, out Vector3 bestHidingSpot) { //Find the closest hiding spot float distToClostest = Mathf.Infinity; bestHidingSpot = Vector3.zero; foreach(Rigidbody2D r in obstacles) { Vector3 hidingSpot = getHidingPosition(r, target); float dist = Vector3.Distance(hidingSpot, transform.position); if(dist < distToClostest) { distToClostest = dist; bestHidingSpot = hidingSpot; } } //If no hiding spot is found then just evade the enemy if(distToClostest == Mathf.Infinity) { return evade.getSteering(target); } //Debug.DrawLine(transform.position, bestHidingSpot); return steeringBasics.arrive(bestHidingSpot); }
public PublicationModels() { KeyWords = new List <KeyWordModels>(); Authors = new List <AuthorModels>(); Descriptions = new List <PublicationDescriptionModels>(); }
} // StringCollection /// <summary> /// Creates a new instance with all the items of the given collection. /// </summary> /// <param name="collection"> /// the items to add. may not be null. any non-string items /// in this collection will be returned as null when trying to access them later. /// </param> public StringCollection(ICollection collection) { InnerList.AddRange(collection); } // StringCollection
public Meal() { MealOrders = new List<MealOrder>(); }
public ApplicationModule() { RolePermissions = new HashSet<RolePermission>(); }
public VehicleResource() { Features = new Collection <KeyValuePairResource>(); }
public Vehicle() { Features = new Collection<VehicleFeature>(); Photos = new Collection<Photo>(); }
/// <summary> /// Returns a list of all items in the provided item group whose itemspecs match the specification, after it is split and any wildcards are expanded. /// If no items match, returns null. /// </summary> /// <param name="items">The items to match</param> /// <param name="specification">The specification to match against the items.</param> /// <param name="specificationLocation">The specification to match against the provided items</param> /// <param name="expander">The expander to use</param> /// <returns>A list of matching items</returns> private List <ProjectItemInstance> FindItemsMatchingSpecification ( ICollection <ProjectItemInstance> items, string specification, ElementLocation specificationLocation, Expander <ProjectPropertyInstance, ProjectItemInstance> expander ) { if (items.Count == 0 || specification.Length == 0) { return(null); } // This is a hashtable whose key is the filename for the individual items // in the Exclude list, after wildcard expansion. HashSet <string> specificationsToFind = new HashSet <string>(StringComparer.OrdinalIgnoreCase); // Split by semicolons var specificationPieces = expander.ExpandIntoStringListLeaveEscaped(specification, ExpanderOptions.ExpandAll, specificationLocation); foreach (string piece in specificationPieces) { // Take each individual path or file expression, and expand any // wildcards. Then loop through each file returned, and add it // to our hashtable. // Don't unescape wildcards just yet - if there were any escaped, the caller wants to treat them // as literals. Everything else is safe to unescape at this point, since we're only matching // against the file system. string[] fileList = _engineFileUtilities.GetFileListEscaped(Project.Directory, piece); foreach (string file in fileList) { // Now unescape everything, because this is the end of the road for this filename. // We're just going to compare it to the unescaped include path to filter out the // file excludes. specificationsToFind.Add(EscapingUtilities.UnescapeAll(file)); } } if (specificationsToFind.Count == 0) { return(null); } // Now loop through our list and filter out any that match a // filename in the remove list. List <ProjectItemInstance> itemsRemoved = new List <ProjectItemInstance>(); foreach (ProjectItemInstance item in items) { // Even if the case for the excluded files is different, they // will still get excluded, as expected. However, if the excluded path // references the same file in a different way, such as by relative // path instead of absolute path, we will not realize that they refer // to the same file, and thus we will not exclude it. if (specificationsToFind.Contains(item.EvaluatedInclude)) { itemsRemoved.Add(item); } } return(itemsRemoved); }
public static void FillCombo(DropDownList dropDownList, string dataTextField, string dataValueField, ICollection iCollection, bool bHasBlank, bool bMandatory) { dropDownList.DataTextField = dataTextField; dropDownList.DataValueField = dataValueField; dropDownList.DataSource = iCollection; dropDownList.DataBind(); if (bHasBlank) { ListItem oItem = new ListItem(); if (!bMandatory) { oItem.Value = "0"; oItem.Text = "Select"; } dropDownList.Items.Insert(0, oItem); } }
/// <summary> /// Create the results based on the search hits. /// Can be overridden by subclass to add particular behavior (e.g. weight transformation) </summary> /// <exception cref="IOException"> If there are problems reading fields from the underlying Lucene index. </exception> protected internal virtual IList <LookupResult> CreateResults(IndexSearcher searcher, TopFieldDocs hits, int num, string charSequence, bool doHighlight, ICollection <string> matchedTokens, string prefixToken) { BinaryDocValues textDV = MultiDocValues.GetBinaryValues(searcher.IndexReader, TEXT_FIELD_NAME); // This will just be null if app didn't pass payloads to build(): // TODO: maybe just stored fields? they compress... BinaryDocValues payloadsDV = MultiDocValues.GetBinaryValues(searcher.IndexReader, "payloads"); IList <AtomicReaderContext> leaves = searcher.IndexReader.Leaves; List <LookupResult> results = new List <LookupResult>(); BytesRef scratch = new BytesRef(); for (int i = 0; i < hits.ScoreDocs.Length; i++) { FieldDoc fd = (FieldDoc)hits.ScoreDocs[i]; textDV.Get(fd.Doc, scratch); string text = scratch.Utf8ToString(); long score = (long)fd.Fields[0]; BytesRef payload; if (payloadsDV != null) { payload = new BytesRef(); payloadsDV.Get(fd.Doc, payload); } else { payload = null; } // Must look up sorted-set by segment: int segment = ReaderUtil.SubIndex(fd.Doc, leaves); SortedSetDocValues contextsDV = leaves[segment].AtomicReader.GetSortedSetDocValues(CONTEXTS_FIELD_NAME); ISet <BytesRef> contexts; if (contextsDV != null) { contexts = new JCG.HashSet <BytesRef>(); contextsDV.SetDocument(fd.Doc - leaves[segment].DocBase); long ord; while ((ord = contextsDV.NextOrd()) != SortedSetDocValues.NO_MORE_ORDS) { BytesRef context = new BytesRef(); contextsDV.LookupOrd(ord, context); contexts.Add(context); } } else { contexts = null; } LookupResult result; if (doHighlight) { object highlightKey = Highlight(text, matchedTokens, prefixToken); result = new LookupResult(highlightKey.ToString(), highlightKey, score, payload, contexts); } else { result = new LookupResult(text, score, payload, contexts); } results.Add(result); } return(results); }
private List <WordInfo> PickupKeywords(ICollection <WordInfo> keywordsWordInfos, ICollection <WordInfo> contentWordInfos) { List <WordInfo> ret = new List <WordInfo>(); Dictionary <string, bool> dict = new Dictionary <string, bool>(); foreach (WordInfo wordInfo in keywordsWordInfos) { if (wordInfo == null) { continue; } if (!dict.ContainsKey(wordInfo.Word)) { dict.Add(wordInfo.Word, true); } } foreach (WordInfo wordInfo in contentWordInfos) { if (wordInfo == null) { continue; } if (dict.ContainsKey(wordInfo.Word)) { ret.Add(wordInfo); } } ret.Sort(); return(ret); }
private bool TryAuthenticate(ISession session, AuthenticationState authenticationState, ICollection <string> allowedAuthenticationMethods, ref SshAuthenticationException authenticationException) { if (!allowedAuthenticationMethods.Any()) { authenticationException = new SshAuthenticationException("No authentication methods defined on SSH server."); return(false); } // we want to try authentication methods in the order in which they were // passed in the ctor, not the order in which the SSH server returns // the allowed authentication methods var matchingAuthenticationMethods = authenticationState.SupportedAuthenticationMethods.Where(a => allowedAuthenticationMethods.Contains(a.Name)).ToList(); if (!matchingAuthenticationMethods.Any()) { authenticationException = new SshAuthenticationException(string.Format("No suitable authentication method found to complete authentication ({0}).", string.Join(",", allowedAuthenticationMethods.ToArray()))); return(false); } foreach (var authenticationMethod in GetOrderedAuthenticationMethods(authenticationState, matchingAuthenticationMethods)) { if (authenticationState.FailedAuthenticationMethods.Contains(authenticationMethod)) { continue; } // when the authentication method was previously executed, then skip the authentication // method as long as there's another authentication method to try; this is done to avoid // a stack overflow for servers that do not update the list of allowed authentication // methods after a partial success if (!authenticationState.ExecutedAuthenticationMethods.Contains(authenticationMethod)) { // update state to reflect previosuly executed authentication methods authenticationState.ExecutedAuthenticationMethods.Add(authenticationMethod); } var authenticationResult = authenticationMethod.Authenticate(session); switch (authenticationResult) { case AuthenticationResult.PartialSuccess: if (TryAuthenticate(session, authenticationState, authenticationMethod.AllowedAuthentications.ToList(), ref authenticationException)) { authenticationResult = AuthenticationResult.Success; } break; case AuthenticationResult.Failure: authenticationState.FailedAuthenticationMethods.Add(authenticationMethod); authenticationException = new SshAuthenticationException(string.Format("Permission denied ({0}).", authenticationMethod.Name)); break; case AuthenticationResult.Success: authenticationException = null; break; } if (authenticationResult == AuthenticationResult.Success) { return(true); } } return(false); }
public Floor() { Rooms = new HashSet <Room>(); }
public static List <TokenDefinition> Tokenize(string input, ICollection <TokenDefinition> definition, char[] quote_types, bool include_whitespace, bool include_newlines, PreprocessorOptions preopts) { // First run preprocessor passes // Do trigraph replacement if required if (preopts.StandardCTrigraphs) { input = Replace(input, new string[][] { new string[] { "??=", "#" }, new string[] { "??/", "\\" }, new string[] { "??'", "^" }, new string[] { "??(", "[" }, new string[] { "??)", "]" }, new string[] { "??!", "|" }, new string[] { "??<", "{" }, new string[] { "??>", "}" }, new string[] { "??-", "~" }, }, false); } List <TokenDefinition> ret = new List <TokenDefinition>(); if (quote_types == null) { quote_types = new char[] { } } ; char current_quote_type = '\0'; StringBuilder cur_str = new StringBuilder(); int i = 0; // Terminate input with a newline input = input + "\n"; while (i < input.Length) { char c = input[i]; // If we're within a quote, do interpret it if (current_quote_type != '\0') { // Is it the end of the quote? if (c == current_quote_type) { ret.Add(new TokenDefinition(cur_str.ToString())); ret.Add(new TokenDefinition(current_quote_type)); i++; cur_str = new StringBuilder(); current_quote_type = '\0'; continue; } // Is it an escaped character? if (c == '\\') { i++; c = input[i]; cur_str.Append(c); i++; continue; } // Else, add it to the current string cur_str.Append(c); i++; continue; } // Not within a quote // Is it the start of a quote? foreach (char quote_start in quote_types) { if (c == quote_start) { // We're at the start of a quote. AddToken(ret, cur_str.ToString(), include_whitespace, include_newlines); current_quote_type = c; cur_str = new StringBuilder(); i++; continue; } } // Not the start of a quote, is it whitespace? if (IsWhiteSpace(c)) { // Is the current token only whitespace? If so add it if (IsWhiteSpace(cur_str.ToString())) { cur_str.Append(c); i++; continue; } // If not, it marks the end of a string if (cur_str.Length > 0) { // Now try and match the specific strings against this string s = cur_str.ToString(); int j = 0; int str_start = 0; while (j < s.Length) { int chars_left = s.Length - j; bool match = false; foreach (TokenDefinition spec_str in definition) { if ((spec_str.Type == TokenDefinition.def_type.String) && (chars_left >= spec_str.String.Length)) { if (s.Substring(j, spec_str.String.Length) == spec_str.String) { // We have a match // Add the previous string if there was one if (str_start != j) { AddToken(ret, s.Substring(str_start, j - str_start), include_whitespace, include_newlines); } // Add this match AddToken(ret, spec_str.String, include_whitespace, include_newlines); // Advance on beyond this string j = j + spec_str.String.Length; str_start = j; match = true; break; } } } if (!match) { j++; } } // Now add whatever's left if (str_start < s.Length) { AddToken(ret, s.Substring(str_start), include_whitespace, include_newlines); } cur_str = new StringBuilder(); cur_str.Append(c); i++; continue; } } // Its just a regular character // Is the current string just whitespace? if (IsWhiteSpace(cur_str.ToString())) { AddToken(ret, cur_str.ToString(), include_whitespace, include_newlines); cur_str = new StringBuilder(); } cur_str.Append(c); i++; continue; } // Now remove comments i = 0; int starting_comment_token = 0; PreprocessorOptions.CommentsType cur_comment = null; while (i < ret.Count) { TokenDefinition tok = ret[i]; // Are we currently in a comment? if (cur_comment != null) { // Do we match the end comment marker? if (((cur_comment.End == null) && (tok.Type == TokenDefinition.def_type.Newline)) || ((cur_comment.End == tok.String) && (tok.Type == TokenDefinition.def_type.String))) { // Remove tokens from starting_comment_token up to and including i ret.RemoveRange(starting_comment_token, i - starting_comment_token + 1); i = starting_comment_token; // Reinsert the newline if we removed one if (cur_comment.End == null) { ret.Insert(i, new TokenDefinition(TokenDefinition.def_type.Newline)); i++; } cur_comment = null; continue; } else { i++; continue; } } else { // Do we match a new comment start? if ((tok.Type == TokenDefinition.def_type.String) && (preopts.Comments != null)) { foreach (PreprocessorOptions.CommentsType ct in preopts.Comments) { if (ct.Start == tok.String) { cur_comment = ct; starting_comment_token = i; } } } } // Continue i++; } // If still in a comment, remove the last tokens if (cur_comment != null) { ret.RemoveRange(starting_comment_token, i - starting_comment_token); } // Now parse looking for #define, #include etc // First add a newline at the start if not already there, to assist searching on 'Newline' '#' 'include' etc if (!((ret.Count > 0) && (ret[0].Type == TokenDefinition.def_type.Newline))) { ret.Insert(0, new TokenDefinition(TokenDefinition.def_type.Newline)); } i = 0; while (i < ret.Count) { // TODO if (preopts.Includes && Match(ret, PreprocessorOptions.IncludeDefinition, i)) { } i++; } // Now remove the newline again ret.RemoveAt(0); // Terminate with a newline ret.Add(new TokenDefinition(TokenDefinition.def_type.Newline)); return(ret); }
/// <summary> /// Set all of the specified element's class names, and returns the element itself. /// </summary> /// <param name="self"> /// The input <see cref="Element"/>, /// which acts as the <b>this</b> instance for the extension method. /// </param> /// <param name="classNames">the new set of classes</param> /// <returns>The input <see cref="Element"/>, for method chaining.</returns> /// <seealso cref="Element.ClassNames">Element.ClassNames</seealso> public static Element ClassNames(this Element self, ICollection<string> classNames) { self.ClassNames = classNames; return self; }
internal KeyCollection(ICollection <TKey> collection) { }
public void Flatten(ICollection <float> points, int maxNumberOfIterations, float tolerance) { points.Add(Point1); points.Add(Point2); }
public TicketType() { Tickets = new HashSet<Ticket>(); }
/// <summary> /// Performs the disposal. /// </summary> /// <param name="sessions">The sessions.</param> protected virtual void PerformDisposal(ICollection <ISession> sessions) { }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { ICollection <string> errors = value as ICollection <string>; return(errors != null && errors.Count > 0 ? errors.ElementAt(0) : null); }
public ApplicationUser() { this.Products = new HashSet <Product>(); }
public Player(string name, ChessColor color) { this._figures = new List<IFigure>(); this.Color = color; this.Name = name; }
protected void RefreshTariffs(int day) { _CurrentContracts = _CurrentContracts .Select(x => x.Date.Day == day ? new Contract(x.Number, x.TariffPlan.GetNewInstance(), x.Date) : x) .ToList(); }
internal protected UnrecognizedAssertionsBindingElement(XmlQualifiedName wsdlBinding, ICollection <XmlElement> bindingAsserions) { Fx.Assert(wsdlBinding != null, ""); _wsdlBinding = wsdlBinding; _bindingAsserions = bindingAsserions; }
public DynamicArray(ICollection <T> Collection) //3 { array = new T[Collection.Count]; Collection.CopyTo(array, 0); }
public static int GetRandomIndexMinimum <T>(this ICollection <T> collection, int startIndex) { return(RandomFactory.GetInstance().Next(startIndex, collection.Count)); }
public ErrorModel(string header, ICollection<string> errorMessagesList, ICollection<string> errorKeysList) { Header = header; ErrorMessagesList = errorMessagesList; ErrorKeysList = errorKeysList; }
public Proposal() { this.votes = new HashSet <Vote>(); }
public static T GetRandomElement <T>(this ICollection <T> collection) { var randomIndex = RandomFactory.GetInstance().Next(collection.Count); return(collection.ElementAtOrDefault(randomIndex)); }
public MappingException(ICollection appendToMessageItems, string formatString, params object[] args) : base(appendToMessageItems, formatString, args) { }
public static int GetRandomIndex <T>(this ICollection <T> collection) { return(RandomFactory.GetInstance().Next(collection.Count)); }