private static void InitializeDocumentStore() { DocumentStore = new List<User>(); DocumentStore.Add(new User { Username = "******" }); DocumentStore.Add(new User { Username = "******" }); DocumentStore.Add(new User { Username = "******" }); DocumentStore.Add(new User { Username = "******" }); DocumentStore.Add(new User { Username = "******" }); DocumentStore.Add(new User { Username = "******" }); DocumentStore.Add(new User { Username = "******" }); }
public override void AddEffectsInfo(IList<string> list) { list.Add("25% Group power refresh."); list.Add(""); list.Add("Target: Group"); list.Add("Casting time: instant"); }
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { Proveedores = new Dictionary<string, int>(); Unidades = new Dictionary<string, int>(); TipoSuministro = new List<string>(); Proveedores = cProveedor.ListarDicProveedores(); IList<Unidad> unidades = cUnidad.ListarUnidades(); foreach (var unit in unidades) { Unidades.Add(unit.NombreUnidad, unit.UnidadId); } TipoSuministro.Add("Medio de Cultivo"); TipoSuministro.Add("Reactivo Quimico"); TipoSuministro.Add("Material"); selectTipoSuministro.DataSource = TipoSuministro; selectTipoSuministro.DataBind(); selectProveedor.DataSource = Proveedores; selectProveedor.DataTextField = "Key"; selectProveedor.DataValueField = "Value"; selectProveedor.DataBind(); selectUnidad.DataSource = Unidades; selectUnidad.DataTextField = "Key"; selectUnidad.DataValueField = "Value"; selectUnidad.DataBind(); } }
public BushService() { _bushes = new List<BushModel>(); _bushes.Add(new BushModel() {Id = 1, Genus = "Forsythia"}); _bushes.Add(new BushModel() {Id = 2, Genus = "Hydrangea"}); _bushes.Add(new BushModel() {Id = 3, Genus = "Buddleia"}); }
public AIMoveStore(Transform chess) { Chess = chess; CharacterProperty chessP = chess.GetComponent<CharacterProperty>(); CmdsLeft = new List<UICommands>(); CmdsUsed = new List<UICommands>(); if(!chessP.Moved) CmdsLeft.Add(UICommands.Move); else if(!chessP.Defensed) CmdsUsed.Add(UICommands.Move); if(!chessP.Attacked) CmdsLeft.Add(UICommands.Attack); else if(!chessP.Defensed) CmdsUsed.Add(UICommands.Attack); if(!chessP.Activated) CmdsLeft.Add(UICommands.Skill); else CmdsUsed.Add(UICommands.Skill); if(!chessP.Defensed) CmdsLeft.Add(UICommands.Defense); else CmdsUsed.Add(UICommands.Defense); if(chessP.Summoner) CmdsLeft.Add(UICommands.Summon); }
public void Select(IList<IIndividual> Individuals, int firstSize, int secondSize) { ElitismSelection eliteSelection = new ElitismSelection(); WheelSelection wheelSelection = new WheelSelection(); IList<IIndividual> eliteIndividuals = new List<IIndividual>(); IList<IIndividual> wheelIndividuals = new List<IIndividual>(); (Individuals as List<IIndividual>).ForEach( i => { eliteIndividuals.Add(i.Clone()); wheelIndividuals.Add(i.Clone()); } ); eliteSelection.Select(eliteIndividuals, firstSize); wheelSelection.Select(wheelIndividuals, secondSize); Individuals.Clear(); (eliteIndividuals as List<IIndividual>).ForEach( i => Individuals.Add(i) ); (wheelIndividuals as List<IIndividual>).ForEach( i => Individuals.Add(i) ); }
public virtual void SaveAllProperties(IList<KeyValuePair<string, object>> output) { output.Add(new KeyValuePair<string, object>("name", this.Name)); if (this.Content != null) output.Add(new KeyValuePair<string, object>("content", this.Content)); }
public override void PopulateStrEntries(IList<StrEntry> strEntries) { PopulateJan2004StrEntries(strEntries); strEntries.Add(new SamlDirectStrEntry()); strEntries.Add(new X509ThumbprintStrEntry(this.SecurityTokenSerializer.EmitBspRequiredAttributes)); strEntries.Add(new EncryptedKeyHashStrEntry(this.SecurityTokenSerializer.EmitBspRequiredAttributes)); }
public override void AddEffectsInfo(IList<string> list) { list.Add("Decrease Paladin stats by 25%, and pulse a 300 points group heal with a 750 units range every 3 seconds for 15 seconds total."); list.Add(""); list.Add("Duration: 15 sec"); list.Add("Casting time: instant"); }
public static void AddEqStatement(string fieldName, object fieldValue, string fieldAlias, ref string whereStatement, IList<object> param) { if (fieldValue == null) { return; } if (fieldValue.GetType() != typeof(string) || !string.IsNullOrWhiteSpace((string)fieldValue)) { if (!string.IsNullOrWhiteSpace(fieldAlias)) { fieldName = fieldAlias + "." + fieldName; } if (whereStatement == string.Empty) { whereStatement = " where " + fieldName + " = ?"; } else { whereStatement += " and " + fieldName + " = ?"; } if (fieldValue.GetType() == typeof(string)) { param.Add(fieldValue.ToString().Trim()); } else { param.Add(fieldValue); } } }
public CalculadorPreco() { regras = new List<IRegraPreco>(); regras.Add(new RegraPrecoEspecial()); regras.Add(new RegraPrecoPorGrama()); regras.Add(new RegraPrecoCada()); }
public void Execute(IDice dice, Combatant attacker, Combatant defender, IList<CombatLogEntry> combatLog) { int attack = attacker.ToHitAttack; int defend = defender.ToHitDefense; var toHitThreshold = ((attack + ((attacker.Level - defender.Level) / 2)) / ((double)attack + defend)).ConstrainWithinBounds(0.20, 0.80); Debug.WriteLine("{0} has a {1:P0} chance to hit {2}", attacker.Name, toHitThreshold, defender.Name); if (dice.Random() < toHitThreshold) { var damage = Math.Max(1, attacker.GetAttackDamage(dice)); defender.LowerHealth(damage); combatLog.Add(new CombatLogEntryFromAction<Attack>(Name) { Text = string.Format("{0} hits {1} with {2} for {3} points!", attacker.Name, defender.Name, Name, damage), Attacker = attacker, CombatEffect = new CombatOutcome() { Damage = damage } }); } else { combatLog.Add( new CombatLogEntry { Text = string.Format("{0} attempts to hit {1} with {2} and fails miserably!", attacker.Name, defender.Name, Name), Attacker = attacker }); } }
public SafeDirectoryCatalog(string path) { exceptions = new List<Exception>(); var files = Directory.EnumerateFiles(GetFullPath(path), "*.dll", SearchOption.AllDirectories); aggregateCatalog = new AggregateCatalog(); foreach (var file in files) { try { var assemblyCatalog = new AssemblyCatalog(file); if (assemblyCatalog.Parts.ToList().Count > 0) aggregateCatalog.Catalogs.Add(assemblyCatalog); } catch (ReflectionTypeLoadException ex) { foreach (var exception in ex.LoaderExceptions) { exceptions.Add(exception); } } catch (Exception ex) { exceptions.Add(ex); } } }
public DatadogSeries(string name, long epoch, IDictionary<string,string> additionalTags) { this.Tags = new List<string>(); if (!name.Contains("[")) { Name = name; } else { int index = name.IndexOf("[", 0); Name = name.Substring(0, index); string tags = name.Substring(index + 1, name.Length - index - 2); foreach (string t in tags.Split(_tagSplit, StringSplitOptions.None)) { Tags.Add(t); } } if (additionalTags != null && additionalTags.Count > 0) { foreach (string tag in additionalTags.Keys) { Tags.Add(tag + ":" + additionalTags[tag]); } } this.Epoch = epoch; //this._host = host; }
protected void PopulateJan2004TokenEntries(IList<TokenEntry> tokenEntryList) { tokenEntryList.Add(new GenericXmlTokenEntry()); tokenEntryList.Add(new UserNamePasswordTokenEntry(this.tokenSerializer)); tokenEntryList.Add(new KerberosTokenEntry(this.tokenSerializer)); tokenEntryList.Add(new X509TokenEntry(this.tokenSerializer)); }
private bool HandleVariables(IList<object> qiContent, ref ITrackingSpan applicableToSpan, IList<ClassificationSpan> spans, SnapshotPoint? point) { ClassificationSpan span; string text = GetText(spans, point, PredefinedClassificationTypeNames.SymbolDefinition, out span); if (string.IsNullOrWhiteSpace(text)) return false; string value = Environment.GetEnvironmentVariable(text.Trim('%')); if (string.IsNullOrEmpty(value)) return false; string displayText = value; if (value.Equals("path", StringComparison.OrdinalIgnoreCase)) displayText = string.Join(Environment.NewLine, value.Split(';')); applicableToSpan = _buffer.CurrentSnapshot.CreateTrackingSpan(span.Span, SpanTrackingMode.EdgeNegative); qiContent.Add(displayText); string expanded = Environment.ExpandEnvironmentVariables(value); if (expanded != value) qiContent.Add(expanded); return true; }
public Tape(String initialiser) { mSymbols = new List<char>(); String[] initialiserLines = initialiser.Split('\n'); foreach (String character in initialiserLines[0].Split(',')) { if(String.IsNullOrEmpty(character)) { mSymbols.Add(' '); } else { mSymbols.Add(character[0]); } } mIndex = 0; if (initialiserLines.Length > 1) { string headPosition = initialiser.Split('\n')[1]; if (!String.IsNullOrEmpty(headPosition)) { mIndex = Int32.Parse(headPosition); } } }
private static IEnumerable<int> GenerateTermsForSeed(int seed, IList<int> terms) { if (!terms.Contains(seed)) { terms.Add(seed); } var current = seed; while (current != 1) { if (current < 0) { break; } // 256 128 64 32 16 8 4 2 1 if (current % 2 == 0) { current = current / 2; } else { current = (3 * current) + 1; } if (terms.Contains(current)) break; terms.Add(current); } return terms; }
public string FindGame(IList <string> errors = null) { string steamPath = (string)ReadRegistrySafe("Software\\Valve\\Steam", "SteamPath"); if (string.IsNullOrEmpty(steamPath)) { errors?.Add("It appears you don't have Steam installed."); return(null); } string appsPath = Path.Combine(steamPath, "steamapps"); if (File.Exists(Path.Combine(appsPath, $"appmanifest_{SUBNAUTICA_APP_ID}.acf"))) { return(Path.Combine(appsPath, "common", SUBNAUTICA_GAME_NAME)); } string path = SearchAllInstallations(Path.Combine(appsPath, "libraryfolders.vdf"), SUBNAUTICA_APP_ID, SUBNAUTICA_GAME_NAME); if (string.IsNullOrEmpty(path)) { errors?.Add($"It appears you don't have {SUBNAUTICA_GAME_NAME} installed anywhere. The game files are needed to run the server."); } else { return(path); } return(null); }
public PgpPublicKeyRing( Stream inputStream) { this.keys = Platform.CreateArrayList(); BcpgInputStream bcpgInput = BcpgInputStream.Wrap(inputStream); PacketTag initialTag = bcpgInput.NextPacketTag(); if (initialTag != PacketTag.PublicKey && initialTag != PacketTag.PublicSubkey) { throw new IOException("public key ring doesn't start with public key tag: " + "tag 0x" + ((int)initialTag).ToString("X")); } PublicKeyPacket pubPk = (PublicKeyPacket) bcpgInput.ReadPacket();; TrustPacket trustPk = ReadOptionalTrustPacket(bcpgInput); // direct signatures and revocations IList keySigs = ReadSignaturesAndTrust(bcpgInput); IList ids, idTrusts, idSigs; ReadUserIDs(bcpgInput, out ids, out idTrusts, out idSigs); keys.Add(new PgpPublicKey(pubPk, trustPk, keySigs, ids, idTrusts, idSigs)); // Read subkeys while (bcpgInput.NextPacketTag() == PacketTag.PublicSubkey) { keys.Add(ReadSubkey(bcpgInput)); } }
public void UserGroupDropDownList(IList<UserGroup> _userGroup) { NpgsqlDataReader _dr = null; DataBaseHelper _db = new DataBaseHelper(Command, CommandType.Text); try { _dr = _db.ExecuteReader(returnParam()); _userGroup.Add(new UserGroup(0, "Select Group")); while (_dr.Read()) { _userGroup.Add(new UserGroup(int.Parse(_dr[0].ToString()), _dr[1].ToString())); } } catch (Exception ex) { throw new Exception(" :: " + ex.Message); } finally { if (_dr != null) { _db = null; _dr = null; _userGroup = null; } } }
public string FindGame(IList <string> errors = null) { string steamPath = RegistryEx.Read <string>(@"Software\\Valve\\Steam\SteamPath"); if (string.IsNullOrEmpty(steamPath)) { errors?.Add("It appears you don't have Steam installed."); return(null); } string appsPath = Path.Combine(steamPath, "steamapps"); if (File.Exists(Path.Combine(appsPath, $"appmanifest_{GameInfo.Subnautica.SteamAppId}.acf"))) { return(Path.Combine(appsPath, "common", GameInfo.Subnautica.Name)); } string path = SearchAllInstallations(Path.Combine(appsPath, "libraryfolders.vdf"), GameInfo.Subnautica.SteamAppId, GameInfo.Subnautica.Name); if (string.IsNullOrEmpty(path)) { errors?.Add($"It appears you don't have {GameInfo.Subnautica.Name} installed anywhere. The game files are needed to run the server."); } else { return(path); } return(null); }
// Arg(ControllerName),Param(..),.. -> Arg(ControllerName),Arg('Index'),... public static IList<Token> Rewrite(IList<Token> tokens) { //"--command" if (tokens.Count() >= 2 && tokens[0].TokenType==TokenType.Argument && tokens[0].Value.EqualsIC("help") && tokens[1].TokenType==TokenType.Argument) { tokens[1] = new Token(tokens[1].Value,TokenType.ParameterValue,tokens[1].Index); tokens.Insert(1,new Token("command",TokenType.Parameter,1)); //index:2 if (tokens.Count() >= 4) { tokens[3] = new Token(tokens[3].Value, TokenType.ParameterValue, tokens[1].Index); } tokens.Insert(3, new Token("action", TokenType.Parameter, 2)); } //help maps to index (should have routing here) if (tokens.Count() == 0) { tokens.Add(new Token("help",TokenType.Argument,0)); } //Index rewrite: var indexToken= new Token("Index", TokenType.Argument,1); if (tokens.Count()>=2 && tokens[1].TokenType!=TokenType.Argument && tokens[0].TokenType==TokenType.Argument) { tokens.Insert(1,indexToken); } else if (tokens.Count()==1 && tokens[0].TokenType==TokenType.Argument) { tokens.Add(indexToken); } return tokens; }
private void InitializeFakeEmployeeRepository() { Employees = new List<EmployeeReport>(); Employees.Add(new EmployeeReport {Id = Guid.NewGuid(), Name = "Jens Pettersson", Available = false}); Employees.Add(new EmployeeReport {Id = Guid.NewGuid(), Name = "Mr Sir Developer", Available = true}); }
private void BuildCategoryDetails( org.apache.lucene.facet.Facets facets, IList<CategoryDetail> categoryDetails, CategoryOptions categoryOptions, string categoryName, string[] label, int count, IEnumerable<string> drillDownValues) { var lastLabel = label.Last(); if (!drillDownValues.Contains(lastLabel)) { categoryDetails.Add(new CategoryDetail { Value = lastLabel, Count = count }); //logger.Info("Value = {2} -- {0}; Count = {1}", lastLabel, count, String.Join("_ ", label)); } else { var drilldownFacets = facets.getTopChildren(categoryOptions.MaxPerCategory, categoryName, label); if (drilldownFacets != null) { var valDetail = new CategoryDetail { Value = lastLabel, Count = count }; categoryDetails.Add(valDetail); foreach (var lv in drilldownFacets.labelValues) { var childLabel = new List<string>(label); childLabel.Add(lv.label); BuildCategoryDetails( facets, valDetail.Children, categoryOptions, categoryName, childLabel.ToArray(), lv.value.intValue(), drillDownValues); } } } }
public override void SaveAllProperties(IList<KeyValuePair<string, object>> output) { output.Add(new KeyValuePair<string, object>("rows", this.Rows)); output.Add(new KeyValuePair<string, object>("cols", this.Columns)); base.SaveAllProperties(output); }
private void Fill(IList list) { list.Add(1); list.Add(null); list.Add(new AtomData("foo")); list.Add("foo"); }
public void PatternDropDownList(IList<Pattern> _Pattern) { NpgsqlDataReader _dr = null; DataBaseHelper _db = new DataBaseHelper(Command, CommandType.Text); try { _dr = _db.ExecuteReader(returnParam()); _Pattern.Add(new Pattern(0, "Select Pattern")); while (_dr.Read()) { _Pattern.Add(new Pattern(int.Parse(_dr[0].ToString()), _dr[1].ToString())); } } catch (Exception ex) { throw new Exception(" :: " + ex.Message); } finally { if(_dr!=null) { _db = null; _dr=null; _Pattern = null; } } }
protected override void ValidateCore(object instance, string value, IList<ValidationResult> results) { if (!String.IsNullOrEmpty(value)) { var selectedSourceProperty = (ElementReferenceProperty)instance; if (selectedSourceProperty.ReferencedElement == null) return; if (typeof(SystemConfigurationSourceElement) != selectedSourceProperty.ReferencedElement.ConfigurationType) { var containingSection = (ConfigurationSourceSectionViewModel)selectedSourceProperty.ContainingSection; if (!String.IsNullOrEmpty((string)containingSection.Property("ParentSource").Value)) { results.Add(new PropertyValidationResult( selectedSourceProperty, Resources.WarningSelectedSourceCannotBeUsedInCombinationWithParentSource, true)); } if (containingSection.DescendentElements().Any(x => typeof(RedirectedSectionElement).IsAssignableFrom(x.ConfigurationType))) { results.Add(new PropertyValidationResult( selectedSourceProperty, Resources.WarningSelectedSourceCannotBeUsedInCombinationWithRedirects, true)); } } } }
public RampGradient(int lengthX, int lengthY, IList<RampGradientDivision> divisionsX = null, IList<RampGradientDivision> divisionsY = null, GenerationCalculationType generationCalculationType = GenerationCalculationType.Average) : base(lengthX, lengthY) { _divisionsX = divisionsX == null ? new List<RampGradientDivision>() : new List<RampGradientDivision>(divisionsX); _divisionsY = divisionsY == null ? new List<RampGradientDivision>() : new List<RampGradientDivision>(divisionsY); _generationCalculationType = generationCalculationType; if(_divisionsX.Count == 0 && _divisionsY.Count == 0) { _divisionsX.Add( new RampGradientDivision() { Point = 0f, Value = 0f }); _divisionsX.Add( new RampGradientDivision() { Point = LengthX, Value = 1f }); _divisionsY.Add( new RampGradientDivision() { Point = 0f, Value = 0f }); _divisionsY.Add( new RampGradientDivision() { Point = LengthY, Value = 1f }); } }
/// <summary> /// Verifies the given path against the given definition's constraints /// </summary> /// <param name="def">Constraint source</param> /// <param name="layer">Layer to use for node snapping, or null</param> /// <param name="nodes">Nodes in path</param> /// <param name="errors">Destination for all errors that occurred, or null</param> /// <returns>true if the path is valid</returns> public static bool ValidatePath(BendyComponentDefinition def, BendyLayer layer, IList <AnnotatedNode> nodes, IList <string> errors) { if (nodes.Count <= 1) { errors?.Add("Not enough points to form a path"); return(false); } if (nodes.Count >= RailConstants.MaxNodesPlaced) { errors?.Add($"Can't place more than {RailConstants.MaxNodesPlaced} nodes at once"); return(false); } for (var i = 1; i < nodes.Count; i++) { if (!VerifyEdge(def, nodes[i - 1], nodes[i], errors) && errors == null) { return(false); } } return(errors == null || errors.Count == 0); }
public override void AddEffectsInfo(IList<string> list) { list.Add(LanguageMgr.GetTranslation(ServerProperties.Properties.SERV_LANGUAGE, "DashingDefenseAbility.AddEffectsInfo.Info1")); list.Add(""); list.Add(LanguageMgr.GetTranslation(ServerProperties.Properties.SERV_LANGUAGE, "DashingDefenseAbility.AddEffectsInfo.Info2")); list.Add(LanguageMgr.GetTranslation(ServerProperties.Properties.SERV_LANGUAGE, "DashingDefenseAbility.AddEffectsInfo.Info3")); }
static EmployeeRepository() { employees = new List<Employee>(); employees.Add(new Employee("001", "张三", "男",new DateTime(1981, 8, 24), "销售部")); employees.Add(new Employee("002", "李四", "女",new DateTime(1982, 7, 10), "人事部")); employees.Add(new Employee("003", "王五", "男",new DateTime(1981, 9, 21), "人事部")); }
public IEnumerable <T> AdvanceRange() { while (MoveNext()) { yield return(Current); _storage?.Add(Current); } IsFinished = true; }
/// <summary> /// 동기 커맨드 생성(With. ThrownExceptions) /// 반환값 없는 커맨드 실행 메소드(or Unit -> Unit 리턴 메소드는 궂이 리턴을 하지 않아도 상관이 없음) /// </summary> /// <typeparam name="TParam"></typeparam> /// <param name="action">구현 메소드(파라미터 : TParam)</param> /// <param name="loggerAction">로그(예외) 구현 메소드</param> /// <param name="canExcute">커맨드 활성 유무</param> /// <param name="disposers">IList<IDisposable> 객체 -> ThrownExceptions.Subscribe()는 IDisposable 을 반환. ThrownExceptions을 구독하는 델리게이트 해제하기 위함. </param> /// <returns></returns> public static ReactiveCommand <TParam, Unit> CreateCommandWithThrownEx <TParam>(Action <TParam> action, Action <Exception> loggerAction, IObservable <bool> canExcute = null, IList <IDisposable> disposers = null, bool addExcute = true) { var command = ReactiveCommand.Create(action, canExcute); disposers?.Add(command.ThrownExceptions.Subscribe(e => loggerAction(e))); if (addExcute) { disposers?.Add(command); } return(command); }
/// <summary> /// 비동기 커맨드 생성(With. ThrownExceptions) /// 커맨드 실행 메소드의 반화 값 IObservable /// </summary> /// <typeparam name="TResult"></typeparam> /// <param name="func">구현 메소드(반환값 : TResult)</param> /// <param name="loggerAction">로그(예외) 구현 메소드</param> /// <param name="canExcute">커맨드 활성 유무</param> /// <param name="disposers">IList<IDisposable> 객체 -> ThrownExceptions.Subscribe()는 IDisposable 을 반환. ThrownExceptions을 구독하는 델리게이트 해제하기 위함. </param> /// <returns></returns> public static ReactiveCommand <Unit, TResult> CreateAsyncCommandWithThrownEx <TResult>(Func <IObservable <TResult> > func, Action <Exception> loggerAction, IObservable <bool> canExcute = null, IList <IDisposable> disposers = null, bool addExcute = true) { var command = ReactiveCommand.CreateFromObservable(func, canExcute); disposers?.Add(command.ThrownExceptions.Subscribe(e => loggerAction(e))); if (addExcute) { disposers?.Add(command); } return(command); }
/// <summary> /// Divides an array of Individuals into the Pareto front and the "nonFront" (everyone else). /// The Pareto front is returned. You may provide Lists for the front and a nonFront. /// If you provide null for the front, a List will be created for you. If you provide /// null for the nonFront, non-front individuals will not be added to it. This algorithm is O(n^2). /// </summary> public static IList <Individual> PartitionIntoParetoFront(IList <Individual> inds, IList <Individual> front, IList <Individual> nonFront) { if (front == null) { front = new List <Individual>(); } // put the first guy in the front front.Add(inds[0]); // iterate over all the remaining individuals for (var i = 1; i < inds.Count; i++) { var ind = inds[i]; var noOneWasBetter = true; var frontSize = front.Count; // iterate over the entire front for (var j = 0; j < frontSize; j++) { var frontmember = front[j]; // if the front member is better than the individual, dump the individual and go to the next one if (((MultiObjectiveFitness)frontmember.Fitness).ParetoDominates( (MultiObjectiveFitness)ind.Fitness)) { nonFront?.Add(ind); noOneWasBetter = false; break; // failed. He's not in the front } // if the individual was better than the front member, dump the front member. But look over the // other front members (don't break) because others might be dominated by the individual as well. if (((MultiObjectiveFitness)ind.Fitness).ParetoDominates( (MultiObjectiveFitness)frontmember.Fitness)) { Yank(j, front); // a front member is dominated by the new individual. Replace him frontSize--; // member got removed j--; // because there's another guy we now need to consider in his place nonFront?.Add(frontmember); } } if (noOneWasBetter) { front.Add(ind); } } return(front); }
public static int Remove( IList <IndexRange>?ranges, IndexRange range, IList <IndexRange>?removed = null) { if (ranges is null) { return(0); } var result = 0; for (var i = 0; i < ranges.Count; ++i) { var existing = ranges[i]; if (range.Intersects(existing)) { if (range.Begin <= existing.Begin && range.End >= existing.End) { ranges.RemoveAt(i--); removed?.Add(existing); result += existing.Count; } else if (range.Begin > existing.Begin && range.End >= existing.End) { ranges[i] = new IndexRange(existing.Begin, range.Begin - 1); removed?.Add(new IndexRange(range.Begin, existing.End)); result += existing.End - (range.Begin - 1); } else if (range.Begin > existing.Begin && range.End < existing.End) { ranges[i] = new IndexRange(existing.Begin, range.Begin - 1); ranges.Insert(++i, new IndexRange(range.End + 1, existing.End)); removed?.Add(range); result += range.Count; } else if (range.End <= existing.End) { var remove = new IndexRange(existing.Begin, range.End); ranges[i] = new IndexRange(range.End + 1, existing.End); removed?.Add(remove); result += remove.Count; } } } return(result); }
public static void Push <T>(this IList <T> list, T item) { if (item != null) { list?.Add(item); } }
/// <summary> /// Adds the given filter command to the list of /// filters if it isn't null. /// </summary> /// <param name="filterCommands">The list of filters to add to.</param> /// <param name="command">The filter command to add.</param> private void AddFilterCommand(IList <FilterCommand> filterCommands, FilterCommand command) { if (command != null) { filterCommands?.Add(command); } }
private static void InternalAddDirectory(ZipArchive zipArchive, DirectoryInfoBase directory, ITracer tracer, string directoryNameInArchive, IList <ZipArchiveEntry> files = null) { bool any = false; foreach (var info in directory.GetFileSystemInfos()) { any = true; var subDirectoryInfo = info as DirectoryInfoBase; if (subDirectoryInfo != null) { string childName = ForwardSlashCombine(directoryNameInArchive, subDirectoryInfo.Name); InternalAddDirectory(zipArchive, subDirectoryInfo, tracer, childName, files); } else { var entry = zipArchive.AddFile((FileInfoBase)info, tracer, directoryNameInArchive); files?.Add(entry); } } if (!any) { // If the directory did not have any files or folders, add a entry for it zipArchive.CreateEntry(EnsureTrailingSlash(directoryNameInArchive)); } }
async Task AddTodoItem(string newTodoText) { todos?.Add(new ListItemViewModel { Text = newTodoText }); await LoadTodoItems(hideIfDone); }
/// <summary> /// Processes conditional (when) effects. /// </summary> /// <param name="expression">Conditions expression in CNF.</param> /// <param name="relevantConditionalEffects">Output indices of relevant conditional effects (can be null).</param> /// <returns>Tuple of two values, where the first is true when the positive relevance condition (inclusion) is satisfied, while the second is /// true when the negative condition (exclusion) is not violated. False otherwise.</returns> private Tuple <bool, bool> ProcessWhenEffects(ConditionsCNF expression, IList <int> relevantConditionalEffects) { bool positiveCondition = false; int whenEffectIndex = -1; foreach (var whenEffect in Effects.WhenEffects) { ++whenEffectIndex; List <IEffect> subEffects = new List <IEffect>(); whenEffect.Effects.ForEach(subEffect => subEffects.Add(subEffect)); EffectsRelevanceConditionsEvaluator evaluator = new EffectsRelevanceConditionsEvaluator(subEffects, GroundingManager); var result = evaluator.EvaluateWithExtendedResult(expression, OperatorSubstitution, ExpressionSubstitution, relevantConditionalEffects); if (!result.Item2) { continue; } if (result.Item1 && result.Item2) { relevantConditionalEffects?.Add(whenEffectIndex); } positiveCondition |= result.Item1; } return(Tuple.Create(positiveCondition, true)); }
private CellRangeReference GetCellRangeReference(IXLRange range) { var res = new CellRangeReference(range, this); _cellRanges?.Add(res.Range); return(res); }
private void SetDynamicObject(DataTable sqlTable) { var tempObj = new ExpandoObject() as IDictionary <string, Object>; if (sqlTable.Rows.Count > 0) //If there's no data no need to create the object. Just return an Empty IDictionary { int columnIndex = 0; foreach (DataColumn col in sqlTable.Columns) { string columnName = col.ColumnName; tempObj.Add(columnName, null); tempObj[columnName] = Helper.Lists.InstantiateDynamicList(sqlTable.Rows[0].ItemArray[columnIndex++]); } foreach (DataRow row in sqlTable.Rows) { int rowIndex = 0; foreach (object item in row.ItemArray) { string columnName = tempObj.ElementAt(rowIndex++).Key; IList listPtr = (IList)tempObj[columnName]; listPtr?.Add(item); } } } obj = tempObj; }
/// <summary> /// Processes conditional (when) effects. /// </summary> /// <param name="relativeState">Relative state.</param> /// <param name="relevantConditionalEffects">Output indices of relevant conditional effects (can be null).</param> /// <returns>Effect relevance (relevant, irrelevant, or anti-relevant).</returns> private EffectRelevance ProcessWhenEffects(IRelativeState relativeState, IList <int> relevantConditionalEffects = null) { bool anyRelevant = false; int whenEffectIndex = -1; foreach (var whenEffect in Effects.WhenEffects) { ++whenEffectIndex; List <IEffect> subEffects = new List <IEffect>(); whenEffect.Effects.ForEach(subEffect => subEffects.Add(subEffect)); EffectsRelevanceRelativeStateEvaluator evaluator = new EffectsRelevanceRelativeStateEvaluator(subEffects, GroundingManager); var result = evaluator.EvaluateInternal(relativeState, OperatorSubstitution, relevantConditionalEffects); if (result == EffectRelevance.ANTI_RELEVANT) { // anti-relevant conditional effect -> can't be used (but it doesn't have to be, we just ignore it) continue; } if (result == EffectRelevance.RELEVANT) { relevantConditionalEffects?.Add(whenEffectIndex); anyRelevant = true; } } return((anyRelevant) ? EffectRelevance.RELEVANT : EffectRelevance.IRRELEVANT); }
/// <summary> /// Generates a series of commits. /// </summary> /// <param name="numberCommits">The number of commits to generate.</param> /// <param name="directory">The directory of the repository.</param> /// <param name="local">The repository manager for the repository.</param> /// <param name="branchName">The branch name to add the commits into.</param> /// <param name="commitMessages">A optional output list which is populated with the commit messages.</param> private static void GenerateCommits( int numberCommits, string directory, IGitProcessManager local, string branchName, IList <string> commitMessages = null) { if (branchName != "master") { local.RunGit(new[] { $"branch {branchName}" }).FirstOrDefaultAsync().Wait(); } try { local.RunGit(new[] { $"checkout {branchName}" }).Wait(); } catch (GitProcessException) { // Ignored } for (var i = 0; i < numberCommits; ++i) { File.WriteAllText(Path.Combine(directory, Path.GetRandomFileName()), @"Hello World" + i); local.RunGit(new[] { "add -A" }).FirstOrDefaultAsync().Wait(); commitMessages?.Add($"Commit {branchName}-{i}"); local.RunGit(new[] { $"commit -m \"Commit {branchName}-{i}\"" }).FirstOrDefaultAsync().Wait(); } }
private Type GetParameterType(Type baseClass, IList <Type> typeHierarchy, Type clazz, int returnParamPos) { typeHierarchy?.Add(clazz); var interfaceTypes = clazz.GetInterfaces().Where(it => it.IsGenericType); // search in interfaces for base class foreach (var t in interfaceTypes) { var parameter = GetParameterTypeFromGenericType(baseClass, typeHierarchy, t, returnParamPos); if (parameter != null) { return(parameter); } } // search in superclass for base class var t1 = clazz.BaseType; var parameter1 = GetParameterTypeFromGenericType(baseClass, typeHierarchy, t1, returnParamPos); if (parameter1 != null) { return(parameter1); } throw new InvalidTypesException("The types of the interface " + baseClass.Name + " could not be inferred. " + "Support for synthetic interfaces, lambdas, and generic or raw types is limited at this point"); }
public static IEnumerable <TParent> QueryParentChild <TParent, TChild, TParentKey>( this IDbConnection connection, string sql, Func <TParent, TParentKey> parentKeySelector, Func <TParent, IList <TChild> > childSelector, dynamic param = null, IDbTransaction transaction = null, bool buffered = true, string splitOn = "Id", int?commandTimeout = null, CommandType?commandType = null) { Dictionary <TParentKey, TParent> cache = new Dictionary <TParentKey, TParent>(); connection.Query <TParent, TChild, TParent>( sql, (parent, child) => { if (!cache.ContainsKey(parentKeySelector(parent))) { cache.Add(parentKeySelector(parent), parent); } TParent cachedParent = cache[parentKeySelector(parent)]; IList <TChild> children = childSelector(cachedParent); children?.Add(child); return(cachedParent); }, param as object, transaction, buffered, splitOn, commandTimeout, commandType); return(cache.Values); }
/// <summary> /// Add item to list if item is not null /// </summary> /// <typeparam name="T">Type of element</typeparam> /// <param name="items">IList of items</param> /// <param name="item">Item to check and add</param> public static void AddIfNotNull <T>(this IList <T> items, T item) { if (item != null) { items?.Add(item); } }
/// <summary> /// Registers a setting name to the Value Cache. /// </summary> /// <param name="settingName">The name of the setting (case sensitive).</param> /// <param name="valueType">The type the setting should end up as (i.e. int).</param> /// <param name="isRequired">Whether the setting is required or if a default value can be used.</param> /// <param name="defaultValue">The value that should be used if the setting is not found and if the setting is not required.</param> /// <param name="customTypeDelegate">The operation used for casting a setting to a Custom Type (should match the type of valueType).</param> /// <exception cref="ArgumentNullException">If either the settingName or valueType are not provided.</exception> /// <exception cref="InvalidOperationException">If the provided setting is already registered or its defaultValue type does not match its valueType.</exception> public void RegisterValue(string settingName, Type valueType, bool isRequired, dynamic defaultValue, Func <string, dynamic> customTypeDelegate) { if (string.IsNullOrWhiteSpace(settingName)) { throw new ArgumentNullException(nameof(settingName), "Setting Name is required."); } if (valueType == null) { throw new ArgumentNullException(nameof(valueType), "Value Type is required."); } ValidateSettingNotAlreadyRegistered(settingName); if (!isRequired) { ValidateDefaultValueType(valueType, defaultValue); } _values?.Add(new ValueRegistry { Name = settingName, ValueType = valueType, Required = isRequired, Default = defaultValue, CustomTypeCastFunction = customTypeDelegate }); }
private static void SiftDown(int i, T[] array, int size, IList <string> log = null) { var minIndex = i; var l = LeftChild(i); if (l < size) { if (array[l].CompareTo(array[minIndex]) < 0) { minIndex = l; } } var r = RightChild(i); if (r < size) { if (array[r].CompareTo(array[minIndex]) < 0) { minIndex = r; } } if (i != minIndex) { log?.Add($"{i} {minIndex}"); Swap(ref array[i], ref array[minIndex]); SiftDown(minIndex, array, size, log); } }
public virtual void InternalAddStockOnHands(StockOnHand __item) { if (__item == null || disableInternalAdditions) { return; } stockOnHands?.Add(__item); }
public virtual void InternalAddDeliveryNoteProducts(DeliveryNoteProduct __item) { if (__item == null || disableInternalAdditions) { return; } deliveryNoteProducts?.Add(__item); }
public virtual void InternalAddSubCategory(SubCategory __item) { if (__item == null || disableInternalAdditions) { return; } subCategory?.Add(__item); }
public virtual void InternalAddProducts(OrderProduct __item) { if (__item == null || disableInternalAdditions) { return; } products?.Add(__item); }
public virtual void InternalAddProperties(AuditPropertyConfiguration __item) { if (__item == null || disableInternalAdditions) { return; } properties?.Add(__item); }
public static int Intersect( IList <IndexRange> ranges, IndexRange range, IList <IndexRange>?removed = null) { var result = 0; for (var i = 0; i < ranges.Count && range != s_invalid; ++i) { var existing = ranges[i]; if (existing.End < range.Begin || existing.Begin > range.End) { removed?.Add(existing); ranges.RemoveAt(i--); result += existing.Count; } else { if (existing.Begin < range.Begin) { var except = new IndexRange(existing.Begin, range.Begin - 1); removed?.Add(except); ranges[i] = existing = new IndexRange(range.Begin, existing.End); result += except.Count; } if (existing.End > range.End) { var except = new IndexRange(range.End + 1, existing.End); removed?.Add(except); ranges[i] = new IndexRange(existing.Begin, range.End); result += except.Count; } } } MergeRanges(ranges); if (removed is object) { MergeRanges(removed); } return(result); }
public virtual void InternalAddOrders(ShippingOrder __item) { if (__item == null || disableInternalAdditions) { return; } orders?.Add(__item); }
public virtual void InternalAddTransportUnCaps(TransportUnCap __item) { if (__item == null || disableInternalAdditions) { return; } transportUnCaps?.Add(__item); }