static void Main() { var elements = new List<int>() { 40, 50, 60, 5, 10, 20, 30, }; var ordered = elements.SortBy(x => x); Console.WriteLine(string.Join(", ", ordered)); var students = new List<Student>() { new Student("Gosho", 20, 4.5), new Student("Pesho", 17, 2), new Student("Tanio", 23, 6.00), new Student("Ivan", 21, 5.5) }; var goodStudents = students .Filter(st => st.AverageGrade > 5) .SortBy(st => st.Age) .Project(st => st.Name); Console.WriteLine(string.Join("\n", goodStudents)); }
public int GetSumOfNumbers(List<string> numbersAsText) { return numbersAsText .Filter(s => !string.IsNullOrEmpty(s)) .Map(s => ParsedOrNull(s)) .Filter(n => n.HasValue) .Reduce(0, (acc, num) => acc + num.Value); }
//Refactor these methods to use map/filter/reduce instead of loops public bool AreAllNonEmptyStringsLongerThan5(List<string> input) { return input .Filter(s => !string.IsNullOrEmpty(s)) .Reduce( true, (acc, str) => (str.Length >= 5) && acc); }
internal static List<Edge> SelectNonIntersectingEdges(BitmapData keepOutMask, List<Edge> edgesToTest) { if (keepOutMask == null) { return edgesToTest; } _keepOutMask = keepOutMask; return edgesToTest.Filter(MyTest); }
public Projects GetProjectsByProjectHostAndUsername(string projectHostUsernamePair, string filters) { var hostAndUsername = ProjectHostExtensions.ParseProjectHostAndUsername(projectHostUsernamePair); var projects = new List<Project>(); foreach (var hostUsername in hostAndUsername) { projects.AddRange(GetProjectsByUsername(hostUsername.Key, hostUsername.Value)); } return new Projects(projects.Filter(filters).OrderBy(p => p.Name).ThenByDescending(p => string.IsNullOrEmpty(p.LastModified) ? DateTime.Now : DateTime.Parse(p.LastModified))); }
public static void Main(string[] args) { List<int> number = new List<int>() { 3, 4, 5, 6, 1, 7 }; var orderNumber = number.OrderEnumerable(n => n); Console.WriteLine(string.Join(".", orderNumber)); var filterList = number.Filter(n => n % 2 != 0); var res = number.WhereNot(n => n < 5); ; Console.WriteLine(string.Join(" ", filterList)); Console.WriteLine(string.Join(" ", res) + "new"); Student misho = new Student("Aisho", 10, 5); Student gosho = new Student("Gosho", 20, 6); Student minka = new Student("Binka", 40, 4); Student koko = new Student("Coko", 30, 2); List<Student> studentCollection = new List<Student>(); studentCollection.Add(misho); studentCollection.Add(gosho); studentCollection.Add(minka); studentCollection.Add(koko); var orderListOfStudentByName = studentCollection.OrderEnumerable(st => st.Name); Console.WriteLine(string.Join("\n", orderListOfStudentByName)); var age = studentCollection.Project(st => st.Age); var stres = studentCollection.WhereNot(st => st.Name.StartsWith("K")); foreach (var s in stres) { Console.WriteLine(s.Name); } Console.WriteLine(string.Join(" ", age)); }
private static void Main() { var elements = new List<int> { 40, 50, 60, 5, 10, 20, 30 }; var ordered = elements.SortBy(x => x); Console.WriteLine(string.Join(", ", ordered)); var students = new List<Student> { new Student("Gosho", 20, 4.5), new Student("Pesho", 17, 2), new Student("Tanio", 23, 6.00), new Student("Ivan", 21, 5.5) }; var goodStudents = students.Filter(st => st.AverageGrade > 5).SortBy(st => st.Age).Project(st => st.Name); var ivan = students.FirstOrDef(st => st.Name == "Ivan"); // var goodStudents = students.Where(st => st.AverageGrade > 5).OrederBy(st => st.Age).Select(st => st.Name); //tova e LINQ varianta na gornata zaivka Console.WriteLine(string.Join("\n", goodStudents)); }
public HttpResponseMessage Get(FilterViewModel filter) { var rawMatches = db.Where<RawMatch>(string.Format("LeagueId IN {0} AND SeasonId IN {1}", filter.Leagues.ToInCollection<Guid>(), filter.Seasons.ToInCollection<Guid>())); var teams = db.Where<Team>(string.Format("CountryId = '{0}'", filter.Country)); var matches = new List<Match>(); foreach (var season in filter.Seasons) { var seasonMatches = rawMatches.Where(m => m.SeasonId == season); MatchBuilder matchBuilder = new MatchBuilder(seasonMatches, teams, new TableBuilder(seasonMatches, teams)); matches.AddRange(matchBuilder.ProcessMatches()); } var result = matches.Filter(filter.Team1, filter.Team2); try { return Success<FilterResult>(result); } catch (Exception ex) { return Error(HttpStatusCode.InternalServerError, ex.Message); } }
public async Task <Either <BaseError, List <PlexMediaSource> > > GetServers() { try { var result = new List <PlexMediaSource>(); string clientIdentifier = await _plexSecretStore.GetClientIdentifier(); foreach (PlexUserAuthToken token in await _plexSecretStore.GetUserAuthTokens()) { List <PlexResource> httpResources = await _plexTvApi.GetResources( 0, clientIdentifier, token.AuthToken); List <PlexResource> httpsResources = await _plexTvApi.GetResources( 1, clientIdentifier, token.AuthToken); var allResources = httpResources.Filter(resource => resource.HttpsRequired == false) .Append(httpsResources.Filter(resource => resource.HttpsRequired)) .ToList(); IEnumerable <PlexResource> ownedResources = allResources .Filter(r => r.Provides.Split(",").Any(p => p == "server")) .Filter(r => r.Owned); // TODO: maybe support non-owned servers in the future foreach (PlexResource resource in ownedResources) { var serverAuthToken = new PlexServerAuthToken( resource.ClientIdentifier, resource.AccessToken); await _plexSecretStore.UpsertServerAuthToken(serverAuthToken); List <PlexResourceConnection> sortedConnections = resource.HttpsRequired ? resource.Connections : resource.Connections.OrderBy(c => c.Local ? 0 : 1).ToList(); var source = new PlexMediaSource { ServerName = resource.Name, ProductVersion = resource.ProductVersion, Platform = resource.Platform, PlatformVersion = resource.PlatformVersion, ClientIdentifier = resource.ClientIdentifier, Connections = sortedConnections .Map(c => new PlexConnection { Uri = c.Uri }).ToList() }; result.Add(source); } } return(result); } catch (ApiException apiException) { if (apiException.ReasonPhrase == "Unauthorized") { await _plexSecretStore.DeleteAll(); } return(BaseError.New(apiException.Message)); } catch (Exception ex) { _logger.LogError(ex, "Error getting plex servers"); return(BaseError.New(ex.Message)); } }
static void Main(string[] args) { //string path = @"C:\windows"; //ShowLageFilesWithoutLinq(path); //Console.WriteLine("******"); //ShowLageFilesWithLinq(path); Func <int, int> square = x => x * x; //Func<int, int, int> Add = (x, y) => x + y; Func <int, int, int> Add = (x, y) => { var temp = x + y; return(temp); }; Console.WriteLine(square(3)); Console.WriteLine(Add(3, 4)); //Action method take one param and return void Action <int> Write = x => Console.WriteLine(x); Write(2); IEnumerable <Employee> developers = new Employee[] { new Employee { Id = 1, Name = "Scott" }, new Employee { Id = 2, Name = "Zuko" } }; IEnumerable <Employee> sales = new List <Employee>() { new Employee { Id = 3, Name = "Zzuko" } }; Console.WriteLine(sales.Count()); IEnumerator <Employee> enumerator = developers.GetEnumerator(); while (enumerator.MoveNext()) { Console.WriteLine(enumerator.Current.Name); } //use named method foreach (var employee in developers.Where(NameStartsWithS)) { Console.WriteLine(employee.Name); } //use anonymous method foreach (var employee in developers.Where( delegate(Employee employee) { return(employee.Name.StartsWith("S")); })) { Console.WriteLine(employee.Name); } //use lambda exp foreach (var employee in developers.Where( e => e.Name.StartsWith("S"))) { Console.WriteLine(employee.Name); } var query2 = from developer in developers where developer.Name.Length == 5 orderby developer.Name descending select developer; Console.WriteLine(query2.Count()); foreach (var dev in query2) { Console.WriteLine(dev.Name); } Console.WriteLine("****************************************************************"); var movies = new List <Movie> { new Movie { Title = "The Dark Knight", Rating = 8.9f, Year = 2021 }, new Movie { Title = "The Dark Hallow", Rating = 8.5f, Year = 2021 }, new Movie { Title = "The Light Knight", Rating = 8.4f, Year = 2000 } }; var query = movies.Where(m => m.Year > 2000); foreach (var m in query) { Console.WriteLine(m.Title); } Console.WriteLine("*****************"); var query3 = movies.Filter(m => m.Year > 2000); //foreach (var m in query3) //{ // Console.WriteLine(m.Title); //} var enumerator1 = query3.GetEnumerator(); while (enumerator1.MoveNext()) { Console.WriteLine(enumerator1.Current.Title); } Console.WriteLine("------------------------------------------------------------------"); var cars = ProcessFile("fuel.csv"); foreach (var car in cars) { Console.WriteLine(car.Name); } Console.WriteLine("fuel efiicient --------------"); var queryCars = cars.OrderByDescending(c => c.Combined) .ThenBy(c => c.Name); //then by gives the capability of secondary sort foreach (var car in queryCars.Take(10)) { Console.WriteLine($"{car.Name}-{car.Combined}"); } Console.WriteLine("--------------"); //with query var manufacturers = ProcessManufacturer("manufacturers.csv"); var queryCars2 = from car in cars join manufacturer in manufacturers on car.Manufacturer equals manufacturer.Name orderby car.Combined descending, car.Name ascending select new { manufacturer.Headquarters, car.Name, car.Combined }; foreach (var car in queryCars2.Take(10)) { Console.WriteLine($"{car.Name}-{car.Combined}-{car.Headquarters}"); } Console.WriteLine("-------------------------------------------------------"); var queryCars3 = cars.Join(manufacturers, c => c.Manufacturer, m => m.Name, (c, m) => new { Car = c, Manufacturer = m }) .OrderByDescending(c => c.Car.Combined) .ThenBy(c => c.Car.Name) .Select(c => new { c.Manufacturer.Headquarters, c.Car.Name, c.Car.Combined }); foreach (var car in queryCars3.Take(10)) { Console.WriteLine($"{car.Name}-{car.Combined}-{car.Headquarters}"); } Console.WriteLine("---------------------------------------------------"); //to join on two things //to check the equality both side should have same property like year and Manufacturer var queryCars4 = from car in cars join manufacturer in manufacturers on new { car.Manufacturer, car.Year } equals new { Manufacturer = manufacturer.Name, manufacturer.Year } orderby car.Combined descending, car.Name ascending select new { manufacturer.Headquarters, car.Name, car.Combined }; foreach (var car in queryCars4.Take(10)) { Console.WriteLine($"{car.Name}-{car.Combined}-{car.Headquarters}"); } Console.WriteLine("-------------------------------------------------------"); var queryCars5 = cars.Join(manufacturers, c => new { c.Manufacturer, c.Year }, m => new { Manufacturer = m.Name, m.Year }, (c, m) => new { Car = c, Manufacturer = m }) .OrderByDescending(c => c.Car.Combined) .ThenBy(c => c.Car.Name) .Select(c => new { c.Manufacturer.Headquarters, c.Car.Name, c.Car.Combined }); foreach (var car in queryCars5.Take(10)) { Console.WriteLine($"{car.Name}-{car.Combined}-{car.Headquarters}"); } Console.WriteLine("---------------------------------------------------"); var queryCars6 = from car in cars group car by car.Manufacturer.ToUpper() into manufacture orderby manufacture.Key select manufacture; foreach (var group in queryCars6) { Console.WriteLine(group.Key); foreach (var car in group.OrderByDescending(c => c.Combined).Take(2)) { Console.WriteLine($"\t{car.Name}:{car.Combined}"); } } Console.WriteLine("---------------------------------------------------"); var queryCars7 = cars.GroupBy(c => c.Manufacturer.ToUpper()) .OrderBy(g => g.Key); foreach (var group in queryCars7) { Console.WriteLine(group.Key); foreach (var car in group.OrderByDescending(c => c.Combined).Take(2)) { Console.WriteLine($"\t{car.Name}:{car.Combined}"); } } Console.WriteLine("-----------------------Group join----------------------------"); var queryCars8 = from manufacturer in manufacturers join car in cars on manufacturer.Name equals car.Manufacturer into carGroup select new { Manufacturer = manufacturer, Cars = carGroup }; foreach (var group in queryCars8) { Console.WriteLine(group.Manufacturer.Name); foreach (var car in group.Cars.OrderByDescending(c => c.Combined).Take(2)) { Console.WriteLine($"\t{car.Name}:{car.Combined}"); } } Console.WriteLine("-----------------------Group join----------------------------"); var queryCars9 = manufacturers.GroupJoin(cars, m => m.Name, c => c.Manufacturer, (m, g) => new { Cars = g, Manufacturer = m }) .OrderBy(m => m.Manufacturer.Name); foreach (var group in queryCars9) { Console.WriteLine(group.Manufacturer.Name); foreach (var car in group.Cars.OrderByDescending(c => c.Combined).Take(2)) { Console.WriteLine($"\t{car.Name}:{car.Combined}"); } } Console.WriteLine("-----------------------Group join----------------------------"); var queryCars10 = from car in cars group car by car.Manufacturer into carGroup select new { Name = carGroup.Key, Max = carGroup.Max(c => c.Combined), Min = carGroup.Min(c => c.Combined), Avg = carGroup.Average(c => c.Combined) }; foreach (var result3 in queryCars10) { Console.WriteLine(result3.Name); Console.WriteLine(result3.Max); Console.WriteLine(result3.Min); Console.WriteLine(result3.Avg); } var top = cars.Where(c => c.Manufacturer == "BMW" && c.Year == 2016) .OrderByDescending(c => c.Combined) .ThenBy(c => c.Name) .Select(c => c) .First(); Console.WriteLine("-------------"); Console.WriteLine(top.Name); var top1 = cars .OrderByDescending(c => c.Combined) .ThenBy(c => c.Name) .Select(c => c) .First(c => c.Manufacturer == "BMW" && c.Year == 2016); Console.WriteLine("-------------"); Console.WriteLine(top1.Name); var result = cars.Any(c => c.Manufacturer == "Ford"); Console.WriteLine("-------------"); Console.WriteLine(result); var result2 = cars.All(c => c.Manufacturer == "Ford"); Console.WriteLine("-------------"); Console.WriteLine(result2); }
/// <summary> /// Filter short-hand for filtering on ascending order, element-by-element, count-based sample size. /// </summary> /// <typeparam name="T1"></typeparam> /// <param name="source"></param> /// <param name="sampleSize"></param> /// <returns></returns> public static List <T1> Filter <T1>(this List <T1> source, int sampleSize) { var i = 0; return(source.Filter(item => i++ < sampleSize)); }
static void Main(string[] args) { IEnumerable <int> numbers = new List <int> { 2, 3, 5, 7, 8, 11, 13, 16 }; // 3 5 7 11 13 // {1.73, 2.23, 2.64, 3.31, 3.60} //var result = GetMappedItems(numbers.Filter(n => n % 2 == 1), n => Math.Sqrt(n)); var result = numbers .Where(n => n % 2 == 1) .Select(n => Math.Sqrt(n)); result.PrintItems(); var otherResults = from n in numbers where n % 2 == 1 select Math.Sqrt(n); otherResults.PrintItems(); var cubes = numbers .Filter(n => n % 2 == 0) .Map(n => n * n * n) .Map(n => Math.Sqrt(n)); cubes.PrintItems(); var names = InitPersons() .Map(p => $"{p.LastName}, {p.FirstName}"); names.PrintItems(); IEnumerable <int> ages = InitPersons().Select(p => p.Age).ToList(); Console.WriteLine(ages.GetType().Name); ages.PrintItems(); var groups = InitPersons() .GroupBy(p => p.LastName) .Where(group => group.Count() > 1) .ToDictionary(g => g.Key, g => g.ToList()); foreach (var group in groups) { Console.WriteLine(group.Key); group.Value.PrintItems(); } var sumAge = InitPersons().Sum(p => p.Age); var aggAge = InitPersons().Aggregate(0, (a, p) => a + p.Age); Console.WriteLine(sumAge); Console.WriteLine(aggAge); var sum = string.Empty; foreach (var item in InitPersons()) { sum = sum + " " + item.LastName; } var aggLastName = InitPersons().Aggregate(string.Empty, (a, p) => a + " " + p.LastName); Console.WriteLine(aggLastName); var persons = groups.SelectMany(g => g.Value).ToList(); persons.PrintItems(); }
static void Main(string[] args) { List<Employee> workers = new List<Employee> { new Employee("vasia","pupkin",2000,2), new Employee("vasia","fedorov",2000,3), new Employee("vasia","ivanov",2000,5), new Employee("vasia","volkov",2000,10), new Employee("vasia","durov",22000,22), new Employee("vasia","vetkin",2000,30), new Employee("vasia","chrushov",2000,13), new Employee("petia","pupkin",4000,1), }; Console.WriteLine("\tWorkers wtih work age > 10"); var oldWorkers = workers.Filter(X=>X.WorkAge>10); foreach (var i in oldWorkers) Console.WriteLine(i.ToString()); Console.WriteLine("\n\tOld Workers wtih salary < 4000"); var smallSalary = oldWorkers.Filter(x=>x.salary<4000); foreach (var i in smallSalary) Console.WriteLine(i.ToString()); Console.ReadKey(); }
/// <summary> /// Method used to perform activity if it can occur as soon as resources are available. /// </summary> public override void DoActivity() { List <Ruminant> herd = CurrentHerd(false); if (herd != null && herd.Count > 0) { // calculate feed limit double feedLimit = 0.0; double wastage = 1.0 - this.ProportionTramplingWastage; double dailyAmountShortfall = 1.0; ResourceRequest feedRequest = ResourceRequestList.Where(a => a.ResourceType == typeof(AnimalFoodStore)).FirstOrDefault(); FoodResourcePacket details = new FoodResourcePacket(); if (feedRequest != null) { details = feedRequest.AdditionalDetails as FoodResourcePacket; feedLimit = Math.Min(1.0, feedRequest.Provided / feedRequest.Required); } // feed animals int month = Clock.Today.Month - 1; if (feedRequest == null || (feedRequest.Required == 0 | feedRequest.Available == 0)) { Status = ActivityStatus.NotNeeded; return; } // if feed style is fixed daily amount compare amount received against herd requirement. // this produces a reduction from potential intake for each individual. if (FeedStyle == RuminantFeedActivityTypes.SpecifiedDailyAmount) { double herdRequirement = 0; foreach (Model child in this.Children.Where(a => a.GetType().ToString().Contains("RuminantFeedGroup"))) { herdRequirement += herd.Filter(child).Sum(a => a.PotentialIntake - a.Intake); } dailyAmountShortfall = Math.Min(1.0, (feedRequest.Provided * wastage) / herdRequirement); } // get list from filters foreach (Model child in this.Children.Where(a => a.GetType().ToString().Contains("RuminantFeedGroup"))) { double value = 0; if (child is RuminantFeedGroup) { value = (child as RuminantFeedGroup).Value; } else { value = (child as RuminantFeedGroupMonthly).MonthlyValues[month]; } foreach (Ruminant ind in herd.Filter(child)) { switch (FeedStyle) { case RuminantFeedActivityTypes.SpecifiedDailyAmount: details.Amount = (ind.PotentialIntake - ind.Intake); details.Amount *= dailyAmountShortfall; ind.AddIntake(details); break; case RuminantFeedActivityTypes.SpecifiedDailyAmountPerIndividual: details.Amount = value * 30.4; // * ind.Number; details.Amount *= feedLimit * wastage; ind.AddIntake(details); break; case RuminantFeedActivityTypes.ProportionOfWeight: details.Amount = value * ind.Weight * 30.4; // * ind.Number; details.Amount *= feedLimit * wastage; ind.AddIntake(details); break; case RuminantFeedActivityTypes.ProportionOfPotentialIntake: details.Amount = value * ind.PotentialIntake; // * ind.Number; details.Amount *= feedLimit * wastage; ind.AddIntake(details); break; case RuminantFeedActivityTypes.ProportionOfRemainingIntakeRequired: details.Amount = value * (ind.PotentialIntake - ind.Intake); // * ind.Number; details.Amount *= feedLimit * wastage; ind.AddIntake(details); break; default: throw new Exception("Feed style used [" + FeedStyle + "] not implemented in [" + this.Name + "]"); } } } SetStatusSuccess(); } }
/// <summary> /// Determines how much labour is required from this activity based on the requirement provided /// </summary> /// <param name="requirement">The details of how labour are to be provided</param> /// <returns></returns> public override double GetDaysLabourRequired(LabourRequirement requirement) { List <Ruminant> herd = CurrentHerd(false); int head = 0; double adultEquivalents = 0; foreach (Model child in this.Children.Where(a => a.GetType().ToString().Contains("RuminantFeedGroup"))) { var subherd = herd.Filter(child).ToList(); head += subherd.Count(); adultEquivalents += subherd.Sum(a => a.AdultEquivalent); } double daysNeeded = 0; double numberUnits = 0; switch (requirement.UnitType) { case LabourUnitType.Fixed: daysNeeded = requirement.LabourPerUnit; break; case LabourUnitType.perHead: numberUnits = head / requirement.UnitSize; if (requirement.WholeUnitBlocks) { numberUnits = Math.Ceiling(numberUnits); } daysNeeded = numberUnits * requirement.LabourPerUnit; break; case LabourUnitType.perAE: numberUnits = adultEquivalents / requirement.UnitSize; if (requirement.WholeUnitBlocks) { numberUnits = Math.Ceiling(numberUnits); } daysNeeded = numberUnits * requirement.LabourPerUnit; break; case LabourUnitType.perKg: daysNeeded = feedRequired * requirement.LabourPerUnit; break; case LabourUnitType.perUnit: numberUnits = feedRequired / requirement.UnitSize; if (requirement.WholeUnitBlocks) { numberUnits = Math.Ceiling(numberUnits); } daysNeeded = numberUnits * requirement.LabourPerUnit; break; default: throw new Exception(String.Format("LabourUnitType {0} is not supported for {1} in {2}", requirement.UnitType, requirement.Name, this.Name)); } return(daysNeeded); }
/// <summary> /// Method to determine resources required for this activity in the current month /// </summary> /// <returns>List of required resource requests</returns> public override List <ResourceRequest> GetResourcesNeededForActivity() { List <Ruminant> herd = CurrentHerd(false); // get zero limited month from clock int month = Clock.Today.Month - 1; feedRequired = 0; // get list from filters foreach (Model child in this.Children.Where(a => a.GetType().ToString().Contains("RuminantFeedGroup"))) { double value = 0; if (child is RuminantFeedGroup) { value = (child as RuminantFeedGroup).Value; } else { value = (child as RuminantFeedGroupMonthly).MonthlyValues[month]; } if (FeedStyle == RuminantFeedActivityTypes.SpecifiedDailyAmount) { feedRequired += value * 30.4; } else { foreach (Ruminant ind in herd.Filter(child)) { switch (FeedStyle) { case RuminantFeedActivityTypes.SpecifiedDailyAmountPerIndividual: feedRequired += value * 30.4; break; case RuminantFeedActivityTypes.ProportionOfWeight: feedRequired += value * ind.Weight * 30.4; break; case RuminantFeedActivityTypes.ProportionOfPotentialIntake: feedRequired += value * ind.PotentialIntake; break; case RuminantFeedActivityTypes.ProportionOfRemainingIntakeRequired: feedRequired += value * (ind.PotentialIntake - ind.Intake); break; default: throw new Exception(String.Format("FeedStyle {0} is not supported in {1}", FeedStyle, this.Name)); } } } } if (feedRequired > 0) { //FeedTypeName includes the ResourceGroup name eg. AnimalFoodStore.FeedItemName string feedItemName = FeedTypeName.Split('.').Last(); return(new List <ResourceRequest>() { new ResourceRequest() { AllowTransmutation = true, Required = feedRequired, ResourceType = typeof(AnimalFoodStore), ResourceTypeName = feedItemName, ActivityModel = this } }); } else { return(null); } }
public static Tuple <List <Card>, List <Card>, string, string> GetCards(int i) { if (schools == null) { Init(); } List <Card> tmp1 = new List <Card>(); List <Card> tmp2 = new List <Card>(); string str1; string str2; var tmp = new List <School>(); int counter = 0; do { counter++; tmp1 = new List <Card>(); tmp2 = new List <Card>(); schools.Shuffle(); tmp = schools.Shuffle().Take(2).ToList(); for (int j = 3 * i; j < 3 * i + 3; j++) { tmp1.Add(tmp[0].cards.Filter(card => card.star == starList[j]).GetOneRandomly()); } for (int j = 3 * i; j < 3 * i + 3; j++) { tmp2.Add(tmp[1].cards.Filter(card => card.star == starList[j]).GetOneRandomly()); } }while ((tmp1.Contains(null) || tmp2.Contains(null) || (tmp1.Distinct()).Count() < 3 || (tmp2.Distinct()).Count() < 3) && counter < 20); str1 = tmp[0].name; str2 = tmp[1].name; if (counter >= 20) { var tmpCards = new List <Card>(); foreach (var scool in schools) { foreach (var item in scool.cards) { tmpCards.Add(item); } } tmpCards.Distinct(); do { if (tmp1.Contains(null) || tmp1.Distinct().Count() < 3) { tmp1.Clear(); for (int j = 3 * i; j < 3 * i + 3; j++) { tmp1.Add(tmpCards.Filter(card => card.star == starList[j]).GetOneRandomly()); } Debug.Log("牌堆1生成失败,随机发牌"); str1 = "混沌"; } if (tmp2.Contains(null) || tmp2.Distinct().Count() < 3) { tmp2.Clear(); for (int j = 3 * i; j < 3 * i + 3; j++) { tmp2.Add(tmpCards.Filter(card => card.star == starList[j]).GetOneRandomly()); } Debug.Log("牌堆2生成失败,随机发牌"); str2 = "混沌"; } }while ((tmp1.Contains(null) || tmp2.Contains(null) || (tmp1.Distinct()).Count() < 3 || (tmp2.Distinct()).Count() < 3)); } return(new Tuple <List <Card>, List <Card>, string, string>(tmp1, tmp2, str1, str2)); }
[System.Web.Http.Route("api/Profiles")] // was AllProfiles public ServiceResult GetAllUserProfiles() { ProfileManager profileManager = new ProfileManager(Globals.DBConnectionKey, this.GetAuthToken(Request)); UserManager userManager = new UserManager(Globals.DBConnectionKey, this.GetAuthToken(Request)); LocationManager locationManager = new LocationManager(Globals.DBConnectionKey, this.GetAuthToken(Request)); _profileMemberManager = new ProfileMemberManager(Globals.DBConnectionKey, this.GetAuthToken(Request)); List <Profile> tmp = new List <Profile>(); DataFilter filter = this.GetFilter(Request); if (CurrentUser == null) //not logged in. { tmp = profileManager.GetPublicProfiles(ref filter); } else { tmp = profileManager.GetAllProfiles(ref filter); } if (tmp == null) { return(ServiceResponse.OK("", new List <Profile>())); } List <dynamic> profiles = tmp.Cast <dynamic>().ToList(); //profileManager.GetAllProfiles().Cast<dynamic>().ToList(); profiles = profiles.Filter(ref filter); var defaultFilter = new DataFilter(); // todo add profile Members? or rename profileLogs to profileMembers? so you can map multiple users to one profile // if profileLogs remember to sort by sortOrder _profileMemberManager = new ProfileMemberManager(Globals.DBConnectionKey, this.GetAuthToken(Request)); profiles = profiles.Select(s => new { Name = s.Name, UUID = s.UUID, AccountUUID = s.AccountUUID, UUIDType = s.UUIDType, Image = s.Image, NSFW = s.NSFW, // Email = s.Email, Active = s.Active, Description = s.Description, Members = string.IsNullOrWhiteSpace(s.MembersCache) ? _profileMemberManager.GetProfileMembers(s.UUID, s.AccountUUID, ref filter) : JsonConvert.DeserializeObject <List <ProfileMember> >(s.MembersCache), User = string.IsNullOrWhiteSpace(s.UserCache) ? ConvertResult(userManager.Get(s.UserUUID)) : JsonConvert.DeserializeObject <User>(s.UserCache), LocationDetail = string.IsNullOrWhiteSpace(s.LocationDetailCache) ? ConvertLocationResult(locationManager.Get(s.LocationUUID)) : JsonConvert.DeserializeObject <Location>(s.LocationDetailCache), // this.selectedProfile.LocationUUID = data.UUID; //this.selectedProfile.LocationType = data.LocationType; //single,married,ply, + genders by age? so ply-mfmfm // Profile.cs todo add to profileLogs/Members //Location { get; set; } //LocationType { get; set; } //Theme { get; set; } //View { get; set; } //UserUUID { get; set; } // // Node.cs //Status = string.Empty; //AccountUUID = string.Empty; //Deleted = false; //Private = true; //SortOrder = 0; //CreatedBy = string.Empty; //DateCreated = DateTime.MinValue; //RoleWeight = RoleFlags.MemberRoleWeights.Member; //RoleOperation = ">="; //Image = ""; }).Cast <dynamic>().ToList(); return(ServiceResponse.OK("", profiles, filter.TotalRecordCount)); }
static void Main(string[] args) { Console.WriteLine("Hello World!"); IQueryable <Employee> query = new List <Employee>() { new Employee() { FirstName = "aa XXx1 dd c", LastName = "aa yyyy1 v v", Subordinates = new List <Person> { new Person { Name = "Some person" }, new Person { Name = "Some person" } } }, new Employee() { FirstName = "aa xxx3 dd c", LastName = "aa yyyy1 v v", }, new Employee() { FirstName = "aa xxx2 dd c", LastName = "aa yyyy1 v v", Subordinates = new List <Person> { new Person { Name = "Some person" }, new Person { Name = "Some person" }, } }, }.AsQueryable(); var filterElement = new FilterCollection <Employee>() { Elements = new List <IFilterElement> { new FilterCollection <Employee>() { Elements = new List <IFilterElement> { new FilterElement { Property = "FirstName", Operator = new ToLowerDecorator(new TrimDecorator(new ContainsOperator())), Value = "xxx1" }, new FilterElement { Property = "Subordinates", Operator = new CountOperator(), Value = 2 }, }, Operator = new OrOperator() }, new FilterElement { Property = "LastName", Operator = new ContainsOperator(), Value = "yyyy1" }, }, Operator = new AndOperator() }; var result = query.Filter(filterElement).ToList(); }
/// <summary> /// Method used to perform activity if it can occur as soon as resources are available. /// </summary> public override void DoActivity() { List <Ruminant> herd = CurrentHerd(false); if (herd != null && herd.Count > 0) { double feedLimit = 0.0; ResourceRequest feedRequest = ResourceRequestList.Where(a => a.ResourceType == typeof(AnimalFoodStore)).LastOrDefault(); FoodResourcePacket details = new FoodResourcePacket(); if (feedRequest != null) { details = feedRequest.AdditionalDetails as FoodResourcePacket; feedLimit = Math.Min(1.0, feedRequest.Provided / feedRequest.Required); } // feed animals if (feedRequest == null || (feedRequest.Required == 0 | feedRequest.Available == 0)) { Status = ActivityStatus.NotNeeded; return; } // get list from filters foreach (Model child in this.Children.Where(a => a.GetType().ToString().Contains("RuminantFeedGroup"))) { double value = 0; if (child is RuminantFeedGroup) { value = (child as RuminantFeedGroup).Value; } else { value = (child as RuminantFeedGroupMonthly).MonthlyValues[Clock.Today.Month - 1]; } foreach (Ruminant ind in herd.Filter(child)) { switch (FeedStyle) { case RuminantFeedActivityTypes.SpecifiedDailyAmount: case RuminantFeedActivityTypes.ProportionOfFeedAvailable: details.Amount = ((ind.PotentialIntake * (usingPotentialintakeMultiplier ? ind.BreedParams.OverfeedPotentialIntakeModifier : 1)) - ind.Intake); details.Amount *= feedLimit; break; case RuminantFeedActivityTypes.SpecifiedDailyAmountPerIndividual: details.Amount = value * 30.4; details.Amount *= feedLimit; break; case RuminantFeedActivityTypes.ProportionOfWeight: details.Amount = value * ind.Weight * 30.4; details.Amount *= feedLimit; break; case RuminantFeedActivityTypes.ProportionOfPotentialIntake: details.Amount = value * ind.PotentialIntake; details.Amount *= feedLimit; break; case RuminantFeedActivityTypes.ProportionOfRemainingIntakeRequired: details.Amount = value * (ind.PotentialIntake - ind.Intake); details.Amount *= feedLimit; break; default: throw new Exception("Feed style used [" + FeedStyle + "] not implemented in [" + this.Name + "]"); } // check amount meets intake limits if (usingPotentialintakeMultiplier) { if (details.Amount > (ind.PotentialIntake + (Math.Max(0, ind.BreedParams.OverfeedPotentialIntakeModifier - 1) * overfeedProportion * ind.PotentialIntake)) - ind.Intake) { details.Amount = (ind.PotentialIntake + (Math.Max(0, ind.BreedParams.OverfeedPotentialIntakeModifier - 1) * overfeedProportion * ind.PotentialIntake)) - ind.Intake; } } ind.AddIntake(details); } } SetStatusSuccess(); } }
public void DoesNotThrowForNullFilter() { var queryable = new List <string>().AsQueryable(); var actual = queryable.Filter(null, x => y => y != null, true); }
internal static List <Edge> SelectEdgesForSitePointF(PointF coord, List <Edge> edgesToTest) { _coord = coord; return(edgesToTest.Filter(MyTest)); }
public IList<WebChannelState> GetAllRadioChannelStatesForGroup(int groupId, string userName, string filter = null) { IList<WebChannelBasic> list = GetRadioChannelsBasic(groupId); IList<WebChannelState> webChannelStates = new List<WebChannelState>(); foreach (WebChannelBasic entry in list) { webChannelStates.Add(GetChannelState(entry.Id, userName)); } return webChannelStates.Filter(filter).ToList(); }
private List <Edge> HullEdges() { return(_edges.Filter(MyTestHullEdges)); }
/// <summary> /// Method used to perform activity if it can occur as soon as resources are available. /// </summary> public override void DoActivity() { List <Ruminant> herd = CurrentHerd(false); if (herd != null && herd.Count > 0) { // calculate labour limit double labourLimit = 1; double labourNeeded = ResourceRequestList.Where(a => a.ResourceType == typeof(Labour)).Sum(a => a.Required); double labourProvided = ResourceRequestList.Where(a => a.ResourceType == typeof(Labour)).Sum(a => a.Provided); if (labourNeeded > 0) { labourLimit = labourProvided / labourNeeded; } // calculate feed limit double feedLimit = 0.0; double wastage = 1.0 - this.ProportionTramplingWastage; ResourceRequest feedRequest = ResourceRequestList.Where(a => a.ResourceType == typeof(AnimalFoodStore)).FirstOrDefault(); FoodResourcePacket details = new FoodResourcePacket(); if (feedRequest != null) { details = feedRequest.AdditionalDetails as FoodResourcePacket; feedLimit = Math.Min(1.0, feedRequest.Provided / feedRequest.Required); } // feed animals int month = Clock.Today.Month - 1; SetStatusSuccess(); // get list from filters foreach (RuminantFeedGroup child in Apsim.Children(this, typeof(RuminantFeedGroup))) { foreach (Ruminant ind in herd.Filter(child as RuminantFeedGroup)) { switch (FeedStyle) { case RuminantFeedActivityTypes.SpecifiedDailyAmount: details.Amount = (child as RuminantFeedGroup).MonthlyValues[month] * 30.4; details.Amount *= feedLimit * labourLimit * wastage; ind.AddIntake(details); break; case RuminantFeedActivityTypes.ProportionOfWeight: details.Amount = (child as RuminantFeedGroup).MonthlyValues[month] * ind.Weight * 30.4; // * ind.Number; details.Amount *= feedLimit * labourLimit * wastage; ind.AddIntake(details); break; case RuminantFeedActivityTypes.ProportionOfPotentialIntake: details.Amount = (child as RuminantFeedGroup).MonthlyValues[month] * ind.PotentialIntake; // * ind.Number; details.Amount *= feedLimit * labourLimit * wastage; ind.AddIntake(details); break; case RuminantFeedActivityTypes.ProportionOfRemainingIntakeRequired: details.Amount = (child as RuminantFeedGroup).MonthlyValues[month] * (ind.PotentialIntake - ind.Intake); // * ind.Number; details.Amount *= feedLimit * labourLimit * wastage; ind.AddIntake(details); break; default: break; } } } } }
public async Task <Option <Subtitle> > SelectSubtitleStream( MediaVersion version, List <Subtitle> subtitles, StreamingMode streamingMode, string channelNumber, string preferredSubtitleLanguage, ChannelSubtitleMode subtitleMode) { if (subtitleMode == ChannelSubtitleMode.None) { return(None); } if (streamingMode == StreamingMode.HttpLiveStreamingDirect && string.IsNullOrWhiteSpace(preferredSubtitleLanguage)) { // _logger.LogDebug( // "Channel {Number} is HLS Direct with no preferred subtitle language; using all subtitle streams", // channel.Number); return(None); } string language = (preferredSubtitleLanguage ?? string.Empty).ToLowerInvariant(); if (string.IsNullOrWhiteSpace(language)) { _logger.LogDebug("Channel {Number} has no preferred subtitle language code", channelNumber); } else { // filter to preferred language List <string> allCodes = await _searchRepository.GetAllLanguageCodes(new List <string> { language }); subtitles = subtitles .Filter( s => allCodes.Any(c => string.Equals(s.Language, c, StringComparison.InvariantCultureIgnoreCase))) .ToList(); } if (subtitles.Count > 0) { switch (subtitleMode) { case ChannelSubtitleMode.Forced: foreach (Subtitle subtitle in subtitles.OrderBy(s => s.StreamIndex).Find(s => s.Forced)) { return(subtitle); } break; case ChannelSubtitleMode.Default: foreach (Subtitle subtitle in subtitles.OrderBy(s => s.Default ? 0 : 1).ThenBy(s => s.StreamIndex)) { return(subtitle); } break; case ChannelSubtitleMode.Any: foreach (Subtitle subtitle in subtitles.OrderBy(s => s.StreamIndex).HeadOrNone()) { return(subtitle); } break; } } _logger.LogDebug( "Found no subtitles for channel {ChannelNumber} with mode {Mode} matching language {Language}", channelNumber, subtitleMode, preferredSubtitleLanguage); return(None); }
public async Task <FabricAuthUserSearchResponse> Search(IdentitySearchRequest request) { var searchResults = new List <IdentitySearchResponse>(); if (string.IsNullOrWhiteSpace(request.ClientId)) { throw new BadRequestException <IdentitySearchRequest>("Client ID is required."); } var client = await _clientService.GetClient(request.ClientId); var clientRoles = await _roleService.GetRoles(client); var clientRoleEntities = clientRoles.ToList(); _logger.Debug($"clientRoles = {clientRoleEntities.ListToString()}"); if (clientRoleEntities.Count == 0) { return(new FabricAuthUserSearchResponse { HttpStatusCode = Nancy.HttpStatusCode.OK, Results = new List <IdentitySearchResponse>() }); } // get all groups tied to clientRoles var groupIds = clientRoleEntities.SelectMany(r => r.Groups).Distinct().ToList(); _logger.Debug($"groupIds = {groupIds.ListToString()}"); if (groupIds.Count == 0) { return(new FabricAuthUserSearchResponse { HttpStatusCode = Nancy.HttpStatusCode.OK, Results = new List <IdentitySearchResponse>() }); } var groupEntities = new List <Group>(); foreach (var groupId in groupIds) { var group = await _groupService.GetGroup(groupId, request.ClientId); groupEntities.Add(group); } _logger.Debug($"groupEntities = {groupEntities.ListToString()}"); var groupsMappedToClientRoles = groupEntities.Where(g => g.Roles.Any(r => clientRoleEntities.Contains(r))).ToList(); var nonCustomGroups = groupsMappedToClientRoles.Where(g => !string.Equals(g.Source, GroupConstants.CustomSource, StringComparison.OrdinalIgnoreCase)).ToList(); _logger.Debug($"nonCustomGroups = {nonCustomGroups.ListToString()}"); // add all non-custom groups to the response searchResults.AddRange(nonCustomGroups.Select(g => new IdentitySearchResponse { GroupName = g.Name, Roles = g.Roles.Select(r => r.Name), EntityType = IdentitySearchResponseEntityType.Group.ToString() })); // get all users mapped to groups in client roles var users = groupsMappedToClientRoles .Where(g => g.Users != null && g.Users.Count > 0) .SelectMany(g => g.Users) .DistinctBy(u => u.SubjectId); var userList = new List <IdentitySearchResponse>(); foreach (var user in users) { // get groups for user var userGroups = user.Groups; var userGroupEntities = groupEntities.Where(g => userGroups.Contains(g.Name, StringComparer.OrdinalIgnoreCase)); // get roles for user var userRoles = userGroupEntities.SelectMany(g => g.Roles).Select(r => r.Name); // add user to response userList.Add(new IdentitySearchResponse { SubjectId = user.SubjectId, IdentityProvider = user.IdentityProvider, Roles = userRoles, EntityType = IdentitySearchResponseEntityType.User.ToString() }); } var fabricIdentityUserResponse = await _identityServiceProvider.Search(request.ClientId, userList.Select(u => $"{u.SubjectId}:{u.IdentityProvider}")); if (fabricIdentityUserResponse != null && fabricIdentityUserResponse.HttpStatusCode == System.Net.HttpStatusCode.OK) { // update user details with Fabric.Identity response foreach (var user in fabricIdentityUserResponse.Results) { var userSearchResponse = userList.FirstOrDefault(u => string.Equals(u.SubjectId, user.SubjectId, StringComparison.OrdinalIgnoreCase)); if (userSearchResponse == null) { continue; } userSearchResponse.FirstName = user.FirstName; userSearchResponse.MiddleName = user.MiddleName; userSearchResponse.LastName = user.LastName; userSearchResponse.LastLoginDateTimeUtc = user.LastLoginDate; } } searchResults.AddRange(userList); _logger.Debug($"searchResults = {searchResults.ListToString()}"); var pageSize = request.PageSize ?? 100; var pageNumber = request.PageNumber ?? 1; return(new FabricAuthUserSearchResponse { HttpStatusCode = fabricIdentityUserResponse != null && fabricIdentityUserResponse.HttpStatusCode != System.Net.HttpStatusCode.OK ? Nancy.HttpStatusCode.PartialContent : Nancy.HttpStatusCode.OK, Results = searchResults .Filter(request) .Sort(request) .Skip((pageNumber - 1) * pageSize) .Take(pageSize) }); }
/// <summary> /// Ctor /// </summary> public ClassInstancesAssembly() { try { Debug.WriteLine("Internal ctor"); var asms = GetAssemblies().ToList(); Debug.WriteLine($"Assemblies collected"); var asmNames = (from nam in asms where nam != null && nam.Name != "mscorlib" && !nam.Name.StartsWith("System.") && !nam.Name.StartsWith("Microsoft.") select nam) .ToList(); Debug.WriteLine($"Assemblies filtered"); var loadedAsms = (from nam in asmNames let asm = SafeLoadAsm(nam) where asm != null select asm) .ToList(); Debug.WriteLine($"Assemblies loaded"); var allTypes = (from asm in loadedAsms from typ in SafeGetTypes(asm) select typ) .ToList(); Debug.WriteLine($"Types collected"); Types = (from typ in allTypes where typ != null && !typ.FullName.StartsWith("<") && !typ.FullName.Contains("+<") select typ) .ToList(); Debug.WriteLine($"Types found: {Types.Count}"); Structs = Types.Filter(t => t?.IsValueType ?? false).ToList(); Debug.WriteLine($"Structs found: {Structs.Count}"); AllClassInstances = Structs.Filter(t => t?.GetTypeInfo().ImplementedInterfaces?.Exists(i => i == typeof(Typeclass)) ?? false).ToList(); Debug.WriteLine($"AllClassInstances found: {AllClassInstances.Count}"); ClassInstances = new Dict(); foreach (var ci in AllClassInstances) { var typeClasses = ci?.GetTypeInfo().ImplementedInterfaces ?.Filter(i => typeof(Typeclass).GetTypeInfo().IsAssignableFrom(i.GetTypeInfo())) ?.ToList() ?? new List <Type>(); foreach (var typeClass in typeClasses) { if (ClassInstances.ContainsKey(typeClass)) { ClassInstances[typeClass].Add(ci); } else { var nset = new GSet(); nset.Add(ci); ClassInstances.Add(typeClass, nset); } } } Debug.WriteLine($"ClassInstances found: {ClassInstances.Count}"); } catch (Exception e) { Debug.WriteLine($"Internal error: {e}"); Error = e; } }
/// <summary> /// Get value of a specific individual with special requirements check (e.g. breeding sire or draught purchase) /// </summary> /// <returns>value</returns> public double ValueofIndividual(Ruminant ind, PurchaseOrSalePricingStyleType purchaseStyle, RuminantFilterParameters property, string value) { double price = 0; if (PricingAvailable()) { string criteria = property.ToString().ToUpper() + ":" + value.ToUpper(); List <Ruminant> animalList = new List <Ruminant>() { ind }; //find first pricing entry matching specific criteria AnimalPriceGroup matchIndividual = null; AnimalPriceGroup matchCriteria = null; foreach (AnimalPriceGroup item in PriceList.FindAllChildren <AnimalPriceGroup>().Cast <AnimalPriceGroup>().Where(a => a.PurchaseOrSale == purchaseStyle || a.PurchaseOrSale == PurchaseOrSalePricingStyleType.Both)) { if (animalList.Filter(item).Count() == 1 && matchIndividual == null) { matchIndividual = item; } // check that pricing item meets the specified criteria. if (item.FindAllChildren <RuminantFilter>().Cast <RuminantFilter>().Where(a => (a.Parameter.ToString().ToUpper() == property.ToString().ToUpper() && a.Value.ToUpper() == value.ToUpper())).Count() > 0) { if (matchCriteria == null) { matchCriteria = item; } else { // multiple price entries were found. using first. value = xxx. if (!WarningsMultipleEntry.Contains(criteria)) { WarningsMultipleEntry.Add(criteria); Summary.WriteWarning(this, "Multiple specific [" + purchaseStyle.ToString() + "] price entries were found for [r=" + ind.Breed + "] where [" + property + "]" + (value.ToUpper() != "TRUE" ? " = [" + value + "]." : ".") + "\nOnly the first entry will be used. Price [" + matchCriteria.Value.ToString("#,##0.##") + "] [" + matchCriteria.PricingStyle.ToString() + "]."); } } } } if (matchCriteria == null) { // report specific criteria not found in price list string warningString = "No [" + purchaseStyle.ToString() + "] price entry was found for [r=" + ind.Breed + "] meeting the required criteria [" + property + "]" + (value.ToUpper() != "TRUE" ? " = [" + value + "]." : "."); if (matchIndividual != null) { // add using the best pricing available for [][] purchases of xx per head warningString += "\nThe best available price [" + matchIndividual.Value.ToString("#,##0.##") + "] [" + matchIndividual.PricingStyle.ToString() + "] will be used."; price = matchIndividual.Value * ((matchIndividual.PricingStyle == PricingStyleType.perKg) ? ind.Weight : 1.0); } else { warningString += "\nNo alternate price for individuals could be found for the individuals. Add a new [r=AnimalPriceGroup] entry in the [r=AnimalPricing] for [" + ind.Breed + "]"; } if (!WarningsNotFound.Contains(criteria)) { WarningsNotFound.Add(criteria); Summary.WriteWarning(this, warningString); } } else { price = matchCriteria.Value * ((matchCriteria.PricingStyle == PricingStyleType.perKg) ? ind.Weight : 1.0); } } return(price); }
/// <summary> /// Retrieve a ResourceType from a ResourceGroup based on a request item including filter and sort options /// </summary> /// <param name="Request">A resource request item</param> /// <param name="MissingResourceAction">Action to take if requested resource group not found</param> /// <param name="MissingResourceTypeAction">Action to take if requested resource type not found</param> /// <returns>A reference to the item of type Model</returns> public Model GetResourceItem(ResourceRequest Request, OnMissingResourceActionTypes MissingResourceAction, OnMissingResourceActionTypes MissingResourceTypeAction) { if (Request.FilterDetails != null) { if (Request.ResourceType == null) { string errorMsg = String.Format("Resource type must be supplied in resource request from {0}", Request.ActivityModel.Name); Summary.WriteWarning(Request.ActivityModel, String.Format("Resource type must be supplied in resource request from {0}", Request.ActivityModel.Name)); throw new Exception(errorMsg); } IModel resourceGroup = this.GetByType(Request.ResourceType); if (resourceGroup == null) { string errorMsg = String.Format("Unable to locate resources of type ({0}) for ({1})", Request.ResourceType, Request.ActivityModel.Name); switch (MissingResourceAction) { case OnMissingResourceActionTypes.ReportErrorAndStop: throw new Exception(errorMsg); case OnMissingResourceActionTypes.ReportWarning: Summary.WriteWarning(Request.ActivityModel, errorMsg); break; default: break; } return(null); } // get list of children matching the conditions in filter // and return the lowest item that has enough time available object resourceGroupObject = resourceGroup as object; switch (resourceGroupObject.GetType().ToString()) { case "Models.CLEM.Resources.Labour": // get matching labour types // use activity uid to ensure unique for this request List <LabourType> items = (resourceGroup as Labour).Items; items = items.Filter(Request.FilterDetails.FirstOrDefault() as Model); items = items.Where(a => a.LastActivityRequestID != Request.ActivityID).ToList(); if (items.Where(a => a.Amount >= Request.Required).Count() > 0) { // get labour least available but with the amount needed return(items.Where(a => a.Amount >= Request.Required).OrderByDescending(a => a.Amount).FirstOrDefault()); } else { // get labour with most available but with less than the amount needed return(items.OrderByDescending(a => a.Amount).FirstOrDefault()); } default: string errorMsg = "Resource cannot be filtered. Filtering not implemented for " + resourceGroupObject.GetType().ToString() + " from activity (" + Request.ActivityModel.Name + ")"; Summary.WriteWarning(Request.ActivityModel, errorMsg); throw new Exception(errorMsg); } } else { return(GetResourceItem(Request.ActivityModel, Request.ResourceType, Request.ResourceTypeName, MissingResourceAction, MissingResourceTypeAction)); } }
public void CollectionFiltersWithCorrectResults() { var testList = new List <TestClass> { new TestClass { ID = 1, TestOrder = 1, TestProperty = "Test1" }, new TestClass { ID = 2, TestOrder = 2, TestProperty = "Test1" }, new TestClass { ID = 3, TestOrder = 2, TestProperty = "Test2" }, new TestClass { ID = 4, TestOrder = 3, TestProperty = "Test3" } }; // Simple filter var filteredList1 = testList.Filter( new GetCollectionRequest { Filter = JsonConvert.SerializeObject(new FilterModel { Field = "TestProperty", Operator = FilterOperator.EndsWith, Value = "1" }) }, new NewtonsoftSerializationProvider()); Assert.AreEqual(2, filteredList1.Count(), "Filtered List 2 should contain 2 items."); Assert.IsTrue(filteredList1.Where(x => x.ID == 1).Any(), "Filtered List 1 should contain ID 1."); Assert.IsTrue(filteredList1.Where(x => x.ID == 2).Any(), "Filtered List 1 should contain ID 2."); // Complex AND filter var filteredList2 = testList.Filter( new GetCollectionRequest { Filter = JsonConvert.SerializeObject(new FilterModel { Logic = FilterLogic.And, ChildFilters = new List <FilterModel> { new FilterModel { Field = "TestProperty", Operator = FilterOperator.Equals, Value = "Test1" }, new FilterModel { Field = "TestOrder", Operator = FilterOperator.GreaterThan, Value = 1, ValueType = "int" }, } }) }, new NewtonsoftSerializationProvider()); Assert.AreEqual(1, filteredList2.Count(), "Filtered List 2 should contain 1 item."); Assert.AreEqual(2, filteredList2.First().ID, "Filtered List 2 should contain ID 2."); // Complex OR filter var filteredList3 = testList.Filter( new GetCollectionRequest { Filter = JsonConvert.SerializeObject(new FilterModel { Logic = FilterLogic.Or, ChildFilters = new List <FilterModel> { new FilterModel { Field = "TestProperty", Operator = FilterOperator.Equals, Value = "Test3" }, new FilterModel { Field = "TestOrder", Operator = FilterOperator.LessThanOrEqualTo, Value = 3, ValueType = "int" }, } }) }, new NewtonsoftSerializationProvider()); Assert.AreEqual(4, filteredList3.Count(), "Filtered List 3 should contain all 4 items."); }
public IEnumerable<string> GetNonNullNorEmptyStrings(List<string> inputData) { return inputData.Filter(s => !string.IsNullOrEmpty(s)); }
static void Main(string[] args) { IEnumerable<int> numbers = new List<int> { 2, 3, 5, 7, 8, 11, 13, 16 }; // 3 5 7 11 13 // {1.73, 2.23, 2.64, 3.31, 3.60} //var result = GetMappedItems(numbers.Filter(n => n % 2 == 1), n => Math.Sqrt(n)); var result = numbers .Where(n => n % 2 == 1) .Select(n => Math.Sqrt(n)); result.PrintItems(); var otherResults = from n in numbers where n % 2 == 1 select Math.Sqrt(n); otherResults.PrintItems(); var cubes = numbers .Filter(n => n % 2 == 0) .Map(n=> n*n*n) .Map(n => Math.Sqrt(n)); cubes.PrintItems(); var names = InitPersons() .Map(p => $"{p.LastName}, {p.FirstName}"); names.PrintItems(); IEnumerable<int> ages = InitPersons().Select(p => p.Age).ToList(); Console.WriteLine(ages.GetType().Name); ages.PrintItems(); var groups = InitPersons() .GroupBy(p => p.LastName) .Where(group => group.Count() > 1) .ToDictionary(g=> g.Key, g => g.ToList()); foreach (var group in groups) { Console.WriteLine(group.Key); group.Value.PrintItems(); } var sumAge = InitPersons().Sum(p => p.Age); var aggAge = InitPersons().Aggregate(0, (a, p) => a + p.Age); Console.WriteLine(sumAge); Console.WriteLine(aggAge); var sum = string.Empty; foreach (var item in InitPersons()) { sum = sum + " " + item.LastName; } var aggLastName = InitPersons().Aggregate(string.Empty, (a, p) => a + " " + p.LastName); Console.WriteLine(aggLastName); var persons = groups.SelectMany(g => g.Value).ToList(); persons.PrintItems(); }
/// <summary> /// Gets the property identified by <paramref name="name"/> on the given <paramref name="type"/>. /// Use the <paramref name="bindingFlags"/> parameter to define the scope of the search. /// </summary> /// <returns>A single PropertyInfo instance of the first found match or null if no match was found.</returns> public static PropertyInfo Property( this Type type, string name, Flags bindingFlags ) { // we need to check all properties to do partial name matches if( bindingFlags.IsAnySet( Flags.PartialNameMatch | Flags.TrimExplicitlyImplemented ) ) { return type.Properties( bindingFlags, name ).FirstOrDefault(); } var result = type.GetProperty( name, bindingFlags | Flags.DeclaredOnly ); if( result == null && bindingFlags.IsNotSet( Flags.DeclaredOnly ) ) { if( type.BaseType != typeof(object) && type.BaseType != null ) { return type.BaseType.Property( name, bindingFlags ); } } bool hasSpecialFlags = bindingFlags.IsSet( Flags.ExcludeExplicitlyImplemented ); if( hasSpecialFlags ) { IList<PropertyInfo> properties = new List<PropertyInfo> { result }; properties = properties.Filter( bindingFlags ); return properties.Count > 0 ? properties[ 0 ] : null; } return result; }
/// <summary> /// Method to determine resources required for this activity in the current month /// </summary> /// <returns>List of required resource requests</returns> public override List <ResourceRequest> GetResourcesNeededForActivity() { List <Ruminant> herd = CurrentHerd(false); feedEstimated = 0; feedToSatisfy = 0; feedToOverSatisfy = 0; // get list from filters foreach (Model child in this.Children.Where(a => a.GetType().ToString().Contains("RuminantFeedGroup"))) { var selectedIndividuals = herd.Filter(child); switch (FeedStyle) { case RuminantFeedActivityTypes.SpecifiedDailyAmountPerIndividual: case RuminantFeedActivityTypes.ProportionOfWeight: case RuminantFeedActivityTypes.ProportionOfFeedAvailable: case RuminantFeedActivityTypes.SpecifiedDailyAmount: usingPotentialintakeMultiplier = true; break; } // get the amount that can be eaten. Does not account for individuals in multiple filters // accounts for some feeding style allowing overeating to the user declared value in ruminant feedToSatisfy += selectedIndividuals.Sum(a => a.PotentialIntake - a.Intake); feedToOverSatisfy += selectedIndividuals.Sum(a => a.PotentialIntake * (usingPotentialintakeMultiplier ? a.BreedParams.OverfeedPotentialIntakeModifier : 1) - a.Intake); double value = 0; if (child is RuminantFeedGroup) { value = (child as RuminantFeedGroup).Value; } else { value = (child as RuminantFeedGroupMonthly).MonthlyValues[Clock.Today.Month - 1]; } if (FeedStyle == RuminantFeedActivityTypes.SpecifiedDailyAmount) { feedEstimated += value * 30.4; } else if (FeedStyle == RuminantFeedActivityTypes.ProportionOfFeedAvailable) { feedEstimated += value * FeedType.Amount; } else { foreach (Ruminant ind in selectedIndividuals) { switch (FeedStyle) { case RuminantFeedActivityTypes.SpecifiedDailyAmountPerIndividual: feedEstimated += value * 30.4; break; case RuminantFeedActivityTypes.ProportionOfWeight: feedEstimated += value * ind.Weight * 30.4; break; case RuminantFeedActivityTypes.ProportionOfPotentialIntake: feedEstimated += value * ind.PotentialIntake; break; case RuminantFeedActivityTypes.ProportionOfRemainingIntakeRequired: feedEstimated += value * (ind.PotentialIntake - ind.Intake); break; default: throw new Exception(String.Format("FeedStyle {0} is not supported in {1}", FeedStyle, this.Name)); } } } } if (StopFeedingWhenSatisfied) { // restrict to max intake permitted by individuals and avoid overfeed wastage feedEstimated = Math.Min(feedEstimated, Math.Max(feedToOverSatisfy, feedToSatisfy)); } if (feedEstimated > 0) { // FeedTypeName includes the ResourceGroup name eg. AnimalFoodStore.FeedItemName string feedItemName = FeedTypeName.Split('.').Last(); return(new List <ResourceRequest>() { new ResourceRequest() { AllowTransmutation = true, Required = feedEstimated, ResourceType = typeof(AnimalFoodStore), ResourceTypeName = feedItemName, ActivityModel = this, Category = "Feed", RelatesToResource = this.PredictedHerdName } }); } else { return(null); } }
public void FilterWithListFilterCallbackWorks() { var list = new List<int> { -1, 1, 4, 3 }; Assert.AreEqual(list.Filter((x, i, a) => a == list && (int)x == i), new[] { 1, 3 }); }
public override Tuple <PlayoutBuilderState, List <PlayoutItem> > Schedule( PlayoutBuilderState playoutBuilderState, Dictionary <CollectionKey, IMediaCollectionEnumerator> collectionEnumerators, ProgramScheduleItemDuration scheduleItem, ProgramScheduleItem nextScheduleItem, DateTimeOffset hardStop) { var playoutItems = new List <PlayoutItem>(); PlayoutBuilderState nextState = playoutBuilderState; var willFinishInTime = true; Option <DateTimeOffset> durationUntil = None; IMediaCollectionEnumerator contentEnumerator = collectionEnumerators[CollectionKey.ForScheduleItem(scheduleItem)]; while (contentEnumerator.Current.IsSome && nextState.CurrentTime < hardStop && willFinishInTime) { MediaItem mediaItem = contentEnumerator.Current.ValueUnsafe(); // find when we should start this item, based on the current time DateTimeOffset itemStartTime = GetStartTimeAfter(nextState, scheduleItem); // remember when we need to finish this duration item if (nextState.DurationFinish.IsNone) { nextState = nextState with { DurationFinish = itemStartTime + scheduleItem.PlayoutDuration }; durationUntil = nextState.DurationFinish; } TimeSpan itemDuration = DurationForMediaItem(mediaItem); List <MediaChapter> itemChapters = ChaptersForMediaItem(mediaItem); if (itemDuration > scheduleItem.PlayoutDuration) { _logger.LogWarning( "Skipping playout item {Title} with duration {Duration} that is longer than schedule item duration {PlayoutDuration}", PlayoutBuilder.DisplayTitle(mediaItem), itemDuration, scheduleItem.PlayoutDuration); contentEnumerator.MoveNext(); continue; } var playoutItem = new PlayoutItem { MediaItemId = mediaItem.Id, Start = itemStartTime.UtcDateTime, Finish = itemStartTime.UtcDateTime + itemDuration, InPoint = TimeSpan.Zero, OutPoint = itemDuration, GuideGroup = nextState.NextGuideGroup, FillerKind = scheduleItem.GuideMode == GuideMode.Filler ? FillerKind.Tail : FillerKind.None, CustomTitle = scheduleItem.CustomTitle, WatermarkId = scheduleItem.WatermarkId, PreferredAudioLanguageCode = scheduleItem.PreferredAudioLanguageCode, PreferredSubtitleLanguageCode = scheduleItem.PreferredSubtitleLanguageCode, SubtitleMode = scheduleItem.SubtitleMode }; durationUntil.Do(du => playoutItem.GuideFinish = du.UtcDateTime); DateTimeOffset durationFinish = nextState.DurationFinish.IfNone(SystemTime.MaxValueUtc); DateTimeOffset itemEndTimeWithFiller = CalculateEndTimeWithFiller( collectionEnumerators, scheduleItem, itemStartTime, itemDuration, itemChapters); willFinishInTime = itemStartTime > durationFinish || itemEndTimeWithFiller <= durationFinish; if (willFinishInTime) { // LogScheduledItem(scheduleItem, mediaItem, itemStartTime); playoutItems.AddRange( AddFiller(nextState, collectionEnumerators, scheduleItem, playoutItem, itemChapters)); nextState = nextState with { CurrentTime = itemEndTimeWithFiller, // only bump guide group if we don't have a custom title NextGuideGroup = string.IsNullOrWhiteSpace(scheduleItem.CustomTitle) ? nextState.IncrementGuideGroup : nextState.NextGuideGroup }; contentEnumerator.MoveNext(); } else { TimeSpan durationBlock = itemEndTimeWithFiller - itemStartTime; if (itemEndTimeWithFiller - itemStartTime > scheduleItem.PlayoutDuration) { _logger.LogWarning( "Unable to schedule duration block of {DurationBlock} which is longer than the configured playout duration {PlayoutDuration}", durationBlock, scheduleItem.PlayoutDuration); } nextState = nextState with { DurationFinish = None }; nextState.ScheduleItemsEnumerator.MoveNext(); } } // this is needed when the duration finish exactly matches the hard stop if (nextState.DurationFinish.IsSome && nextState.CurrentTime == nextState.DurationFinish) { nextState = nextState with { DurationFinish = None }; nextState.ScheduleItemsEnumerator.MoveNext(); } if (playoutItems.Select(pi => pi.GuideGroup).Distinct().Count() != 1) { nextState = nextState with { NextGuideGroup = nextState.DecrementGuideGroup }; } foreach (DateTimeOffset nextItemStart in durationUntil) { switch (scheduleItem.TailMode) { case TailMode.Filler: if (scheduleItem.TailFiller != null) { (nextState, playoutItems) = AddTailFiller( nextState, collectionEnumerators, scheduleItem, playoutItems, nextItemStart); } if (scheduleItem.FallbackFiller != null) { (nextState, playoutItems) = AddFallbackFiller( nextState, collectionEnumerators, scheduleItem, playoutItems, nextItemStart); } nextState = nextState with { CurrentTime = nextItemStart }; break; case TailMode.Offline: if (scheduleItem.FallbackFiller != null) { (nextState, playoutItems) = AddFallbackFiller( nextState, collectionEnumerators, scheduleItem, playoutItems, nextItemStart); } nextState = nextState with { CurrentTime = nextItemStart }; break; } } // clear guide finish on all but the last item var all = playoutItems.Filter(pi => pi.FillerKind == FillerKind.None).ToList(); PlayoutItem last = all.OrderBy(pi => pi.FinishOffset).LastOrDefault(); foreach (PlayoutItem item in all.Filter(pi => pi != last)) { item.GuideFinish = null; } nextState = nextState with { NextGuideGroup = nextState.IncrementGuideGroup }; return(Tuple(nextState, playoutItems)); } }
internal static List<Edge> SelectEdgesForSitePointF(PointF coord, List<Edge> edgesToTest) { _coord = coord; return edgesToTest.Filter(MyTest); }
/// <summary> /// Retrieve a ResourceType from a ResourceGroup based on a request item including filter and sort options /// </summary> /// <param name="request">A resource request item</param> /// <param name="missingResourceAction">Action to take if requested resource group not found</param> /// <param name="missingResourceTypeAction">Action to take if requested resource type not found</param> /// <returns>A reference to the item of type Model</returns> public IModel GetResourceItem(ResourceRequest request, OnMissingResourceActionTypes missingResourceAction, OnMissingResourceActionTypes missingResourceTypeAction) { if (request.FilterDetails != null) { if (request.ResourceType == null) { string errorMsg = String.Format("Resource type must be supplied in resource request from [a={0}]", request.ActivityModel.Name); throw new Exception(errorMsg); } IModel resourceGroup = this.GetGroupByType(request.ResourceType); if (resourceGroup == null) { string errorMsg = String.Format("@error:Unable to locate resources of type [r{0}] for [a={1}]", request.ResourceType, request.ActivityModel.Name); switch (missingResourceAction) { case OnMissingResourceActionTypes.ReportErrorAndStop: throw new Exception(errorMsg); case OnMissingResourceActionTypes.ReportWarning: errorMsg = errorMsg.Replace("@error:", ""); Summary.WriteWarning(request.ActivityModel, errorMsg); break; default: break; } return(null); } // get list of children matching the conditions in filter // and return the lowest item that has enough time available object resourceGroupObject = resourceGroup as object; switch (resourceGroupObject.GetType().ToString()) { case "Models.CLEM.Resources.Labour": // get matching labour types // use activity uid to ensure unique for this request List <LabourType> items = (resourceGroup as Labour).Items; items = items.Filter(request.FilterDetails.FirstOrDefault() as Model); items = items.Where(a => a.LastActivityRequestID != request.ActivityID).ToList(); if (items.Where(a => a.Amount >= request.Required).Count() > 0) { // get labour least available but with the amount needed return(items.Where(a => a.Amount >= request.Required).OrderByDescending(a => a.Amount).FirstOrDefault()); } else { // get labour with most available but with less than the amount needed return(items.OrderByDescending(a => a.Amount).FirstOrDefault()); } default: string errorMsg = "Resource cannot be filtered. Filtering not implemented for [r=" + resourceGroupObject.GetType().ToString() + "] from activity [a=" + request.ActivityModel.Name + "]"; Summary.WriteWarning(request.ActivityModel, errorMsg); throw new Exception(errorMsg); } } else { // check style of ResourceTypeName used // this is either "Group.Type" from dropdown menus or "Type" only. if (request.ResourceTypeName.Contains(".")) { return(GetResourceItem(request.ActivityModel, request.ResourceTypeName, missingResourceAction, missingResourceTypeAction)); } else { return(GetResourceItem(request.ActivityModel, request.ResourceType, request.ResourceTypeName, missingResourceAction, missingResourceTypeAction)); } } }
/// <summary> /// Get value of a specific individual with special requirements check (e.g. breeding sire or draught purchase) /// </summary> /// <returns>value</returns> public double PayRate(LabourType ind, LabourFilterParameters property, string value) { double price = 0; if (PricingAvailable) { string criteria = property.ToString().ToUpper() + ":" + value.ToUpper(); List <LabourType> labourList = new List <LabourType>() { ind }; //find first pricing entry matching specific criteria LabourPriceGroup matchIndividual = null; LabourPriceGroup matchCriteria = null; foreach (LabourPriceGroup item in PayList.FindAllChildren <LabourPriceGroup>().Cast <LabourPriceGroup>()) { if (labourList.Filter(item).Count() == 1 && matchIndividual == null) { matchIndividual = item; } // check that pricing item meets the specified criteria. if (item.FindAllChildren <LabourFilter>().Cast <LabourFilter>().Where(a => (a.Parameter.ToString().ToUpper() == property.ToString().ToUpper() && a.Value.ToUpper() == value.ToUpper())).Count() > 0) { if (matchCriteria == null) { matchCriteria = item; } else { // multiple price entries were found. using first. value = xxx. if (!WarningsMultipleEntry.Contains(criteria)) { WarningsMultipleEntry.Add(criteria); Summary.WriteWarning(this, "Multiple specific pay rate entries were found where [" + property + "]" + (value.ToUpper() != "TRUE" ? " = [" + value + "]." : ".") + "\r\nOnly the first entry will be used. Pay [" + matchCriteria.Value.ToString("#,##0.##") + "]."); } } } } if (matchCriteria == null) { // report specific criteria not found in price list string warningString = "No [Pay] rate entry was found meeting the required criteria [" + property + "]" + (value.ToUpper() != "TRUE" ? " = [" + value + "]." : "."); if (matchIndividual != null) { // add using the best pricing available for [][] purchases of xx per head warningString += "\r\nThe best available pay rate [" + matchIndividual.Value.ToString("#,##0.##") + "] will be used."; price = matchIndividual.Value; } else { Summary.WriteWarning(this, "\r\nNo alternate pay rate for individuals could be found for the individuals. Add a new [r=LabourPriceGroup] entry in the [r=LabourPricing]"); } if (!WarningsNotFound.Contains(criteria)) { WarningsNotFound.Add(criteria); Summary.WriteWarning(this, warningString); } } else { price = matchCriteria.Value; } } return(price); }
/// <summary> /// Method to determine available labour based on filters and take it if requested. /// </summary> /// <param name="request">Resource request details</param> /// <param name="removeFromResource">Determines if only calculating available labour or labour removed</param> /// <param name="callingModel">Model calling this method</param> /// <param name="resourceHolder">Location of resource holder</param> /// <param name="partialAction">Action on partial resources available</param> /// <returns></returns> public static double TakeLabour(ResourceRequest request, bool removeFromResource, IModel callingModel, ResourcesHolder resourceHolder, OnPartialResourcesAvailableActionTypes partialAction) { double amountProvided = 0; double amountNeeded = request.Required; LabourFilterGroup current = request.FilterDetails.OfType <LabourFilterGroup>().FirstOrDefault() as LabourFilterGroup; LabourRequirement lr; if (current != null) { if (current.Parent is LabourRequirement) { lr = current.Parent as LabourRequirement; } else { // coming from Transmutation request lr = new LabourRequirement() { ApplyToAll = false, MaximumPerPerson = 1000, MinimumPerPerson = 0 }; } } else { lr = callingModel.FindAllChildren <LabourRequirement>().FirstOrDefault() as LabourRequirement; } int currentIndex = 0; if (current == null) { // no filtergroup provided so assume any labour current = new LabourFilterGroup(); } request.ResourceTypeName = "Labour"; ResourceRequest removeRequest = new ResourceRequest() { ActivityID = request.ActivityID, ActivityModel = request.ActivityModel, AdditionalDetails = request.AdditionalDetails, AllowTransmutation = request.AllowTransmutation, Available = request.Available, FilterDetails = request.FilterDetails, Provided = request.Provided, Category = request.Category, RelatesToResource = request.RelatesToResource, Required = request.Required, Resource = request.Resource, ResourceType = request.ResourceType, ResourceTypeName = (request.Resource is null? "":(request.Resource as CLEMModel).NameWithParent) }; // start with top most LabourFilterGroup while (current != null && amountProvided < amountNeeded) { List <LabourType> items = (resourceHolder.GetResourceGroupByType(request.ResourceType) as Labour).Items; items = items.Where(a => (a.LastActivityRequestID != request.ActivityID) || (a.LastActivityRequestID == request.ActivityID && a.LastActivityRequestAmount < lr.MaximumPerPerson)).ToList(); items = items.Filter(current as Model); // search for people who can do whole task first while (amountProvided < amountNeeded && items.Where(a => a.LabourCurrentlyAvailableForActivity(request.ActivityID, lr.MaximumPerPerson) >= request.Required).Count() > 0) { // get labour least available but with the amount needed LabourType lt = items.Where(a => a.LabourCurrentlyAvailableForActivity(request.ActivityID, lr.MaximumPerPerson) >= request.Required).OrderBy(a => a.LabourCurrentlyAvailableForActivity(request.ActivityID, lr.MaximumPerPerson)).FirstOrDefault(); double amount = Math.Min(amountNeeded - amountProvided, lt.LabourCurrentlyAvailableForActivity(request.ActivityID, lr.MaximumPerPerson)); // limit to max allowed per person amount = Math.Min(amount, lr.MaximumPerPerson); // limit to min per person to do activity if (amount < lr.MinimumPerPerson) { request.Category = "Min labour limit"; return(amountProvided); } amountProvided += amount; removeRequest.Required = amount; if (removeFromResource) { lt.LastActivityRequestID = request.ActivityID; lt.LastActivityRequestAmount = amount; lt.Remove(removeRequest); request.Provided += removeRequest.Provided; request.Value += request.Provided * lt.PayRate(); } } // if still needed and allow partial resource use. if (partialAction == OnPartialResourcesAvailableActionTypes.UseResourcesAvailable) { if (amountProvided < amountNeeded) { // then search for those that meet criteria and can do part of task foreach (LabourType item in items.Where(a => a.LabourCurrentlyAvailableForActivity(request.ActivityID, lr.MaximumPerPerson) >= 0).OrderByDescending(a => a.LabourCurrentlyAvailableForActivity(request.ActivityID, lr.MaximumPerPerson))) { if (amountProvided >= amountNeeded) { break; } double amount = Math.Min(amountNeeded - amountProvided, item.LabourCurrentlyAvailableForActivity(request.ActivityID, lr.MaximumPerPerson)); // limit to max allowed per person amount = Math.Min(amount, lr.MaximumPerPerson); // limit to min per person to do activity if (amount >= lr.MinimumPerPerson) { amountProvided += amount; removeRequest.Required = amount; if (removeFromResource) { if (item.LastActivityRequestID != request.ActivityID) { item.LastActivityRequestAmount = 0; } item.LastActivityRequestID = request.ActivityID; item.LastActivityRequestAmount += amount; item.Remove(removeRequest); request.Provided += removeRequest.Provided; request.Value += request.Provided * item.PayRate(); } } else { currentIndex = request.FilterDetails.Count; } } } } currentIndex++; if (current.Children.OfType <LabourFilterGroup>().Count() > 0) { current = current.Children.OfType <LabourFilterGroup>().FirstOrDefault(); } else { current = null; } } // report amount gained. return(amountProvided); }
/// <summary> /// Determines how much labour is required from this activity based on the requirement provided /// </summary> /// <param name="requirement">The details of how labour are to be provided</param> /// <returns></returns> public override double GetDaysLabourRequired(LabourRequirement requirement) { List <LabourType> group = Resources.Labour().Items.Where(a => a.Hired != true).ToList(); int head = 0; double adultEquivalents = 0; foreach (Model child in Apsim.Children(this, typeof(LabourFeedGroup))) { var subgroup = group.Filter(child).ToList(); head += subgroup.Count(); adultEquivalents += subgroup.Sum(a => a.AdultEquivalent); } double daysNeeded = 0; double numberUnits = 0; switch (requirement.UnitType) { case LabourUnitType.Fixed: daysNeeded = requirement.LabourPerUnit; break; case LabourUnitType.perHead: numberUnits = head / requirement.UnitSize; if (requirement.WholeUnitBlocks) { numberUnits = Math.Ceiling(numberUnits); } daysNeeded = numberUnits * requirement.LabourPerUnit; break; case LabourUnitType.perAE: numberUnits = adultEquivalents / requirement.UnitSize; if (requirement.WholeUnitBlocks) { numberUnits = Math.Ceiling(numberUnits); } daysNeeded = numberUnits * requirement.LabourPerUnit; break; case LabourUnitType.perKg: daysNeeded = feedRequired * requirement.LabourPerUnit; break; case LabourUnitType.perUnit: numberUnits = feedRequired / requirement.UnitSize; if (requirement.WholeUnitBlocks) { numberUnits = Math.Ceiling(numberUnits); } daysNeeded = numberUnits * requirement.LabourPerUnit; break; default: throw new Exception(String.Format("LabourUnitType {0} is not supported for {1} in {2}", requirement.UnitType, requirement.Name, this.Name)); } return(daysNeeded); }
public IEnumerable <EnumMemberPair> GetEnumPairingsFor(Type sourceEnumType, Type targetEnumType) => _enumPairings?.Filter(ep => ep.IsFor(sourceEnumType, targetEnumType)) ?? Enumerable <EnumMemberPair> .Empty;
private void UpdateFilter(Func <LogEntry, bool> newFilter) { filter = newFilter; CellData = allData.Filter(filter).ToList(); ReloadData(); }
public IList<WebChannelState> GetAllChannelStatesForGroup(int groupId, string userName, string filter = null) { IList<WebChannelBasic> list = GetChannelsBasic(groupId); IList<WebChannelState> webChannelStates = new List<WebChannelState>(); foreach (WebChannelBasic entry in list) { webChannelStates.Add(GetChannelState(entry.Id, userName)); } return webChannelStates.Filter(filter).ToList(); /* This is the old implementation which doesn't work due to a NullReferenceException in TvService Dictionary<int, ChannelState> channelStates = _tvControl.GetAllChannelStatesForGroup(groupId, GetUserByUserName(userName, true)); Dictionary<int, WebChannelState> webChannelStates = new Dictionary<int, WebChannelState>(); if (channelStates != null && channelStates.Count > 0) { foreach (var entry in channelStates) { webChannelStates.Add(entry.Key, entry.Value.ToWebChannelState(entry.Key)); } } return webChannelStates; */ }
/// <summary> /// Method to determine resources required for this activity in the current month /// </summary> /// <returns>List of required resource requests</returns> public override List <ResourceRequest> GetResourcesNeededForActivity() { ResourceRequestList = null; List <Ruminant> herd = CurrentHerd(false); int head = 0; double AE = 0; foreach (RuminantFeedGroup child in Apsim.Children(this, typeof(RuminantFeedGroup))) { var subherd = herd.Filter(child).ToList(); head += subherd.Count(); AE += subherd.Sum(a => a.AdultEquivalent); } // for each labour item specified foreach (var item in labour) { double daysNeeded = 0; switch (item.UnitType) { case LabourUnitType.Fixed: daysNeeded = item.LabourPerUnit; break; case LabourUnitType.perHead: daysNeeded = Math.Ceiling(head / item.UnitSize) * item.LabourPerUnit; break; case LabourUnitType.perAE: daysNeeded = Math.Ceiling(AE / item.UnitSize) * item.LabourPerUnit; break; default: throw new Exception(String.Format("LabourUnitType {0} is not supported for {1} in {2}", item.UnitType, item.Name, this.Name)); } if (daysNeeded > 0) { if (ResourceRequestList == null) { ResourceRequestList = new List <ResourceRequest>(); } ResourceRequestList.Add(new ResourceRequest() { AllowTransmutation = false, Required = daysNeeded, ResourceType = typeof(Labour), ResourceTypeName = "", ActivityModel = this, FilterDetails = new List <object>() { item } } ); } } herd = CurrentHerd(false); // feed double feedRequired = 0; // get zero limited month from clock int month = Clock.Today.Month - 1; // get list from filters foreach (RuminantFeedGroup child in Apsim.Children(this, typeof(RuminantFeedGroup))) { foreach (Ruminant ind in herd.Filter(child as RuminantFeedGroup)) { switch (FeedStyle) { case RuminantFeedActivityTypes.SpecifiedDailyAmount: feedRequired += (child as RuminantFeedGroup).MonthlyValues[month] * 30.4; break; case RuminantFeedActivityTypes.ProportionOfWeight: feedRequired += (child as RuminantFeedGroup).MonthlyValues[month] * ind.Weight * 30.4; break; case RuminantFeedActivityTypes.ProportionOfPotentialIntake: feedRequired += (child as RuminantFeedGroup).MonthlyValues[month] * ind.PotentialIntake; break; case RuminantFeedActivityTypes.ProportionOfRemainingIntakeRequired: feedRequired += (child as RuminantFeedGroup).MonthlyValues[month] * (ind.PotentialIntake - ind.Intake); break; default: break; } } } if (ResourceRequestList == null) { ResourceRequestList = new List <ResourceRequest>(); } ResourceRequestList.Add(new ResourceRequest() { AllowTransmutation = true, Required = feedRequired, ResourceType = typeof(AnimalFoodStore), ResourceTypeName = this.FeedTypeName, ActivityModel = this } ); return(ResourceRequestList); }
/// <summary> /// Gets the field identified by <paramref name="name"/> on the given <paramref name="type"/>. /// Use the <paramref name="bindingFlags"/> parameter to define the scope of the search. /// </summary> /// <returns>A single FieldInfo instance of the first found match or null if no match was found.</returns> public static FieldInfo Field( this Type type, string name, Flags bindingFlags ) { // we need to check all fields to do partial name matches if( bindingFlags.IsAnySet( Flags.PartialNameMatch | Flags.TrimExplicitlyImplemented ) ) { return type.Fields( bindingFlags, name ).FirstOrDefault(); } var result = type.GetField( name, bindingFlags ); if( result == null && bindingFlags.IsNotSet( Flags.DeclaredOnly ) ) { if( type.BaseType != typeof(object) && type.BaseType != null ) { return type.BaseType.Field( name, bindingFlags ); } } bool hasSpecialFlags = bindingFlags.IsAnySet( Flags.ExcludeBackingMembers | Flags.ExcludeExplicitlyImplemented | Flags.ExcludeHiddenMembers ); if( hasSpecialFlags ) { IList<FieldInfo> fields = new List<FieldInfo> { result }; fields = fields.Filter( bindingFlags ); return fields.Count > 0 ? fields[ 0 ] : null; } return result; }
internal static List<Edge> SelectEdgesForSiteVector2(Vector2 coord, List<Edge> edgesToTest) { _coord = coord; return edgesToTest.Filter(MyTest); }