private bool CorruptEntityAnimations_Func() { List<string> tocorrupt = new List<string>(); if (!LoadXMLAndModify("./entities2.xml", delegate (XmlDocument XML) { tocorrupt.AddRange(from XmlNode n in XML.LastChild.ChildNodes select n.Attributes["anm2path"].Value); })) { return false; } tocorrupt.RemoveAll(x => x.Length == 0); tocorrupt.RemoveAll(x => x.Contains("Fireworks") == true); if (!tocorrupt.Select(corruptfile => "./gfx/" + corruptfile) .All(toopen => LoadXMLAndModify(toopen, delegate (XmlDocument XML) { AnimCont A = new AnimCont(); foreach (XmlNode frame in XML.GetElementsByTagName("Frame")) { CorruptFrame(frame, A); } }))) { return false; } List<string> itemfiles = Safe.GetFiles("./gfx/characters"); return itemfiles.All(file => LoadXMLAndModify(file, delegate (XmlDocument XML) { AnimCont A = new AnimCont(); foreach (XmlNode frame in XML.GetElementsByTagName("Frame")) { CorruptFrame(frame, A); } })); }
private void PrepareProducts(List<Product> products) { products.RemoveAll(x => x.Name.Contains("*")); var coupon = products.FirstOrDefault(x => x.Name.Contains("$")); if (coupon != null) { for (var i = 0; i < coupon.Quantity; i++) { var bread = products.First(x => x.Name.Contains("хляб") && !x.Name.Contains("$") && x.Quantity > 0 && x.SellingPrice > coupon.SellingPrice * -1); bread.Quantity--; var breadWithCouponName = bread.Name + " с купон"; var breadWithCoupon = products.FirstOrDefault(x => x.Name == breadWithCouponName); if (breadWithCoupon != null) { breadWithCoupon.Quantity++; } else { breadWithCoupon = new Product { Name = breadWithCouponName, SellingPrice = bread.SellingPrice - coupon.SellingPrice * -1, Quantity = 1 }; products.Add(breadWithCoupon); } } products.RemoveAll(x => x.Quantity == 0); products.RemoveAll(x => x.Name.Contains("$")); } }
protected void BuildFolderList() { List<FileData> lstFolders = new List<FileData>(); string sRoot = Server.MapPath("~/"); string[] subdirs; try { subdirs = Directory.GetDirectories(sRoot); } catch { subdirs = null; } if (subdirs != null) { foreach (string theDir in subdirs) { string w = FileDataHelper.MakeWebFolderPath(theDir); lstFolders.Add(new FileData { FileName = w, FolderPath = w, FileDate = DateTime.Now }); } } lstFolders.RemoveAll(f => f.FileName.ToLower().StartsWith(SiteData.AdminFolderPath)); lstFolders.RemoveAll(f => f.FileName.ToLower().StartsWith("/bin/")); lstFolders.RemoveAll(f => f.FileName.ToLower().StartsWith("/obj/")); lstFolders.RemoveAll(f => f.FileName.ToLower().StartsWith("/app_data/")); ddlFolders.DataSource = lstFolders.OrderBy(f => f.FileName); ddlFolders.DataBind(); }
static void Main(string[] args) { Console.Write("Show all prime numbers from 1 to "); int n = int.Parse(Console.ReadLine()); List<int> numbers = new List<int>(); numbers.Add(2); //adding 2 in the list for (int i = 0; i < n - 2; i += 2) //so it can show numbers from 3 to N and excluding all even numbers { numbers.Add(i + 3); } int range = (int)(Math.Sqrt(n)); //check for divisors up to the square root of N //first removing numbers divisible by 3, 5, 7, 11 numbers.RemoveAll(item => item % 3 == 0 && item != 3); numbers.RemoveAll(item => item % 5 == 0 && item != 5); numbers.RemoveAll(item => item % 7 == 0 && item != 7); numbers.RemoveAll(item => item % 11 == 0 && item != 11); //then checking the rest divisiors with the help of the range for (int i = 13; i < range; i += 2) { numbers.RemoveAll(item => item % i == 0); } //printing numbers Console.WriteLine("The prime numbers from 1 to N are: "); Console.WriteLine(String.Join(", ", numbers)); }
public override bool Parse(List<string> aAnswer) { if (!aAnswer.Contains(BASE_ERROR) && aAnswer.Contains("OK")) { aAnswer.RemoveAll(OKString); aAnswer.RemoveAll(this.ReadParamsClone); aAnswer.RemoveAll(String.IsNullOrEmpty); if (aAnswer.Count == 1) { string[] zSplit = aAnswer[0].Split(new Char[] { ' ', ' ', ' ' }); if (zSplit.Count() == 3) { String zCleanSN = TrimValue(zSplit[2]); SerialNumber = zCleanSN; return true; } else { _logger.Debug("InCorrect Params Count: {0}", zSplit.Count()); return false; } } else return false; } else return false; }
private void checkBounds() { units?.ForEach(unit => { if (unit == null) { return; } var unitTransform = unit.transform; if (Mathf.Abs(unitTransform.position.x) > zone.rightBoundX) { velocity.x *= -1f; //destroyItem(unit); } if (Mathf.Abs(unitTransform.position.y) > zone.sizeY / 2) { velocity.y *= -1; } transform.position += velocity * 0.8f; }); units?.RemoveAll(unit => unit == null); }
private static List<int> GetMostCommonElementList(List<int> intsList) { intsList.Sort(); List<int> listWithRemovedElements =new List<int>(intsList); int listCount = intsList.Count; int currentNumber = intsList[0]; int occurance = 1; for (int i = 0; i <= listCount - 1; i++) { if (i == listCount - 1 && intsList[i] != intsList[i-1]) { currentNumber = intsList[i]; listWithRemovedElements.RemoveAll(x => x == currentNumber); } else if (intsList[i] == intsList[i + 1]) { occurance++; } else { if (occurance % 2 != 0) { currentNumber = intsList[i]; listWithRemovedElements.RemoveAll(x => x == currentNumber); } occurance = 1; } } return listWithRemovedElements; }
/// <summary> /// Sometimes the assets file gives a path of the form "a/b/c/_._" which is not an actual file. /// Sometimes there is no path. /// Sometimes the path is a base class library and is not in the nuget folder. /// Removes all of the paths that are of these cases. /// </summary> private void RemoveNonsensePaths(List <string> paths, string name, string version) { if (name.StartsWith("System.")) { // Base class library paths?.RemoveAll(); return; } paths?.RemoveAll(path => { var pathParts = path.Split("/"); // if(pathParts[0] == "ref") return true; // nonsense _._ if (pathParts.Last() == "_._") { return(true); } return(false); // var fullPath = Path.Combine(NuGetPackageRoot,name.ToLower(),version, path).ParseEnvironmentVariables(); // return !File.Exists(fullPath); }); // || ; // return paths.First().Split("/").Last() == "_._"; }
static void Main(string[] args) { string[] input = Console.ReadLine().Split('\\'); List<char> left = input[0].ToCharArray().ToList(); List<char> right = input[1].ToCharArray().ToList(); string command = input[2]; List<char> result = new List<char>(); switch (command) { case "join": foreach (char element in right) { result.AddRange(left.FindAll(c => c == element)); } result.Sort(); Console.WriteLine(String.Join("", result.Distinct())); break; case "right exclude": result = left; foreach (char element in right) { result.RemoveAll(c => c == element); } result.Sort(); Console.WriteLine(String.Join("", result.Distinct())); break; case "left exclude": result = right; foreach (char element in left) { result.RemoveAll(c => c == element); } result.Sort(); Console.WriteLine(String.Join("", result.Distinct())); break; default: break; } }
public async Task <int> DeleteEventByUserId(Guid user_id) { if (eventsList?.Where(x => x.User_id == user_id) != null) { eventsList?.RemoveAll(x => x.User_id == user_id); return(1); } return(0); }
public static void Main (string[] args) { var l = new List<string> { "A", "A", "B", "C", "D" }; PrintItems(l); Console.WriteLine(l.RemoveAll((s) => s == "A")); PrintItems(l); Console.WriteLine(l.RemoveAll((s) => s == "Q")); PrintItems(l); }
void OnHierarchyChange() { emitters = new List<StudioEventEmitter>(Resources.FindObjectsOfTypeAll<StudioEventEmitter>()); if (!levelScope) { emitters.RemoveAll(x => PrefabUtility.GetPrefabType(x) != PrefabType.Prefab); } if (!prefabScope) { emitters.RemoveAll(x => PrefabUtility.GetPrefabType(x) == PrefabType.Prefab); } }
public static List<TfmRidPair> FilterForApplicableTFMRIDPairs(List<TfmRidPair> tfmRidPairs, string framework, string runtimeIdentifier) { if (framework != null) { tfmRidPairs.RemoveAll(x => !framework.Equals(x.framework)); } if (runtimeIdentifier != null) { tfmRidPairs.RemoveAll(x => !runtimeIdentifier.Equals(x.runtimeIdentifier)); } return tfmRidPairs; }
// Event handlers private void generate_btn_Click(object sender, EventArgs e) { status_bar.Value = 0; string password = ""; List<char> choices = new List<char>(); if(lower_box.Checked) { choices.AddRange(lower); } if(upper_box.Checked) { choices.AddRange(upper); } if(num_box.Checked) { choices.AddRange(numbers); } if(sym_box.Checked) { choices.AddRange(symbols); } if(include_text.Text.Length > 0) { choices.AddRange(include_text.Text.ToCharArray()); } if(exclude_text.Text.Length > 0) { for(int i = 0; i < exclude_text.Text.Length; i++) { choices.RemoveAll(item => item == exclude_text.Text[i]); } } char next; for(int i = 0; i < (int)passlength_select.Value; i++) { if(choices.Count > 0) { next = choices[rand.Next(choices.Count)]; } else { next = ' '; } if(repeat_box.Checked) { choices.RemoveAll(item => item == next); } password += next; } status_bar.Value = 100; pass_text.Text = password; }
/// <summary> /// Adds a custom bread crumb to the list /// </summary> /// <param name="ctx"></param> /// <param name="breadCrumb"></param> public static bool AddBreadCrumb(this HttpContext ctx, BreadCrumb breadCrumb) { if (ctx == null) { return(false); } if (breadCrumbs == null) { breadCrumbs = GetCurrentCookie(ctx); } breadCrumbs?.RemoveAll(p => p.Position > breadCrumb.Position); if (breadCrumbs.Any(crumb => crumb.Link.Equals(breadCrumb.Link, StringComparison.OrdinalIgnoreCase))) { return(false); } if (breadCrumbs.FirstOrDefault(p => p.Position == breadCrumb.Position) != null) { breadCrumbs.RemoveAll(p => p.Position == breadCrumb.Position); } breadCrumbs.Add(breadCrumb); return(true); }
/// <summary> /// Remove a conversation from a subscription. /// </summary> public async Task <bool> RemoveSubscription( ITurnContext context, string subscriptionKey, ConversationReference conversationReference, CancellationToken cancellationToken) { bool isEmpty = false; ProactiveSubscription subscription = await this.GetSubscriptionByKey(context, subscriptionKey, cancellationToken); // Get SubscriptionMap var proactiveSubscriptionMap = await this._proactiveStateSubscription.GetAsync(context, () => new ProactiveSubscriptionMap()).ConfigureAwait(false); // remove thread message id string conversationId = conversationReference.Conversation.Id.Split(';')[0]; List <ConversationReference> subscribedConversations = subscription.ConversationReferences?.ToList(); subscribedConversations?.RemoveAll(it => it.Conversation.Id == conversationId); if (subscribedConversations == null || subscribedConversations.Count == 0) { await this._proactiveStateSubscription.SetAsync(context, null, cancellationToken); isEmpty = true; } else { subscription.ConversationReferences = subscribedConversations; proactiveSubscriptionMap[subscriptionKey] = subscription; await this._proactiveStateSubscription.SetAsync(context, proactiveSubscriptionMap, cancellationToken); } return(isEmpty); }
//Replaces a single instance of a given object private void Replace(GameObject oldObject) { //Instantiate new prefab var newlyCreatedPrefab = PrefabUtility.InstantiatePrefab(freshPrefab, oldObject.scene) as GameObject; //Apply old transformation if (transferTransform) { ApplyTransformation(oldObject, newlyCreatedPrefab); } TransferComponentValues(oldObject, newlyCreatedPrefab); newlyCreatedPrefab.name = oldObject.name; //Needed to invalidate the scene Undo.RecordObject(oldObject, "Replace object"); //Create a lookup table for the old and new instance MakeHistory(oldObject, newlyCreatedPrefab); DestroyImmediate(oldObject); //Cleanup if (oldObject == brokenPrefab) { brokenPrefab = null; } else { similarObjects?.RemoveAll(o => o.SimilarObject == oldObject); } }
// Update is called once per frame void Update() { monster?.RemoveAll(a => a == null); // 모든 몬스터를 다 잡았다면 if (monster.Count == 0) { isClear = true; } if (false)//Input.GetKey(KeyCode.A) && !t) { RemoveMonster(); SpawnMonster(); } // 몬스터를 모두 잡았을 때 이벤트 발생 if (isClear && !isEvent) { isEvent = true; ClearEvent(); } // 플레이어가 죽었을 때 이벤트 발생 else if (isFail && !isEvent) { isEvent = true; FailEvent(); } }
public void ReplaceInFiles(string rootDir, string include,string exclude,IDictionary<string,string>replacements,StringBuilder logger = null) { if (string.IsNullOrEmpty(rootDir)) { throw new ArgumentNullException("rootDir"); } if (!Directory.Exists(rootDir)) { throw new ArgumentException(string.Format("rootDir doesn't exist at [{0}]", rootDir)); } string rootDirFullPath = Path.GetFullPath(rootDir); // search for all include files List<string> pathsToInclude = new List<string>(); List<string> pathsToExclude = new List<string>(); if (!string.IsNullOrEmpty(include)) { string[] includeParts = include.Split(';'); foreach (string includeStr in includeParts) { var results = RobustReplacer.Search(rootDirFullPath, includeStr); foreach (var result in results) { if (!pathsToInclude.Contains(result)) { pathsToInclude.Add(result); } } } } if (!string.IsNullOrEmpty(exclude)) { string[] excludeParts = exclude.Split(';'); foreach (string excludeStr in excludeParts) { var results = RobustReplacer.Search(rootDirFullPath, excludeStr); foreach (var result in results) { if (!pathsToExclude.Contains(result)) { pathsToExclude.Add(result); } } } } int numFilesExcluded = pathsToInclude.RemoveAll(p => pathsToExclude.Contains(p)); LogMessageLine(logger,"Number of files excluded based on pattern: [{0}]", numFilesExcluded); foreach (string file in pathsToInclude) { string fileFullPath = Path.GetFullPath(file); bool modified = false; using (var fileStream = File.Open(fileFullPath, FileMode.Open, FileAccess.ReadWrite)) { using (var replacer = new TokenReplacer(fileStream)) { foreach (string key in replacements.Keys) { modified |= replacer.Replace(key, replacements[key]); } } fileStream.Flush(); } if (modified) { LogMessageLine(logger,"Updating text after replacements in file [{0}]", fileFullPath); } else { LogMessageLine(logger,"Not writing out file because no replacments detected [{0}]", fileFullPath); } } }
private static List<int> Simp(int i) { List<int> list; if (max_num >= i) { list = new List<int>(good_num); list.RemoveAll(EndS); } else { list = new List<int>(good_num); for (int j = 1; j < i - max_num + 1; j++) { if (IsSimp(max_num + j)) { list.Add(max_num + j); } } } /*list = new List<int>(); for (int j = 1; j < i + 1; j++) { if (IsSimp(j)) { Thread.Sleep(2); list.Add(j); } }*/ return list; }
public override void ExposeData() { base.ExposeData(); Scribe_Values.Look <float>(ref this.radius, "radius", 0f, false); Scribe_Defs.Look <DamageDef>(ref this.damType, "damType"); Scribe_Values.Look <int>(ref this.damAmount, "damAmount", 0, false); Scribe_Values.Look <float>(ref this.armorPenetration, "armorPenetration", 0f, false); Scribe_References.Look <Thing>(ref this.instigator, "instigator", false); Scribe_Defs.Look <ThingDef>(ref this.weapon, "weapon"); Scribe_Defs.Look <ThingDef>(ref this.projectile, "projectile"); Scribe_References.Look <Thing>(ref this.intendedTarget, "intendedTarget", false); Scribe_Values.Look <bool>(ref this.applyDamageToExplosionCellsNeighbors, "applyDamageToExplosionCellsNeighbors", false, false); Scribe_Defs.Look <ThingDef>(ref this.preExplosionSpawnThingDef, "preExplosionSpawnThingDef"); Scribe_Values.Look <float>(ref this.preExplosionSpawnChance, "preExplosionSpawnChance", 0f, false); Scribe_Values.Look <int>(ref this.preExplosionSpawnThingCount, "preExplosionSpawnThingCount", 1, false); Scribe_Defs.Look <ThingDef>(ref this.postExplosionSpawnThingDef, "postExplosionSpawnThingDef"); Scribe_Values.Look <float>(ref this.postExplosionSpawnChance, "postExplosionSpawnChance", 0f, false); Scribe_Values.Look <int>(ref this.postExplosionSpawnThingCount, "postExplosionSpawnThingCount", 1, false); Scribe_Values.Look <float>(ref this.chanceToStartFire, "chanceToStartFire", 0f, false); Scribe_Values.Look <bool>(ref this.damageFalloff, "dealMoreDamageAtCenter", false, false); Scribe_Values.Look <IntVec3?>(ref this.needLOSToCell1, "needLOSToCell1", null, false); Scribe_Values.Look <IntVec3?>(ref this.needLOSToCell2, "needLOSToCell2", null, false); Scribe_Values.Look <int>(ref this.startTick, "startTick", 0, false); Scribe_Collections.Look <IntVec3>(ref this.cellsToAffect, "cellsToAffect", LookMode.Value, Array.Empty <object>()); Scribe_Collections.Look <Thing>(ref this.damagedThings, "damagedThings", LookMode.Reference, Array.Empty <object>()); Scribe_Collections.Look <Thing>(ref this.ignoredThings, "ignoredThings", LookMode.Reference, Array.Empty <object>()); Scribe_Collections.Look <IntVec3>(ref this.addedCellsAffectedOnlyByDamage, "addedCellsAffectedOnlyByDamage", LookMode.Value); if (Scribe.mode == LoadSaveMode.PostLoadInit) { damagedThings?.RemoveAll((Thing x) => x == null); ignoredThings?.RemoveAll((Thing x) => x == null); } }
static void Main() { int number = int.Parse(Console.ReadLine()); var list = new List<int>(); IEnumerable<int> list2 = Enumerable.Range(2, number-1); list = list2.ToList(); int p=2; while (p<=number) { for (int i = 2*(p-1);i < list.Count;i=i+p ) { list[i] = -1; } p++; } list.RemoveAll(item => item == -1); for (int i = 0; i < list.Count - 1; i++) { Console.Write(list[i] + ", "); } Console.Write(list[list.Count - 1]); }
static void Main() { Console.WriteLine("Please, enter a sequence of integers, separated by space:"); var input = Console.ReadLine(); var inputSplited = input.Split(new string[] {" "}, StringSplitOptions.RemoveEmptyEntries); int[] inputInts = Array.ConvertAll(inputSplited, int.Parse); var sequence = new List<int>(); sequence.AddRange(inputInts); var countOccurencies = 0; int currentInt; for (int i = 0; i < sequence.Count; i++) { currentInt = sequence[i]; //-------------------- using simple algorythm ------------- for (int j = 0; j < sequence.Count; j++) { if (sequence[i] == sequence[j]) { countOccurencies++; } } if (countOccurencies % 2 != 0) { sequence.RemoveAll(x => x == currentInt); i = i - 1; } countOccurencies = 0; //-------------- OR using the 10 times faster (for large data) algorythm below:---------- //countOccurencies = 1; //var countedInts = new List<int>(); // //if (!countedInts.Exists(x => x == currentInt)) //{ // for (int j = i + 1; j < sequence.Count; j++) // { // if (sequence[i] == sequence[j]) // { // countOccurencies++; // } // } // // if (countOccurencies%2 != 0) // { // sequence.RemoveAll(x => x == currentInt); // i = i - 1; // } // else // { // countedInts.Add(currentInt); // } // countOccurencies = 1; //} } Console.WriteLine(string.Join(" ", sequence.ToArray())); }
public List<ICheckStrategy> getSolutions() { List<ICheckStrategy> lijst = new List<ICheckStrategy>(); lijst.Add(vermenigvuldigen_door_halveren.ReturnStrat()); lijst.Add(vermenigvuldigen_kolomsgewijs.ReturnStrat()); lijst.Add(vermenigvuldigen_met_1x_meer.ReturnStrat()); lijst.Add(vermenigvuldigen_met_1x_minder.ReturnStrat()); lijst.Add(vermenigvuldigen_met_1x_minder_10.ReturnStrat()); lijst.Add(vermenigvuldigen_met_de_helft_van_10x.ReturnStrat()); lijst.Add(vermenigvuldigen_met_een_handig_getal.ReturnStrat()); lijst.Add(vermenigvuldigen_met_omkeringsprincipe.ReturnStrat()); lijst.Add(vermenigvuldigen_naar_analogie_met_nullen.ReturnStrat()); lijst.Add(vermenigvuldigen_met_rond_getal.ReturnStrat()); lijst.Add(vermenigvulidgen_door_te_verdubbelen.ReturnStrat()); lijst.Add(vermenigvulidgen_met_sprongen_op_de_getallenlijn.ReturnStrat()); lijst.Add(vermenigvulidgen_met_oppervlaktemodel.ReturnStrat()); lijst.Add(cijferend.ReturnStrat()); lijst.RemoveAll(item => item == null); for (int i = 0; i < lijst.Count; i++) { //Console.WriteLine(lijst[i].ReturnImportance()); } return data.GetStratsToDisplay(lijst, 4); }
public override void PostExposeData() { base.PostExposeData(); if (Scribe.mode == LoadSaveMode.Saving) { // let's not bloat saves... if (infusions != null) { if (infusions.Count > 1) { infusions = infusions.OrderBy(i => i.labelReversed).ToList(); } Scribe_Collections.Look(ref infusions, "infusions", LookMode.Def); } } else if (Scribe.mode == LoadSaveMode.LoadingVars) { // Easy loading Scribe_Collections.Look(ref infusions, "infusions", LookMode.Def); infusions?.RemoveAll(item => item == null); isNew = false; } }
/* Task 6: * Write a program that removes from given sequence all numbers that occur odd number of times. Example: * {4, 2, 2, 5, 2, 3, 2, 3, 1, 5, 2} {5, 3, 3, 5} */ static void Main(string[] args) { var numbers = new List<int> { 4, 2, 2, 5, 2, 3, 2, 3, 1, 5, 2 }; var uniqueNumbers = new Dictionary<Int32, Int32>(); for (int i = 0; i < numbers.Count; i++) { if (uniqueNumbers.ContainsKey(numbers[i])) { uniqueNumbers[numbers[i]]++; } else { uniqueNumbers.Add(numbers[i], 1); } } foreach (var uniqueNumber in uniqueNumbers) { if (uniqueNumber.Value % 2 != 0) { numbers.RemoveAll(x => x == uniqueNumber.Key); } } foreach (var number in numbers) { Console.Write("{0} ", number); } }
private List<IPlugin> GetLoadingSequence() { int num = 0; List<IPlugin> tmp; List<IPlugin> list = new List<IPlugin>(plugins); List<IPlugin> ret = new List<IPlugin>(list.FindAll(p => !p.Info.HasPreconditions)); list.RemoveAll(p => ret.Contains(p)); for (int precount = 1; list.Count > 0; precount = num) { tmp = list.FindAll(p => p.Info.Preconditions.Count == precount); ret.AddRange(tmp); list.RemoveAll(p => tmp.Contains(p)); num = precount + 1; } return ret; }
public NanoHttpResponse Handle(NanoHttpRequest request) { try { var places = new List<string>(File.ReadAllLines(Strings.Places)); var place = request.Address.Substring(5); bool found = false; if (places.Contains(place)) { found = true; places.RemoveAll(s => s == place); } File.WriteAllLines(Strings.Places, places.ToArray()); return new NanoHttpResponse(StatusCode.Ok, (found?"Deleted ":"Not found ") + place); } catch (Exception e) { NotificationHandler.Instance.AddNotification("Не удалось обновить places.txt"); return new ErrorHandler(StatusCode.InternalServerError, e.ToString()).Handle(request); } }
public static List<string> ReadFile(string filename) { List<string> listFileContent = new List<string>(); StringBuilder stringBuilder = new StringBuilder(); using (FileStream fileStream = new FileStream(filename, FileMode.Open, FileAccess.Read)) { using (StreamReader streamReader = new StreamReader(fileStream)) { char[] fileContents = new char[_bufferSize]; int charsRead = streamReader.Read(fileContents, 0, _bufferSize); // Can't do much with 0 bytes //if (charsRead == 0) // throw new Exception("File is 0 bytes"); while (charsRead > 0) { stringBuilder.Append(fileContents); charsRead = streamReader.Read(fileContents, 0, _bufferSize); } string[] contentArray = stringBuilder.ToString().Split(new char[] { '\r', '\n' }); foreach (string line in contentArray) { listFileContent.Add(line.Replace("#", "")); } listFileContent.RemoveAll(s => string.IsNullOrEmpty(s)); } } return listFileContent; }
protected override void OnLoad(EventArgs e) { var app_list = new List<App>(from x in DataContainer.Instance().Applications where x.Preferences.Contains(CurrentCourse.BannerName) select x); // now sort according to preferences { var tmpList = new List<App>(); foreach (var x in (CurrentCourse.HiringPreferences ?? "").Split(',')) { tmpList.AddRange(app_list.Where(a => a.User.Equals(x, StringComparison.OrdinalIgnoreCase))); app_list.RemoveAll(a => a.User == x); } tmpList.AddRange(app_list); app_list = tmpList; } appgrid.DataSource = app_list; appgrid.DataBind(); prefs_body.DataSource = (from x in app_list select x.User); prefs_body.DataBind(); }
static void Main(string[] args) { List<int> someSequence = new List<int>() { 4, 2, 2, 5, 2, 3, 2, 3, 1, 5, 2 }; HashSet<int> someHashSet = new HashSet<int>(); for (int i = 0; i < someSequence.Count; i++) { someHashSet.Add(someSequence[i]); } foreach (var number in someHashSet) { int counterForMatches = 0; for (int i = 0; i < someSequence.Count; i++) { if (someSequence[i] == number) { counterForMatches++; } } if (counterForMatches % 2 == 1) { someSequence.RemoveAll(item => item == number); } } foreach (var number in someSequence) { Console.WriteLine(number); } }
public MyDayViewModel( [Import] IEventAggregator aggregator, [Import] ITasksService tasksService, [Import] IProjectsService projectsService, [Import] ITeamService teamService, [Import] IBackgroundExecutor executor, [Import] IAuthorizationService authorizator) : base(aggregator, tasksService, projectsService, teamService, executor, authorizator) { aggregator.Subscribe<MemberProfile>(ScrumFactoryEvent.SignedMemberChanged, OnSignedMemberChanged); aggregator.Subscribe<Task>(ScrumFactoryEvent.TaskAdded, t => { UpdateTasks(); }); aggregator.Subscribe<Task>(ScrumFactoryEvent.TaskAssigneeChanged, t => { UpdateTasks(); }); aggregator.Subscribe<Task>(ScrumFactoryEvent.TaskChanged, t => { UpdateTasks(); }); aggregator.Subscribe<ICollection<ProjectInfo>>(ScrumFactoryEvent.RecentProjectChanged, prjs => { List<ProjectInfo> prjs2 = new List<ProjectInfo>(prjs); if (MemberEngagedProjects != null) prjs2.RemoveAll(p => MemberEngagedProjects.Any(ep => ep.ProjectUId == p.ProjectUId)); RecentProjects = prjs2.Take(8).ToList(); OnPropertyChanged("RecentProjects"); }); OnLoadCommand = new DelegateCommand(OnLoad); RefreshCommand = new DelegateCommand(Load); ShowMemberDetailCommand = new DelegateCommand<MemberProfile>(ShowMemberDetail); CreateNewProjectCommand = new DelegateCommand(CreateNewProject); eventsViewSource = new System.Windows.Data.CollectionViewSource(); }
static List<int> CheckingEquals(List<int> numbers) { List<int> temp = new List<int>(); for (int i = 0; i < numbers.Count; i++) { temp.Add(numbers[i]); } List<int> longestSequ = new List<int>(); while (temp.Count > 0) { List<int> currentSequ = new List<int>(); for (int col = 0; col < temp.Count; col++) { if (temp[0] == temp[col]) { currentSequ.Add(temp[col]); } } temp.RemoveAll(i => i == currentSequ[0]); if (currentSequ.Count > longestSequ.Count) { longestSequ = currentSequ; } } return longestSequ; }
private decimal?FuelConsumptionPerSecond(DateTime timestamp, decimal?fuel, int trackingMinutes = 5) { if (fuel is null) { return(null); } if (fuelLog is null) { fuelLog = new List <KeyValuePair <DateTime, decimal?> >(); } else { fuelLog?.RemoveAll(log => (DateTime.UtcNow - log.Key).TotalMinutes > trackingMinutes); } fuelLog.Add(new KeyValuePair <DateTime, decimal?>(timestamp, fuel)); if (fuelLog.Count > 1) { decimal? fuelConsumed = fuelLog.FirstOrDefault().Value - fuelLog.LastOrDefault().Value; TimeSpan timespan = fuelLog.LastOrDefault().Key - fuelLog.FirstOrDefault().Key; return(timespan.Seconds == 0 ? null : fuelConsumed / timespan.Seconds); // Return tons of fuel consumed per second } // Insufficient data, return 0. return(0); }
public static void Main() { var inputIntList = new List<int>() { 4, 2, 2, 5, 2, 3, 2, 3, 1, 5, 2 }; var dictionary = new Dictionary<int, int>(); for (int i = 0; i < inputIntList.Count; i++) { if (dictionary.ContainsKey(inputIntList[i])) { dictionary[inputIntList[i]]++; } else { dictionary.Add(inputIntList[i], 1); } } foreach (var item in dictionary) { if (item.Value % 2 != 0) { inputIntList.RemoveAll(x => x == item.Key); } } Console.WriteLine(string.Join(", ", inputIntList)); }
protected override void OnGetValue(PropertySpecEventArgs e) { base.OnGetValue(e); var attributeList = new List<Attribute>(); attributeList.AddRange(e.Property.Attributes.ToList()); //check all of the attributes: if we find a dynamic one, evaluate it and possibly add/overwrite a static attribute foreach (Attribute customAttribute in e.Property.Attributes) { if (customAttribute is DynamicReadOnlyAttribute) { attributeList.RemoveAll(x => x is ReadOnlyAttribute); if (DynamicReadOnlyAttribute.IsDynamicReadOnly(propertyObject, e.Property.Name)) { //condition is true: the dynamic attribute should be applied (as static attribute) attributeList.Add(new ReadOnlyAttribute(true)); //add static read only attribute } } } e.Property.Attributes = attributeList.ToArray(); var propertyInfo = propertyObject.GetType().GetProperty(e.Property.Name); var value = propertyInfo.GetValue(propertyObject, null); var isNestedPropertiesObject = IsNestedExpandablePropertiesObject(propertyInfo); // if nested properties object, wrap in DynamicPropertyBag to provide support for things like DynamicReadOnly e.Value = isNestedPropertiesObject ? new DynamicPropertyBag(value) : value; }
internal void Execute(IDbConnection connection, IDbTransaction transaction, MigrationDirection direction, IDbCommandExecutor commandExecutor) { Debug.Assert(connection.State == ConnectionState.Open); var context = new RuntimeContext(connection, transaction, commandExecutor, _providerMetadata); Database database = GetDatabaseContainingMigrationChanges(direction, context); var translator = new CommandsToSqlTranslator(_provider); foreach (string commandText in translator.TranslateToSql(database, context)) { //MigSharp uses ADO, not SMO to run SQL. ADO does not support the 'GO' statement in SQL as it is not TSQL. //We split SQL on 'GO' and run as individual statements var separatedByGoStatements = new List<string>(goStatementRegex.Split(commandText)); separatedByGoStatements.RemoveAll(r => String.IsNullOrEmpty(r.Trim())); foreach (var statement in separatedByGoStatements) { IDbCommand command = connection.CreateCommand(); command.CommandTimeout = 0; // do not timeout; the client is responsible for not causing lock-outs command.Transaction = transaction; command.CommandText = statement; try { commandExecutor.ExecuteNonQuery(command); } catch (DbException x) { Log.Error("An error occurred: {0}{1}while trying to execute:{1}{2}", x.Message, Environment.NewLine, command.CommandText); throw; } } } }
public IList<PatternStart> RandomizeColoring() { //original color Dictionary<PatternStart, IList<Color>> startToColor = new Dictionary<PatternStart, IList<Color>>(); //keep track of the active patterns. Will contain new color List<PatternStart> active = new List<PatternStart>(); foreach (var start in _patternStarts) { IList<Color> colors = EffectsToColors(start.SampleEffect.ColorEffects); startToColor[start] = colors; OrderedSet<Color> distinct = new OrderedSet<Color>(); distinct.AddAll(colors); IDictionary<Color, Color> oldToNew = OldToNew(startToColor, active); Color randBase = distinct.FirstOrDefault(oldToNew.ContainsKey); IList<Color> newColors = randBase == default(Color) ? ColorPicker.PickColors(distinct.Count) : ColorPicker.PickColors(randBase, distinct.Count); IEnumerator<Color> newEnum = newColors.GetEnumerator(); IEnumerator<Color> oldEnum = distinct.GetEnumerator(); while(oldEnum.MoveNext()) { newEnum.MoveNext(); if (!oldToNew.ContainsKey(oldEnum.Current)) { oldToNew[oldEnum.Current] = newEnum.Current; } } start.ApplyColors(colors.Select(c=>oldToNew[c]).ToList()); active.RemoveAll(s => s.EndTime <= start.StartTime); active.Add(start); } return _patternStarts; }
public DataListTO(string dataList, bool ignoreColumnDirection = false) { var fixedDataList = dataList.Replace(GlobalConstants.SerializableResourceQuote, "\"").Replace(GlobalConstants.SerializableResourceSingleQuote, "\'"); Inputs = new List<string>(); Outputs = new List<string>(); using (var stringReader = new StringReader(fixedDataList)) { var xDoc = XDocument.Load(stringReader); var rootEl = xDoc.Element("DataList"); if (rootEl != null) { if (ignoreColumnDirection) { Map(rootEl); } else { MapForInputOutput(rootEl); } } } Inputs.RemoveAll(string.IsNullOrEmpty); Outputs.RemoveAll(string.IsNullOrEmpty); }
public override IEnumerator ReportBombStatus() { IEnumerator baseIEnumerator = base.ReportBombStatus(); while (baseIEnumerator.MoveNext()) { yield return(baseIEnumerator.Current); } List <TwitchBomb> bombHandles = TwitchGame.Instance.Bombs; yield return(new WaitUntil(() => SceneManager.Instance.GameplayState.RoundStarted)); yield return(new WaitForSeconds(0.1f)); _roomLight = (GameObject)_roomLightField.GetValue(_room); PaceMaker paceMaker = SceneManager.Instance.GameplayState.GetPaceMaker(); List <PacingAction> actions = (List <PacingAction>) typeof(PaceMaker).GetField("actions", BindingFlags.NonPublic | BindingFlags.Instance)?.GetValue(paceMaker); actions?.RemoveAll(action => action.EventType == PaceEvent.OneMinuteLeft); while (bombHandles.TrueForAll(handle => !handle.Bomb.HasDetonated)) { if (bombHandles.TrueForAll(handle => handle.Bomb.IsSolved())) { yield break; } ToggleEmergencyLights(OtherModes.currentMode != TwitchPlaysMode.Zen && bombHandles.Any(handle => handle.CurrentTimer < 60f && !handle.Bomb.IsSolved()), bombHandles[0]); yield return(null); } }
public void RestartGame() { isStarted = false; endGame = false; shootBullets = 0; lastShootTime = 0; activeBullets?.ForEach(bullet => { if (bullet != null) { Destroy(bullet.gameObject); } }); activeBullets?.RemoveAll(bullet => bullet == null); }
protected void RemoveStaffWithNoPendingApprovals(List<Staff> staffList) { if (!string.IsNullOrEmpty(GetPreselectedUsername(Page))) { chkHide.Visible = false; return; } if (chkHide.Checked) { staffList.RemoveAll(delegate(Staff staff) { bool hasPending = false; const int stage = 1; // submitted by staff but awaiting approval by supervisor if (BookingMode == eBookingMode.Book) { List<BookedEvent> events = BookedEvent.GetAll(staff.Username, stage); hasPending = events.Count > 0; } else { const string suggestedEventQueryKey = "SE"; bool isAdHoc = Page.Request.QueryString[suggestedEventQueryKey] == null; List<PrebookedEvent> events = PrebookedEvent.GetAll(staff.Username, stage, isAdHoc); hasPending = events.Count > 0; } return !hasPending; }); } }
public void Delete(ExecutedCommand executedCommand) { _history?.RemoveAll(c => string.Equals(c.Value, executedCommand.Value, StringComparison.OrdinalIgnoreCase)); _historyContainer.Delete(GetHash(executedCommand.Value)); Messenger.Default.Send(new CommandHistoryChangedMessage()); }
public void Clear() { MClass = ""; Family = ""; Trait = ""; creatures?.RemoveAll(s => true); description?.RemoveAll(s => true); }
public static void DeleteRecord(string id) { DataAccess <Schedule> .DeleteRecord(id); if (UseCache) { _cache?.RemoveAll(x => x.Id == id); } }
private static void RemoveSmallTalks(List <string> sentences) { List <string> smallTalks = new List <string>(); foreach (string sm in SmallTalkDictionary.smallTalks) { smallTalks.AddRange(sentences.FindAll(s => s.ToLower().Contains(sm.ToLower()))); } sentences?.RemoveAll(st => smallTalks.Contains(st)); }
public static string GetImageString(List <string> images) { images?.RemoveAll(r => string.IsNullOrEmpty(r?.Trim())); if (images == null || images.Count <= 0) { return(null); } return(string.Join(FIRST_SEPARATOR, images)); }
public void PushButton() { SoundDefOf.RadioButtonClicked.PlayOneShot(this); buttonOn = !buttonOn; linkedDoors?.RemoveAll(door => !door.Spawned); if (linkedDoors != null) { foreach (var linkedDoor in linkedDoors) { linkedDoor.Notify_ButtonPushed(); } } }
public override void ExposeData() { base.ExposeData(); _disabledPawns?.RemoveAll(pawn => pawn?.Destroyed ?? true); _disabledPawnSchedules?.RemoveAll(pawn => pawn?.Destroyed ?? true); _disabledWorkTypes?.RemoveAll( workType => !DefDatabase <WorkTypeDef> .AllDefsListForReading.Contains(workType)); Scribe_Values.Look(ref Enabled, nameof(Enabled), true); Scribe_Collections.Look(ref _disabledWorkTypes, "DisabledWorkTypes", LookMode.Def); Scribe_Collections.Look(ref _disabledPawns, "DisabledPawns", LookMode.Reference); Scribe_Collections.Look(ref _disabledPawnWorkTypes, "DisabledPawnWorkTypes", LookMode.Deep); Scribe_Collections.Look(ref _disabledPawnSchedules, "DisabledPawnSchedules", LookMode.Reference); }
private async void OnAction(IDictionary <string, string> data) { JObject push = pushHistory.Find(item => ((string)item["notification_id"]).Equals(data["notification_id"])); switch (data["action"]) { case "reply": string message = data["message"]; if (data["notification_id"].Contains("sms_")) { //TODO: implement SMS sending throw new NotImplementedException("Not implemented SMS send"); } else { PushbulletUtils.QuickReply(push, message); } break; case "activate": try { string packageName = (string)push["package_name"]; string url = await PushbulletUtils.ResolveUrlFromPackageName(packageName); System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(url)); } catch { } break; case "dismiss": default: break; } pushHistory?.RemoveAll(item => ((string)item["notification_id"]).Equals(data["notification_id"])); }
/// <summary> /// Set the parameters property from a data table. /// </summary> /// <param name="data">The data table.</param> private void SetParametersFromGrid(DataTable data) { Parameters = new List <ForageMaterialParameters>(); foreach (DataRow row in data.Rows) { var fullName = row[0].ToString(); if (!string.IsNullOrEmpty(fullName)) // can be empty at bottom of grid because grid.CanGrow=true { Parameters?.RemoveAll(p => p.Name.Equals(fullName, StringComparison.InvariantCultureIgnoreCase)); var live = new ForageMaterialParameters(this, fullName, live: true, row[1].ToString(), Convert.ToDouble(row[3]), Convert.ToDouble(row[5])); Parameters.Add(live); var dead = new ForageMaterialParameters(this, fullName, live: false, row[2].ToString(), Convert.ToDouble(row[4]), 0.0); Parameters.Add(dead); } } }
public void Unsubscribe(object subscriber) { lockSlim.EnterWriteLock(); try { foreach (KeyValuePair <Type, List <WeakReference> > pair in subscriberLists.ToList()) { List <WeakReference> list = pair.Value; list?.RemoveAll(x => x.Target == subscriber); } } finally { lockSlim.ExitWriteLock(); } }
/// <summary> /// Gets or sets the <see cref="Attribute"/> with the specified name. /// </summary> /// <value> /// The <see cref="Attribute"/>. /// </value> /// <param name="name">The name.</param> /// <returns></returns> public Attribute this[string name] { get { return(_attributes?.FirstOrDefault(a => a.Name.Equals(name, StringComparison.OrdinalIgnoreCase))); } set { _attributes?.RemoveAll(a => a.Name.Equals(name, StringComparison.OrdinalIgnoreCase)); if (_attributes == null) { _attributes = new List <Attribute>(); } _attributes.Add(value); } }
private List <Group> LoadGroupsFromFile() { List <Group> groupList = null; string groupSettingsFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, _logingGoupSettingsFileName); if (File.Exists(groupSettingsFilePath)) { groupList = JsonHelper.DeserializeFromFile <List <Group> >(groupSettingsFilePath); // DefaultGroup is hard-code and its users may have changed, so remove it groupList?.RemoveAll(x => x.Name == Group.DefaultGroup); } groupList = groupList ?? new List <Group>(); // Add DefaultGroup as the last one groupList.Add(new Group { Name = Group.DefaultGroup }); return(groupList); }
public IActionResult Add([FromBody] List <ServerRequest> servers) { var response = new BaseResponse(); servers?.RemoveAll(o => o == null); if (servers?.Any() != true) { response.Errors.Add("No servers found in request."); return(BadRequest(response)); } for (var i = 0; i < servers.Count; i++) { if (servers[i].CpuThreshold <= 0) { response.Errors.Add($"Server {i + 1} CpuThreshold cannot be less than 0."); } if (servers[i].Weight <= 0) { response.Errors.Add($"Server {i + 1} Weight cannot be less than 0."); } if (servers[i].CpuUsage < 0) { response.Errors.Add($"Server {i + 1} CpuUsage cannot be less than 0."); } } if (response.Errors.Any()) { return(BadRequest(response)); } foreach (var server in servers) { var serverId = Algorithm.RegisterServer(server.ToData()); if (serverId > 0) { response.Messages.Add($"Server{serverId} added successfully"); } } return(Ok(response)); }
/// <summary> /// The combo box1 selection change committed. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The event arguments.</param> private void ComboBox1_SelectionChangeCommitted(object sender, EventArgs e) { flowLayoutPanel1.SuspendLayout(); pictureBoxes?.RemoveAll(item => RemoveCanvas(flowLayoutPanel1, item)); flowLayoutPanel1.ResumeLayout(true); methods = HelperExtensions.ListStaticMethodsWithAttribute((Type)((ComboBox)sender).SelectedItem, typeof(SourceCodeLocationProviderAttribute)); flowLayoutPanel1.SuspendLayout(); foreach (var method in methods) { AddCanvas(flowLayoutPanel1, pictureBoxes); } flowLayoutPanel1.ResumeLayout(true); comboBox2.DataSource = methods; comboBox2.ValueMember = "Name"; comboBox2.SelectedItem = null; Invalidate(true); }
public void PopulateData(List <SoundDataObject> list) { try { list?.RemoveAll(a => a.IsLiked != null && !a.IsLiked.Value); if (list?.Count > 0) { MAdapter.SoundsList = new ObservableCollection <SoundDataObject>(list); MAdapter.NotifyDataSetChanged(); ShowEmptyPage(); } else { ShowEmptyPage(); } } catch (Exception e) { Console.WriteLine(e); } }
private bool DeleteSave(GUIButton button, object obj) { string saveFile = obj as string; if (obj == null) { return(false); } string header = TextManager.Get("deletedialoglabel"); string body = TextManager.GetWithVariable("deletedialogquestion", "[file]", Path.GetFileNameWithoutExtension(saveFile)); EventEditorScreen.AskForConfirmation(header, body, () => { SaveUtil.DeleteSave(saveFile); prevSaveFiles?.RemoveAll(s => s.StartsWith(saveFile)); UpdateLoadMenu(prevSaveFiles.ToList()); return(true); }); return(true); }
private async Task DecideAddon(Addon addon, ObservableCollection <IFileAction> actions) { this.log.Information("Checking {addon}", addon.Name); var localFolder = new DirectoryInfo(Path.Combine(this.Local.FullName, addon.Name)); List <FileInfo> localFiles = null; if (localFolder.Exists) { localFiles = localFolder.EnumerateFiles("*", SearchOption.AllDirectories).ToList(); } foreach (var file in addon.Files) { var local = new FileInfo(Path.Combine(this.Local.FullName, addon.Name, file.Path.Trim('/', '\\'))); if (local.Exists) { localFiles?.RemoveAll(x => x.FullName == local.FullName); } await DecideFile(local, file, addon, actions); } localFiles?.ForEach(f => f.Delete()); // Delete files found in filesystem but not in index }
public StreetRootResponse GetStreet(string neigborhood_id) { if (String.IsNullOrEmpty(token)) { throw new ArgumentNullException(nameof(token)); } IDictionary <string, string> args = new Dictionary <string, string>(); args.Add(GetTokenPair()); args.Add("t", "sf"); args.Add("u", neigborhood_id); string response = Execute <string>("load.ashx", Method.POST, args); if (String.IsNullOrEmpty(response)) { return(new StreetRootResponse()); } HtmlDocument htmlDocument = new HtmlDocument(); htmlDocument.LoadHtml(response); List <HtmlNode> tableRows = htmlDocument.DocumentNode.SelectNodes("//tbody//tr//td").ToList(); tableRows?.RemoveAll(x => x.InnerText == "CADDE" || x.InnerText == "SOKAK" || x.InnerText == "BULVAR" || x.InnerText == "MEYDAN" || x.InnerText == "KÜME EVLER" || x.InnerText == "KÖY SOKAĞI" || x.InnerText == "SEÇ"); StreetRootResponse streetRootResponse = new StreetRootResponse(); for (int i = 0; i < tableRows.Count; i++) { HtmlNode firstNode = tableRows[i]; streetRootResponse.streetResponses.Add(new StreetRootResponse.StreetResponse { text = firstNode.InnerText, value = firstNode.ParentNode.Id.Substring(1, firstNode.ParentNode.Id.ToString().Length - 1) }); } return(streetRootResponse); }