public NutrientTracker(int minimum, int maximum, int current, Nutrient nutrient) { this.minimum = minimum; this.maximum = maximum; this.current = current; this.nutrient = nutrient; }
public void InsertTest() { Nutrient n = new Nutrient { Name = "Omega-3", Amount = 9000, Number = 1234, UnitName = "ug" }; List <Nutrient> nutrients = new List <Nutrient>(); nutrients.Add(n); // Arrange MealController controllerm = new MealController(); // Act List <Meal> loadAllM = controllerm.Get() as List <Meal>; //grab first result Meal meal = loadAllM[0]; Food f = new Food { FDCId = 999999, dataType = "test", description = "test", publicationDate = System.DateTime.Now, foodCode = "test", foodNutrients = nutrients, Quantity = 2, MealId = meal.Id }; // Arrange FoodController controller = new FoodController(); // Act int result = controller.Post(f); // Assert Assert.IsTrue(result > 0); }
public NutrientTracker(Nutrient nutrient) { minimum = 0; maximum = 100; current = 5; this.nutrient = nutrient; }
internal AdministeredNutrient(Plant plant, Nutrient nutrient, double amount, DateTime date) { Plant = plant; Nutrient = nutrient; Amount = amount; Date = date; }
public async Task <Nutrient> Update(UpdateNutrientModel model) { Nutrient nutrient = await _database.Nutrients .Include(x => x.AdministeredToPlants) .FirstOrDefaultAsync(x => x.Id == model.Id); if (nutrient is null) { return(null); } if (nutrient.AdministeredToPlants.Any()) { throw new NutrientAdministeredToAPlantException(); } IQueryable <Nutrient> existingNutrientsWithName = from existingNutrient in _database.Nutrients where (existingNutrient.Name == model.Name) && (existingNutrient.Id != model.Id) select existingNutrient; if (await existingNutrientsWithName.AnyAsync()) { throw new NutrientWithNameAlreadyExistsException(model.Name); } _mapper.Map(model, nutrient); _database.Nutrients.Update(nutrient); await _database.SaveAsync(); return(nutrient); }
public bool DecreaseNutrient(string name, float amount) { int index = -1; for (int i = 0; i < nutrients.Count; i++) { if (nutrients[i].name == name) { index = i; break; } } if (index == -1) { Debug.LogError("Error nutrient not existant"); return(false); } if (nutrients[index].amount >= amount) { Nutrient n = nutrients[index]; n.amount -= amount; nutrients[index] = n; return(true); } else { return(false); } }
private void Outputted(Nutrient nutrient) { if (_single) { if (_stopwatch.IsRunning) { var elapsed = _stopwatch.ElapsedMilliseconds; _elapseds.Add(elapsed); } _stopwatch.Restart(); } else { //在1个食物输出多个养分的情况下,第一组养分的输入不算入_elapseds //这是因为Satiety模式下,第一次分解食物是没有统计时间的,只有第二次分解食物才能统计出第一次到第二次之间的时间 if (_times >= _nutrientsGroupCount) { if (_stopwatch.IsRunning) { var elapsed = _stopwatch.ElapsedMilliseconds; _elapseds.Add(elapsed); } _stopwatch.Restart(); } } _times++; var sleep = new Random().Next(_nutrientOutputRunTime.Min, _nutrientOutputRunTime.Max); Thread.Sleep(sleep); }
public IActionResult Edit(int id, NutrientEditViewModel data) { var userId = int.Parse(User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Sid)?.Value); if (!decimal.TryParse(data.MaxIntake, out var amount)) { return(View(data)); } var nutrient = new Nutrient { Id = id, Name = data.Name, MaxIntake = amount }; if (_nutrientLogic.Edit(userId, nutrient)) { return(RedirectToAction("List", "Nutrient")); } ViewData["message"] = "Er ging iets fout"; return(View(data)); }
public Task <bool> UpdateNutrientAsync(Nutrient updatedNutrient) { try { // Get the existing record. var ExistingNutrient = _context.Nutrient .FirstOrDefault(nutrient => nutrient.NutrientId == updatedNutrient.NutrientId); if (ExistingNutrient != null) { ExistingNutrient.NutrientName = updatedNutrient.NutrientName; ExistingNutrient.NutrientDescription = updatedNutrient.NutrientDescription; _context.SaveChanges(); } else { return(Task.FromResult(false)); } return(Task.FromResult(true)); } catch (Exception ex) { DetachAllEntities(); throw ex; } }
protected Guid SeedDatabase(Nutrient nutrient) { DatabaseContext.Nutrients.Add(nutrient); DatabaseContext.Save(); return(nutrient.Id); }
/** * Returns closest nutrient within range of TargetColor's type * that isn't already targeted and is in direct line of sight * or null if there are no valid targets */ private Nutrient AcquireTarget() { // get all the nutrients of the target color from the nutrient manager IList <Nutrient> nutrients = m_NutrientManager.GetNutrients(m_TargetColor); if (nutrients == null) // if there are no nutrients of that color then there are no targets { return(null); // return null to indicate there are no targets } // now we need to find the closest, untargeted nutrient as that is what we will shoot at Nutrient closestNutrient = null; // initially set the closest nutrient to null float closestDistance = float.MaxValue; // set the closest distance to infinity // now iterate through the nutrients to find the closest one foreach (Nutrient e in nutrients) { if (!e.IsTargetted) // first check that the nutrient being examined is not already targetted { // now find the distance to that target float distance = MDPUtility.DistanceSquared(gameObject, e.gameObject); // check if this distance is less than the next known closest distance, and that the target is in LOS if (distance < closestDistance && distance < FiringRange * FiringRange && IsInLineOfSight(e.transform)) { // if it passed the check closestNutrient = e; // assign this nutrient to be the closest one closestDistance = distance; // assign this nutrient's distance to be the closest distance } } } // after we are done iterating through the nutrients then return what we found was the closest one as the target return(closestNutrient); }
//Pass in the food id from display food and make logic to get details on the nutrients public async Task <List <Nutrient> > GetNutrientsInfo(int id) { string API = "htn2jn3wOXV60cFNLXNgrsfzlC0yhLVUT2HGLFCm"; List <Nutrient> nutrientInfo = new List <Nutrient>(); var food = db.Foods.SingleOrDefault(c => c.Id == id); var input = food.Name; var ndbno = food.USDANo; using (var client = new HttpClient()) { client.BaseAddress = new Uri("https://api.nal.usda.gov/"); var response = await client.GetAsync($"ndb/V2/reports?ndbno={ndbno}&type=b&format=json&api_key={API}"); response.EnsureSuccessStatusCode(); var stringResult = await response.Content.ReadAsStringAsync(); var json = JObject.Parse(stringResult); var nutrientCount = json["foods"][0]["food"]["nutrients"].Count(); var nutrientList = json["foods"][0]["food"]["nutrients"].ToList(); for (int i = 0; i < nutrientCount; i++) { Nutrient nutrient = new Nutrient(); nutrient.Name = json["foods"][0]["food"]["nutrients"][i]["name"].ToString(); nutrient.Value = nutrientList[i]["value"].ToObject <double>(); nutrient.Unit = nutrientList[i]["unit"].ToObject <string>(); nutrient.Symbol = TrimSymbol(nutrient.Name); nutrientInfo.Add(nutrient); } } return(nutrientInfo); }
public async Task <Guid> Create(Guid plantId, CreateAdministeredNutrientModel model) { Plant plant = await _database.Plants.FindAsync(plantId); if (plant is null) { throw new PlantNotFoundException(plantId); } Nutrient nutrient = await _database.Nutrients.FindAsync(model.NutrientId); if (nutrient is null) { throw new NutrientNotFoundException(model.NutrientId); } if (model.Date < plant.Planted) { throw new NutrientAdministrationDateBeforePlantDateException(); } AdministeredNutrient administeredNutrient = plant.AdministerNutrient(nutrient, model.Amount, model.Date, model.CreateEvent); _database.Plants.Update(plant); await _database.SaveAsync(); return(administeredNutrient.Id); }
/** * controls firing * this is called for a tower whenever the cooldown is up */ private void Fire() { target = AcquireTarget(); // first check if there are any valid targets for this tower if (target) // if a valid target was found { // set the audio clip to the shooting sound which will be played after the bullet is shot GetComponent <AudioSource>().clip = towerShootSound; // track stats PlayerPrefs.SetInt("SIStats_enzymesFired", PlayerPrefs.GetInt("SIStats_enzymesFired") + 1); PlayerPrefs.Save(); transform.Rotate(new Vector3(90, 0, 0), -40, Space.World); // Look at target but lock rotation on x axis transform.LookAt(target.transform); transform.Rotate(new Vector3(90, 0, 0), 40, Space.World); // play the shooting animation transform.Find(m_ActiveModelName).GetComponent <Animation>().Play("Default Take", PlayMode.StopAll); // create the bullet that will seek out the target GameObject bulletObject = Instantiate(Projectile, transform.position, transform.rotation) as GameObject; bulletObject.GetComponent <Renderer>().material.color = m_TargetColor; // set the bullet color to the correct one Bullet bullet = bulletObject.GetComponent <Bullet>(); // get the script on the bullet bullet.Target = target.gameObject; // set the target reference in the bullet script bullet.targets = targets; // set the number of targets one bullet can hit target.IsTargetted = true; // mark the current target as targetted so that it can't be shot more than once GetComponent <AudioSource>().Play(); // play the sound m_CanFire = false; // reset the canFire flag to false until the next cooldown is up } }
// var list = db.Nutrients.ToList(); //資料庫 // List<NutrientDTO> dtoList = new List<NutrientDTO>(); //MODEL清單 // foreach (var item in list) // { // NutrientDTO dto = new NutrientDTO(); // dto.ID = item.ID; //把資料庫資料匯入清單 // dto.Fat =(float) item.Fat; // dto.Protein = (float)item.Protein; // dto.Carbs = (float)item.Carbs; // dto.Sugar = (float)item.Sugar; // dto.VitA = (float)item.VitA; // dto.VitB = (float)item.VitB; // dto.VitC = (float)item.VitC; // dto.VitD = (float)item.VitD; // dto.VitE = (float)item.VitE; // dto.Na = (float)item.Na; // dto.K = (float)item.K; // dtoList.Add(dto); // } // return dtoList; //} public void Update(Nutrient entity) { Nutrient nutrient = db.Nutrients.First(x => x.ID == entity.ID); //NutrientDTO dto = new NutrientDTO(); //int nutrientID = (int)nutrient1.ID; nutrient.Fat = (float)entity.Fat; nutrient.Protein = (float)entity.Protein; nutrient.Carbs = (float)entity.Carbs; nutrient.Sugar = (float)entity.Sugar; nutrient.VitA = (float)entity.VitA; nutrient.VitB = (float)entity.VitB; nutrient.VitC = (float)entity.VitC; nutrient.VitD = (float)entity.VitD; nutrient.VitE = (float)entity.VitE; nutrient.Na = (float)entity.Na; nutrient.Potassium = (float)entity.Potassium; db.SaveChanges(); //Nutrient myNutrient = new Nutrient(); //myNutrient.Fat = nutrient.Fat; //myNutrient.Protein = nutrient.Protein; //myNutrient.Carbs = nutrient.Carbs; //myNutrient.Sugar = nutrient.Sugar; //myNutrient.VitA = nutrient.VitA; //myNutrient.VitB = nutrient.VitB; //myNutrient.VitC = nutrient.VitC; //myNutrient.VitD = nutrient.VitD; //myNutrient.VitE = nutrient.VitE; //myNutrient.Na = nutrient.Na; //myNutrient.K = nutrient.K; //db.Nutrients.Add(nutrient); }
public NutrientDTO GetNutrient(int ID) { MealOption meal = db.MealOptions.First(x => x.ID == ID); NutrientDTO dto = new NutrientDTO(); int nutrientID = (int)meal.NutrientID; Nutrient nutrient = db.Nutrients.First(x => x.ID == nutrientID); dto.ID = nutrient.ID; //把資料庫資料匯入清單 dto.Fat = (float)nutrient.Fat; dto.Protein = (float)nutrient.Protein; dto.Carbs = (float)nutrient.Carbs; dto.Sugar = (float)nutrient.Sugar; dto.VitA = (float)nutrient.VitA; dto.VitB = (float)nutrient.VitB; dto.VitC = (float)nutrient.VitC; dto.VitD = (float)nutrient.VitD; dto.VitE = (float)nutrient.VitE; dto.Na = (float)nutrient.Na; dto.K = (float)nutrient.Potassium; return(dto); }
/** * function to check for the collisions with the bullet */ protected override void CheckCollisions() { if (Collider.CollidesWith(Target)) // if the bullet collides with a target { Destroy(gameObject); // destroy the bullet // get the information on the nutrient target that was hit Nutrient target = Target.GetComponent <Nutrient>(); Color targetColor = target.BodyColor; GameObject parent = Target.transform.parent.gameObject; target.OnBulletCollision(); // call the function on the target to handle a collision targets--; // decrement the targets counter Nutrient[] nutrients = parent.GetComponentsInChildren <Nutrient>(); // get other nutrients with the same parent // as the original target // iterate over the nutrients to see if there are any other valid targets with the same color if the bullet // is able to destroy more targets foreach (Nutrient nutrient in nutrients) { if (nutrient.BodyColor == targetColor && targets > 0 && !nutrient.IsTargetted) { targets--; nutrient.OnBulletCollision(); } } } }
private Guid SeedDatabaseForGetByIdTesting() { using (SpiceContext ctx = SetupInMemoryDatabase()) { Field field = Fields.ModelFactory.DomainModel(); ctx.Fields.Add(field); Domain.Species species = Species.ModelFactory.DomainModel(); ctx.Species.Add(species); Plant plant = ModelFactory.DomainModel(field, species); Nutrient nutrient = Tests.Nutrients.ModelFactory.DomainModel(); ctx.Nutrients.Add(nutrient); AdministeredNutrient administeredNutrient = Nutrients.ModelFactory.DomainModel(nutrient, plant); plant.AdministeredNutrients.Add(administeredNutrient); ctx.AdministeredNutrients.Add(administeredNutrient); Event @event = Events.ModelFactory.DomainModel(plant); plant.Events.Add(@event); ctx.Events.Add(@event); ctx.Plants.Add(plant); ctx.Save(); return(plant.Id); } }
public GameObject nutrientLostSound; //!< for holding a reference to the nutrient lost sound /** * the function to generate what nutrients are on the food blob */ public void GenerateEnzymes(int minNutrients, int maxNutrients, Color[] availableColors) { NumNutrients = Random.Range(minNutrients, maxNutrients + 1); // randomly choose the number of nutrients on the blob // find a reference to the current nutrient manager and game manager m_NutrientManager = FindObjectOfType(typeof(NutrientManager)) as NutrientManager; m_GameManager = FindObjectOfType(typeof(IntestineGameManager)) as IntestineGameManager; // populate the number of nutrients decided earlier for (int i = 0; i < NumNutrients; i++) { float radius = .4f; // choose .4f as a radius to start with float angle = ((2 * Mathf.PI) / NumNutrients) * i; // divide the circle into the right number of angle chunks in rads float xPos = radius * Mathf.Cos(angle); // find the x position as radius*cos(theta) float zPos = radius * Mathf.Sin(angle); // find the y position as radius*sin(theta) Vector3 position = transform.position; // 3 dimensional vector for position position.x += xPos; // set the x position of the vector position.z += zPos; // set the z position of the vector position.y = .5f; // set the y position of the vector // randomly choose a color for the nutrient int randomIndex = MDPUtility.RandomInt(availableColors.Length); Nutrient nutrient = m_NutrientManager.InstantiateNutrient(availableColors[randomIndex], position); nutrient.intestineGameManager = m_GameManager; // assign the game manager reference on the nutrient to be // the same as the one referenced in this class // Attach new enzyme as a child object nutrient.transform.parent = gameObject.transform; ((Behaviour)nutrient.GetComponent("Halo")).enabled = false; // halo should be false unless explicitly enabled } }
/// <summary>Calculate actual decomposition</summary> public SurfaceOrganicMatterDecompType CalculateActualSOMDecomp() { var somDecomp = Nutrient.CalculateActualSOMDecomp(); somDecomp.Multiply(RelativeArea); return(somDecomp); }
/// <summary>Constructor.</summary> /// <param name="soilThicknesses">Soil thicknesses (mm).</param> /// <param name="nutrientPatchManager">The nutrient patch manager.</param> public NutrientPatch(double[] soilThicknesses, NutrientPatchManager nutrientPatchManager) { soilThickness = soilThicknesses; patchManager = nutrientPatchManager; var simulations = FileFormat.ReadFromString <Simulations>(ReflectionUtilities.GetResourceAsString("Models.Resources.Nutrient.json"), e => throw e, false); if (simulations.Children.Count != 1 || !(simulations.Children[0] is Nutrient)) { throw new Exception("Cannot create nutrient model in NutrientPatchManager"); } Nutrient = simulations.Children[0] as Nutrient; Nutrient.IsHidden = true; // Find all solutes. foreach (ISolute solute in Nutrient.FindAllChildren <ISolute>()) { solutes.Add(solute.Name, solute); } lignin = Nutrient.FindInScope <NutrientPool>("FOMLignin"); if (lignin == null) { throw new Exception("Cannot find lignin pool in the nutrient model."); } cellulose = Nutrient.FindInScope <NutrientPool>("FOMCellulose"); if (cellulose == null) { throw new Exception("Cannot find cellulose pool in the nutrient model."); } carbohydrate = Nutrient.FindInScope <NutrientPool>("FOMCarbohydrate"); if (carbohydrate == null) { throw new Exception("Cannot find carbohydrate pool in the nutrient model."); } }
public async Task <ActionResult> Put(Guid id, [FromBody] UpdateNutrientViewModel model) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } try { UpdateNutrientModel updateNutrientModel = _mapper.Map <UpdateNutrientModel>(model); updateNutrientModel.Id = id; Nutrient nutrient = await _commands.Update(updateNutrientModel); if (nutrient is null) { return(NotFound()); } return(Ok(_mapper.Map <NutrientDetailsViewModel>(nutrient))); } catch (Exception ex) when(ex is ResourceStateException) { return(Conflict(new ErrorViewModel(ex))); } }
public ActionResult DeleteConfirmed(int id) { Nutrient nutrient = db.Nutrients.Find(id); db.Nutrients.Remove(nutrient); db.SaveChanges(); return(RedirectToAction("Index")); }
public async Task <NutrientDetailsModel> Get(Guid id) { Nutrient nutrient = await _database.Nutrients .AsNoTracking() .FirstOrDefaultAsync(x => x.Id == id); return(_mapper.Map <NutrientDetailsModel>(nutrient)); }
public List <string> GetMicronutrientTitle(string name) { Nutrient nutrient = Micronutrients.Nutrient(name); return(new List <string> { nutrient.Name + " in " + nutrient.MeasurementUnit }); }
//chem reactions private void Fuse(Nutrient head, Nutrient tail) { head.Decrease(); tail.Decrease(); Nutrient newNutrient = new Nutrient(head.molecule + tail.molecule, 1); Add(newNutrient); }
private void cmbNutrients_SelectionChanged(object sender, SelectionChangedEventArgs e) { lblError.Content = ""; try { _nutrient = (Nutrient)cmbNutrients.SelectedItem; } catch (Exception) { } }
public FlorineSkiaNutrient(Nutrient n) { Name = n.Name; Class = n.Class; Units = n.Units; DailyTarget = n.DailyTarget; switch (Name) { case "Protein": RingColor = new SKColor(0xcc, 0, 0); break; case "Carbohydrates": //#e69138 RingColor = new SKColor(0xe6, 0x91, 0x38); break; case "Fat": RingColor = new SKColor(0xcc, 0xcc, 0xcc); break; case "Fiber": //93c47d RingColor = new SKColor(0x93, 0xc4, 0x7d); break; case "Folic Acid": RingColor = new SKColor(0x6a, 0xa8, 0x4f); break; case "Vitamin D": RingColor = new SKColor(0, 0xff, 0xff); break; case "Calcium": RingColor = new SKColor(0xff, 0xff, 0xff); break; case "Iron": RingColor = new SKColor(0xff, 0, 0); break; case "Potassium": RingColor = new SKColor(0x80, 0, 0x80); break; case "Vitamin B12": RingColor = SKColors.LightGoldenrodYellow; break; case "Vitamin A": RingColor = new SKColor(0xff, 0x99, 0); break; default: RingColor = new SKColor(255, 0, 255); break; } }
public ActionResult Edit([Bind(Include = "NutritientId,Description,Active,Created")] Nutrient nutrient) { if (ModelState.IsValid) { db.Entry(nutrient).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } return(View(nutrient)); }
private void CreateNutrient(Nutrient.NutrientType type) { var nutrient = new Nutrient(type, _startNutrientsAmount); _nutrients.Add(nutrient); var counter = Instantiate(_prefab, _counterRoot); nutrient.OnNutrientsChanged.AddListener(counter.OnNutrientsChanged); counter.OnNutrientsChanged((type, nutrient.GetAmount())); }