public static Demand GetFittedRecord(this IEnumerable<Demand> demands, Demand demand) { return demands.FirstOrDefault( x => x.City == demand.City && x.ProjectName.Trim() == demand.ProjectName.Trim() && x.ReceiveDate > demand.ReceiveDate.AddDays(-1) && x.ReceiveDate < demand.ReceiveDate.AddDays(1)); }
public void flow(Demand demand) { if (freeCapacity >= demand.Capacity) { freeCapacity -= demand.Capacity; } else { addModule(); flow(demand); } }
public void TestDemand_BasicParameters() { Demand demand = new Demand(); Assert.AreEqual(demand.ExpectedSubscriber, 0); Assert.AreEqual(demand.AcceptPath, AcceptPathDef.Direct); Assert.AreEqual(demand.CustomerLevel, CustomerLevelDef.Four); Assert.AreEqual(demand.DemandLevel, DemandLevelDef.C); Assert.AreEqual(demand.DemandSource, DemandSourceDef.Branch); Assert.AreEqual(demand.DemandType, DemandTypeDef.Intra); Assert.AreEqual(demand.MarketingTheme, MarketingThemeDef.Market); Assert.AreEqual(demand.Satisfactory, SatisfactoryDef.Unknown); Assert.AreEqual(demand.ProjectState, ProjectStateDef.InProgress); }
public void TestDemand_ParseDemandParameters() { Demand demand = new Demand() { DemandLevel = DemandLevelDef.B, DemandSource = DemandSourceDef.Government, DemandType = DemandTypeDef.Communication }; DemandView demandView = DemandView.Parse(demand); Assert.AreEqual(demandView.DemandLevel, "B级"); Assert.AreEqual(demandView.DemandSource, "政企客户"); Assert.AreEqual(demandView.DemandType, "通信保障"); }
public vDemand(Demand model) { Markdown mark = new Markdown(); this.Id = model.Id; this.Title = model.Title; this.Text = model.Text; this.DateTime = model.DateTime; this.Vote = model.Vote; this.Price = model.Price; this.UserId = model.UserId; this.Username = model.User.Username; this.State = model.State; this.CourseID = model.CourseID; }
public void TestDemand_ParseBasicParameters() { Demand demand = new Demand() { ExpectedCompleteDate = new DateTime(2014, 6, 22), ExpectedProfit = 20000, ActualCompleteDate = new DateTime(2014, 7, 31), Department = "MarketDepartment" }; DemandView demandView = DemandView.Parse(demand); Assert.AreEqual(demandView.ExpectedCompleteDate, new DateTime(2014, 6, 22)); Assert.AreEqual(demandView.ExpectedProfit, 20000); Assert.AreEqual(demandView.ActualCompleteDate, new DateTime(2014, 7, 31)); Assert.AreEqual(demandView.Department, "MarketDepartment"); }
public void TestDemand_ParseMarketInfos() { Demand demand = new Demand() { CustomerLevel = CustomerLevelDef.Two, MarketingTheme = MarketingThemeDef.Rural, Satisfactory = SatisfactoryDef.Perfect, ProjectState = ProjectStateDef.Complete }; DemandView demandView = DemandView.Parse(demand); Assert.AreEqual(demandView.CustomerLevel, "2"); Assert.AreEqual(demandView.MarketingTheme, "农村市场"); Assert.AreEqual(demandView.Satisfactory, "满意"); Assert.AreEqual(demandView.ProjectState, "完成"); }
internal Demand CreateDemand() { Customer cust = CreateCustomer(); Sku sku = CreateSku(); Demand dem = new Demand(); dem.Id = 1; dem.Code = "codigo"; dem.Sku = sku; dem.OrderId = 10; dem.LineId = 11; dem.InitialQty = 100; dem.ActualQty = 90; dem.DesiredDate = new DateTime(1963, 1, 17); dem.OrderPrice = 25.30; dem.Customer = cust; return(dem); }
private EntityCollector MaterialRequirementsPlanningForOneDemand(Demand demand, IProviderManager providerManager) { EntityCollector entityCollector = new EntityCollector(); EntityCollector response = providerManager.Satisfy(demand, demand.GetQuantity()); entityCollector.AddAll(response); response = providerManager.CreateDependingDemands(entityCollector.GetProviders()); entityCollector.AddAll(response); if (entityCollector.IsSatisfied(demand) == false) { throw new MrpRunException($"'{demand}' was NOT satisfied: remaining is " + $"{entityCollector.GetRemainingQuantity(demand)}"); } return(entityCollector); }
private void CreateGraph(IDbTransactionData dbTransactionData) { foreach (var demandToProvider in dbTransactionData.DemandToProviderGetAll()) { Demand demand = dbTransactionData.DemandsGetById(new Id(demandToProvider.DemandId)); Provider provider = dbTransactionData.ProvidersGetById(new Id(demandToProvider.ProviderId)); if (demand == null || provider == null) { throw new MrpRunException("Demand/Provider should not be null."); } INode fromNode = new Node(demand); INode toNode = new Node(provider); IEdge edge = new Edge(demandToProvider, fromNode, toNode); AddEdge(edge); _originalEdges.Add(edge); } foreach (var providerToDemand in dbTransactionData.ProviderToDemandGetAll()) { Demand demand = dbTransactionData.DemandsGetById(providerToDemand.GetDemandId()); Provider provider = dbTransactionData.ProvidersGetById(providerToDemand.GetProviderId()); if (demand == null || provider == null) { // provider == null can be the case for archive of transactionData, when a // stockExchangeProvider has more than one child stockExchangeDemand // and one of the stockExchangeDemand is archived, but the // stockExchangeProvider cannot be archived yet (because the // stockExchangeProvider is still needed by the other stockExchangeDemand // to correctly calculate the open quantity of a stockExchangeDemand) throw new MrpRunException("Demand/Provider should not be null."); } INode fromNode = new Node(provider); INode toNode = new Node(demand); IEdge edge = new Edge(providerToDemand, fromNode, toNode); AddEdge(edge); _originalEdges.Add(edge); } }
public bool OnAfterLoad_Demand(Demand entity) { try { entity.DEMAND_ID = UtilityHelper.Trim(entity.DEMAND_ID); entity.LINE_ID = UtilityHelper.Trim(entity.LINE_ID); entity.PRODUCT_ID = UtilityHelper.Trim(entity.PRODUCT_ID); entity.PRODUCT_NAME = UtilityHelper.Trim(entity.PRODUCT_NAME); entity.CUSTOMER = UtilityHelper.Trim(entity.CUSTOMER); entity.WEEK_NO = UtilityHelper.Trim(entity.WEEK_NO); entity.DEMAND_TYPE = UtilityHelper.Trim(entity.DEMAND_TYPE); entity.PRODUCT_TYPE = UtilityHelper.Trim(entity.PRODUCT_TYPE); entity.GRADE = UtilityHelper.Trim(entity.GRADE); Product demandProd = FindHelper.FindProduct(entity.LINE_ID, entity.PRODUCT_ID); if (demandProd == null) { return(false); } i++; MicronBEAssyBEMoMaster moMaster; if (InputMart.Instance.MicronBEAssyBEMoMaster.TryGetValue(entity.PRODUCT_ID, out moMaster) == false) { moMaster = new MicronBEAssyBEMoMaster(); moMaster.Product = demandProd; InputMart.Instance.MicronBEAssyBEMoMaster.Add(entity.PRODUCT_ID, moMaster); } MicronBEAssyBEMoPlan moPlan = NewHelper.NewMicronBEAssyMoPlan(moMaster, entity, i); moMaster.AddMoPlan(moPlan); return(false); } catch (Exception e) { WriteHelper.WriteErrorHistory(ErrorLevel.FATAL, string.Format("ErrorMessage : {0} MethodName : {1}", e.Message, System.Reflection.MethodInfo.GetCurrentMethod().Name)); return(false); } }
private void ComposeJunctions(Network net) { FieldsMap fMap = net.FieldsMap; if (!net.Junctions.Any()) { return; } buffer.WriteLine(SectType.JUNCTIONS.ParseStr()); buffer.WriteLine(JUNCS_SUBTITLE); foreach (Node node in net.Junctions) { buffer.Write(" {0}\t{1}", node.Name, fMap.RevertUnit(FieldType.ELEV, node.Elevation)); //if(node.getDemand()!=null && node.getDemand().size()>0 && !node.getDemand()[0].getPattern().getId().equals("")) // buffer.write("\t"+node.getDemand()[0].getPattern().getId()); if (node.Demands.Count > 0) { Demand demand = node.Demands[0]; buffer.Write("\t{0}", fMap.RevertUnit(FieldType.DEMAND, demand.Base)); if (!string.IsNullOrEmpty(demand.pattern.Name) && !net.DefPatId.Equals(demand.pattern.Name, StringComparison.OrdinalIgnoreCase)) { buffer.Write("\t" + demand.pattern.Name); } } if (!string.IsNullOrEmpty(node.Comment)) { buffer.Write("\t;" + node.Comment); } buffer.WriteLine(); } buffer.WriteLine(); }
/** * Arrow equals DemandToProvider and ProviderToDemand */ public List <ILinkDemandAndProvider> GetArrowsToAndFrom(Demand demand) { List <ILinkDemandAndProvider> demandAndProviderLinks = new List <ILinkDemandAndProvider>(); List <ILinkDemandAndProvider> demandToProviders = GetArrowsTo(demand); List <ILinkDemandAndProvider> providerToDemands = GetArrowsFrom(demand); if (demandToProviders != null) { demandAndProviderLinks.AddRange(demandToProviders); } if (providerToDemands != null) { demandAndProviderLinks.AddRange(providerToDemands); } return(demandAndProviderLinks); }
/** * DemandToProvider */ public Providers GetAllChildProvidersOf(Demand demand) { Providers providers = new Providers(); Ids ids = _dbTransactionData.DemandToProviderGetAll().GetByDemandId(demand.GetId()); if (ids == null) { return(null); } foreach (var id in ids) { T_DemandToProvider demandToProvider = _dbTransactionData.DemandToProviderGetById(id); providers.Add( _dbTransactionData.ProvidersGetById(demandToProvider.GetProviderId())); } return(providers); }
private void But_Dell_Click(object sender, EventArgs e) { if (grid_Flats.SelectedRows.Count != 1) { return; } if (!ReallyDoIt()) { return; } Demand cl = grid_Flats.SelectedRows[0].Tag as Demand; if (cl.Deal != null) { MessageBox.Show("Невозможно удалить, т.к. есть связь со сделкой!!"); return; } ModelContext.init().Demands.Remove(cl); save(); }
public void AddDemand(Demand oneDemand, Quantity reservedQuantity) { if (_demands.GetDemandById(oneDemand.GetId()) != null) { throw new MrpRunException("You cannot add an already added demand."); } // if it has quantity that is not reserved, remember it for later reserving if (oneDemand.GetType() == typeof(StockExchangeDemand) && reservedQuantity.IsSmallerThan(oneDemand.GetQuantity())) { _openDemands.Add(oneDemand.GetArticle(), new OpenNode <Demand>(oneDemand, oneDemand.GetQuantity().Minus(reservedQuantity), oneDemand.GetArticle())); } // save demand _demands.Add(oneDemand); }
public R.ResultVm <bool> RemoveServer(string name) { var result = new R.ResultVm <bool>().FromEmptyFailure(); Demand <string> .That(name, "name").HasNonEmptyValue().Result(result); if (result.Errors.Count == 0) { try { return(new ResultVm <bool>().FromSuccessObject(_repo.RemoveServer(name))); } catch (Exception ex) { return(new ResultVm <bool>().FromException(ex)); } } return(result); }
/*public static T_ProductionOrderBom CreateT_ProductionOrderBom() * { * T_ProductionOrderBom tProductionOrderBom = new T_ProductionOrderBom(); * tProductionOrderBom.Quantity = new Random().Next(1, 100); * M_Article article = dbMasterDataCache.M_ArticleGetById( * IdGenerator.GetRandomId(0.M_ArticleGetAll().Count - 1)); * tProductionOrderBom.ArticleChild = article; * tProductionOrderBom.ProductionOrderParent = CreateT_ProductionOrder() * }*/ public static ProductionOrder CreateT_ProductionOrder( Demand demand, Quantity quantity) { if (quantity == null || quantity.GetValue() == null) { throw new MrpRunException("Quantity is not set."); } T_ProductionOrder tProductionOrder = new T_ProductionOrder(); // [ArticleId],[Quantity],[Name],[DueTime],[ProviderId] tProductionOrder.DueTime = demand.GetStartTimeBackward().GetValue(); tProductionOrder.Article = demand.GetArticle(); tProductionOrder.ArticleId = demand.GetArticle().Id; tProductionOrder.Name = $"ProductionOrder for Demand {demand.GetArticle()}"; // connects this provider with table T_Provider tProductionOrder.Quantity = quantity.GetValue().GetValueOrDefault(); return(new ProductionOrder(tProductionOrder)); }
public EntityCollector Satisfy(Demand demand, Quantity demandedQuantity) { // SE:I --> satisfy by orders (PuOP/PrOBom) if (demand.GetType() == typeof(StockExchangeDemand)) { if (demand.GetArticle().ToBuild) { return(_productionManager.Satisfy(demand, demandedQuantity)); } else { return(_purchaseManager.Satisfy(demand, demandedQuantity)); } } // COP or PrOB --> satisfy by SE:W else { return(_stockManager.Satisfy(demand, demandedQuantity)); } }
public R.ResultVm <bool> UpdateServer(string serverName, string address) { var result = new R.ResultVm <bool>().FromEmptyFailure(); Demand <string> .That(serverName, "serverName").HasNonEmptyValue().Result(result); if (result.Errors.Count == 0) { try { return(new ResultVm <bool>().FromSuccessObject(_repo.UpdateServer(serverName, address))); } catch (Exception ex) { return(new ResultVm <bool>().FromException(ex)); } } return(result); }
public ActionResult EditDemand(int id, FormCollection formValues) { Demand demand = demandRepository.FindDemand(id); if (TryUpdateModel(demand)) { demandRepository.Save(); /************** Saving log ***************/ log.DoAll("Demand: " + demand.No + ", " + demand.Thickness + ", " + demand.Color + ", " + demand.Date + ", " + demand.Quantity + ", " + demand.Size + ", " + demand.OrderNo + ", " + demand.MerchID + "."); /*****************************************/ return(RedirectToAction("DemandDetails", new { id = demand.No })); } return(View(demand)); }
public ViewResult Issue(Demand model) { // 区域列表 List <ShopAttributeValues> AreaItemList = _iShopAttributesService.GetListByAttributeId(AttrQuyuId); // 物业类型 List <ShopAttributeValues> TypeItem = _iShopAttributesService.GetListByAttributeId(AttrTypeId); ViewBag.AreaList = AreaItemList == null ? new List <SelectListItem>() : (from m in AreaItemList select new SelectListItem { Text = m.ValueStr, Value = m.ValueStr }).ToList(); ViewBag.TypeList = TypeItem == null ? new List <SelectListItem>() : (from m in TypeItem select new SelectListItem { Text = m.ValueStr, Value = m.ValueStr }).ToList(); if (!ModelState.IsValid) { return(View("Issue")); } ShopPostings postModel = new ShopPostings(); postModel.PIntent = model.Type; postModel.PName = model.Title; postModel.city = "北京"; postModel.Format = model.Format; postModel.district = model.Area; postModel.square = model.Square; postModel.price = model.Price; postModel.Ptype = model.PType; postModel.Pinfo = model.Details; postModel.Endtiem = model.EndDate; postModel.Contacts = model.Contact; postModel.Mobile = model.Mobile; postModel.Addtiem = DateTime.Now; _iShopPostingsService.Insert(postModel); return(View("Succeed")); }
public void Create() { var memoryStore = new List <Demand>(); Demand demandStub = new Demand { Id = 1 }; var mock = new Mock <IRepository <Demand> >(); mock.Setup(repo => repo.GetAll()).Returns(memoryStore.AsQueryable()); mock.Setup(repo => repo.Create(It.IsAny <Demand>())).Returns((Demand demand) => { demand.Id = 1; memoryStore.Add(demand); return(demand); }); var factoryMock = new Mock <IRepositoryFactory>(); factoryMock.Setup(f => f.GetRepository <Demand>()).Returns(mock.Object); _demandController = new DemandController(factoryMock.Object); var emptyJson = _demandController.GetAll(); Assert.IsNotNull(emptyJson); var emptyStore = emptyJson.Value as List <Demand>; Assert.IsNotNull(emptyStore); Assert.AreEqual(emptyStore.Count, 0); var json = _demandController.Create(demandStub); Assert.IsNotNull(json); var result = json.Value as Demand; Assert.NotNull(result); Assert.AreEqual(result.Id, 1); Assert.AreEqual(result.Client, demandStub.Client); var notEmptyJson = _demandController.GetAll(); Assert.IsNotNull(notEmptyJson); var notEmptyStore = notEmptyJson.Value as List <Demand>; Assert.IsNotNull(notEmptyStore); Assert.AreEqual(notEmptyStore.Count, 1); }
public void UnlinkConception(int accessoryPK, int conceptionPK, string userID) { try { // unlink conception Conception conception = db.Conceptions.Find(conceptionPK); Accessory accessory = db.Accessories.Find(accessoryPK); if (conception.CustomerPK != accessory.CustomerPK) { throw new Exception("MÃ HÀNG VÀ PHỤ LIỆU KHÔNG CÙNG KHÁCH HÀNG!"); } List <DemandedItem> demandedItems = (from dI in db.DemandedItems where dI.AccessoryPK == accessoryPK select dI).ToList(); foreach (var item in demandedItems) { Demand demand = db.Demands.Find(item.DemandPK); if (demand.ConceptionPK == conception.ConceptionPK) { throw new Exception("MÃ HÀNG VÀ PHỤ LIỆU ĐÃ ĐƯỢC LIÊN KẾT VÀ SỬ DỤNG!"); } } ConceptionAccessory conceptionAccessory = (from ca in db.ConceptionAccessories where ca.AccessoryPK == accessoryPK && ca.ConceptionPK == conceptionPK select ca).FirstOrDefault(); db.ConceptionAccessories.Remove(conceptionAccessory); // lưu activity unlink Activity activity1 = new Activity("unlink", conception.ConceptionCode, "Conception", userID); Activity activity2 = new Activity("unlink", accessory.AccessoryID, "Accessory", userID); db.Activities.Add(activity1); db.Activities.Add(activity2); db.SaveChanges(); } catch (Exception e) { throw e; } }
public Demand CreateDemand(int customerPK, int conceptionPK, double totalDemand, string receiveDevision, string userID) { try { DateTime now = DateTime.Now; string tempDay = (now.Day + "").Length == 1 ? '0' + (now.Day + "") : (now.Day + ""); string tempMonth = (now.Month + "").Length == 1 ? '0' + (now.Month + "") : (now.Month + ""); string tempYear = (now.Year + "").Substring((now.Year + "").Length - 2); string dateNow = tempDay + tempMonth + tempYear; string demandID = ""; Demand demand = (from acc in db.Demands.OrderByDescending(unit => unit.DemandPK) select acc).FirstOrDefault(); if (demand == null || !demand.DemandID.Contains(dateNow)) { demandID = "AST-PCP-" + dateNow + "01"; } else { int length = demand.DemandID.Length; string tempStr = (Int32.Parse(demand.DemandID.Substring(length - 2, 2)) + 1) + ""; if (tempStr.Length == 1) { tempStr = "0" + tempStr; } demandID = demand.DemandID.Substring(0, length - 2) + tempStr; } // create demand demand = new Demand(demandID, totalDemand, conceptionPK, receiveDevision, userID); db.Demands.Add(demand); db.SaveChanges(); demand = (from de in db.Demands.OrderByDescending(unit => unit.DemandPK) select de).FirstOrDefault(); return(demand); } catch (Exception e) { throw e; } }
public bool AddDemand(DemandViewModelEditAPI demandViewModelEditApi, out string reason) { reason = string.Empty; var demand = _demandDbContext.Demands.SingleOrDefault(item => item.DemandCode == demandViewModelEditApi.DemandCode); if (demand != null) { reason = "已存在名称:" + demandViewModelEditApi.DemandCode; return(false); } var user = _demandDbContext.Users.SingleOrDefault(item => item.UserName == demandViewModelEditApi.User); if (user == null) { reason = "查找不到该提交人"; return(false); } var customer = _demandDbContext.Customers.SingleOrDefault(item => item.Name == demandViewModelEditApi.Customer); if (customer == null) { reason = "查找不到该相关客户"; return(false); } Demand newDemand = new Demand(); newDemand.Id = 0; newDemand.DemandCode = demandViewModelEditApi.DemandCode; newDemand.DemandType = (DemandType)demandViewModelEditApi.DemandType; newDemand.DemandDetail = demandViewModelEditApi.DemandDetail; newDemand.UserId = user.Id; newDemand.CustomerId = customer.Id; newDemand.Remarks = demandViewModelEditApi.Remarks; newDemand.DemandPhase = DemandPhase.需求提出; newDemand.CreateTime = DateTime.Now; newDemand.SoftwareVersionId = null; _demandDbContext.Demands.Add(newDemand); _demandDbContext.SaveChanges(); return(true); }
private void SalaryDetermination(int indexCategory, Basic_Work basic_Work, string industryName, int coefficient) { //Начальный оклад int salary_Start = basic_Work.Salary + rnd.Next(-(int)(basic_Work.Salary * 0.35), (int)(basic_Work.Salary * 0.35)); //Повышение квалификации int salary_Coefficient = (int)(salary_Start * coefficient / 100.0); //Восстребовательность int salary_Demand = (int)(salary_Start * Demand.Professions(industryName) / 100.0); //Расчет финальной зарплаты int salary_End = salary_Start + salary_Coefficient + salary_Demand; //Расчет плана int randomWorkPlan = rnd.Next(450, 600); //Создание класса текущей работы _finalJobs.Add(new FinalJob(indexCategory, industryName, basic_Work.ProfessionName, salary_Start, salary_Coefficient, salary_Demand, salary_End, randomWorkPlan, basic_Work.Req_Intelligence, basic_Work.Req_Charm, basic_Work.Req_PhysicalDevelopment)); }
public ActionResult CreateDemand(Demand d) { if (ModelState.IsValid) { d.MerchID = Convert.ToInt32(Session["merchID"]); d.Date = DateTime.Now.Date; demandRepository.Add(d); /************** Saving log ***************/ log.DoAll("Demand: " + d.No + ", " + d.Thickness + ", " + d.Color + ", " + d.Date + ", " + d.Quantity + ", " + d.Size + ", " + d.OrderNo + ", " + d.MerchID + "."); /*****************************************/ demandRepository.Save(); return(View("Merch", merchRepository.GetMerchByID(Convert.ToInt32(Session["merchID"])))); } return(View("~/Views/Home/Error.aspx")); }
public void UpdateListOfDemands(string name) { Debug.Log(name); for (int i = 0; i < ListOfDemands.Count; i++) { Debug.Log(ListOfDemands[i]); } if (ListOfDemands.IndexOf(new Demand(name)) > -1) { Demand d = ListOfDemands[ListOfDemands.IndexOf(new Demand(name))]; d.Amount -= 1; UpdateTextCanvas(d); if (Win()) { GameManager gm = GameObject.FindGameObjectWithTag("GameManager").GetComponent <GameManager>(); gm.loadNextLevel(); } } }
public bool FillDemandOnTable(ref RSATable table, Graph graph, Demand demand, GraphPath path, List <AvailableSlot> availableSlots, bool protection = false) { List <GraphLink> pathLinks = path.ToLinks(graph.Links); List <List <int> > emptySlots = new List <List <int> >(); foreach (var column in table.Table.Keys) { var reference = availableSlots.FirstOrDefault(r => r.Link.GetLinkId() == column); if (reference != null) { emptySlots.Add(new List <int>(reference.Availables)); } } List <int> intersection = emptySlots.First(); foreach (var list in emptySlots.Skip(1)) { intersection = intersection.Intersect(list).ToList(); } List <int> indexesToFill = GetIndexesToFill(intersection, demand.Slots); if (indexesToFill == null) { return(false); } foreach (GraphLink link in pathLinks) { foreach (var slot in indexesToFill) { table.Table[link.GetLinkId()][slot].IsProtectionDemand = protection; table.Table[link.GetLinkId()][slot].Values.Add(demand.Id.ToString()); } } return(true); }
void fillCombos(ComboBox c_dem, ComboBox c_sup, bool asEdit = false) { Supply[] supplies; Demand[] demands; Demand ld = c_dem.SelectedItem as Demand; Supply ls = c_sup.SelectedItem as Supply; if (ld == null) { supplies = ModelContext.init().Supplies.Include(s => s.Deal).Include(s => s.Realty).Include(s => s.Realty.Earth).Include(s => s.Realty.Flat).Include(s => s.Realty.House).ToArray(); } else { supplies = ModelContext.init().Supplies.Include(s => s.Deal).Include(s => s.Realty).Include(s => s.Realty.Earth).Include(s => s.Realty.Flat).Include(s => s.Realty.House).AsEnumerable() .Where(s => s.Compare(ld)).ToArray(); } if (ls == null) { demands = ModelContext.init().Demands.Include(i => i.Deal).Include(i => i.HouseDemand).Include(i => i.EarthDemand).Include(i => i.FlatDemand).ToArray(); } else { demands = ModelContext.init().Demands.Include(i => i.Deal).Include(i => i.HouseDemand).Include(i => i.EarthDemand).Include(i => i.FlatDemand).AsEnumerable().Where(d => ls.Compare(d)).ToArray(); } supplies = supplies.Where(s => s.Deal == null || asEdit && (ls != null && s.ID == ls.ID)).ToArray(); demands = demands.Where(s => s.Deal == null || asEdit && (ld != null && s.ID == ld.ID)).ToArray(); c_sup.Items.Clear(); c_dem.Items.Clear(); c_sup.Items.AddRange(supplies); c_dem.Items.AddRange(demands); if (demands.Contains(ld)) { c_dem.SelectedItem = ld; } if (supplies.Contains(ls)) { c_sup.SelectedItem = ls; } }
public R.ResultVm <bool> AddServer(ServerOnlyVm server) { var rv = new ResultVm <bool>().FromEmptyFailure(); Demand <string> .That(server.Name, "server.Name").HasNonEmptyValue().Result(rv); if (rv.Errors.Count == 0) { try { return(new ResultVm <bool>().FromSuccessObject(_repo.AddServer(server.ToDataModel()))); } catch (Exception ex) { return(new ResultVm <bool>().FromException(ex)); } } else { return(rv); } }
public async Task <IActionResult> Create(Demand demand) { bool status = false; if (ModelState.IsValid) { using (var client = new HttpClient()) { //string baseUri = _settings.ApiUrl + "/" + Constants.API + "/" + Constants.Demand + "/"; string baseUri = "https://webapilatesttal.azurewebsites.net/" + Constants.API + "/" + Constants.Demand + "/"; client.BaseAddress = new Uri(baseUri); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", HttpContext.Session.GetString("JWTToken")); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var response = await client.PostAsJsonAsync(baseUri, demand); var result = response.Content.ReadAsStringAsync().Result; if (result == "") { status = false; } else { status = JsonConvert.DeserializeObject <bool>(result); } } if (status) { ViewBag.message = "Demand Created Successfully!"; ModelState.Clear(); } else { ViewBag.message = "Unable to create Demand!"; } } return(await Task.FromResult(View())); }
public void Step() { Supply.Clear(); Demand.Clear(); foreach (var agent in Agents) { // Adding supplies from every agent in market to market's supply foreach (var entry in agent.Supplies) { Good good = entry.Key; int amount = entry.Value; if (Supply.ContainsKey(good)) { Supply[good] += amount; } else { Supply[good] = amount; } } // Adding demands from every agent in market to market's demand foreach (var entry in agent.Demands) { Good good = entry.Key; int amount = entry.Value; if (Demand.ContainsKey(good)) { Demand[good] += amount; } else { Demand[good] = amount; } } } }
public R.ResultVm <Server> GetServerMetrics(string serverName, DateTime start, DateTime end) { var result = new R.ResultVm <Server>().FromEmptyFailure(); Demand <string> .That(serverName, "serverName").HasNonEmptyValue().Result(result); Demand <DateTime> .That(start, "start").IsBefore(end).Result(result); if (result.Errors.Count == 0) { try { return(new ResultVm <Server>().FromSuccessObject(_repo.GetServerMetrics(serverName, start, end))); } catch (Exception ex) { return(new ResultVm <Server>().FromException(ex)); } } return(result); }
private async Task <RSATable> FillTable(RSATable table, Graph graph, Demand demand, List <Tuple <GraphPath, GraphPath> > paths) { bool filled = false; foreach (var path in paths) { var tableMemory = table.CopyObject <RSATable>(); await InfoLogger.LogInformation($"trying main path: {string.Join("->", path.Item1.Path)} distance: {path.Item1.ToLinks(graph.Links).Sum(r=>r.Length)}"); List <AvailableSlot> availableTableSlots = base.GetAvailableTableSlots(graph, path.Item1, tableMemory); if (RSATableFill.FillDemandOnTable(ref tableMemory, graph, demand, path.Item1, availableTableSlots)) { availableTableSlots = GetAdditionalAvailableTableSlots(graph, path, tableMemory); await InfoLogger.LogInformation($"trying secundary path: {string.Join("->", path.Item2.Path)} distance: {path.Item2.ToLinks(graph.Links).Sum(r => r.Length)}"); if (RSATableFill.FillDemandOnTable(ref tableMemory, graph, demand, path.Item2, availableTableSlots, true)) { DemandSupplyMemory.Add(new DemandLinkPair(demand, path)); filled = true; await InfoLogger.LogInformation($"demand supplied\n"); table = tableMemory; await InfoLogger.LogInformation(table.ToStringTable()); supplied++; break; } } } if (filled == false) { await InfoLogger.LogInformation($"It's not possible to supply demand of {demand.Slots} from {demand.NodeIdFrom} to {demand.NodeIdTo}\n"); } return(table); }
public async Task <ActionResult> CreateDemond([FromBody] DemandCreateDto demand) { int id = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); var logineduser = await _auth.VerifyUser(id); var num = String.Format("{0:d9}", (DateTime.Now.Ticks / 10) % 1000000000); Demand _newDemand = new Demand() { Name = demand.Name, DemandNumber = num, Company = logineduser.Company, CreateDate = DateTime.Now, CheckStatus = 1, Status = true, Created = logineduser }; _context.Demands.Add(_newDemand); await _context.SaveChangesAsync(); foreach (var item in demand.DemandProduct) { DemandProduct _newDemanProduct = new DemandProduct() { Demand = _newDemand, Product = await _context.Products.FirstOrDefaultAsync(s => s.Id == item.ProductId), Quantity = item.Quantity, Parcel = await _context.Parcels.FirstOrDefaultAsync(s => s.Id == item.ParcelId), Country = await _context.Country.FirstOrDefaultAsync(s => s.Id == item.CountryId), Workers = await _context.Workers.FirstOrDefaultAsync(s => s.Id == item.RequestingWorkerId), ExpirationDate = item.ExpirationDate, RequiredDate = item.RequiredDate }; _context.DemandProducts.Add(_newDemanProduct); await _context.SaveChangesAsync(); } return(StatusCode(201)); }
public void TestGetFittedDemandRecord_Demand_CityUnFit() { demand = new Demand { Id = 4, City = CityDef.Shantou, ProjectName = "project1", ReceiveDate = new DateTime(2013, 12, 12, 6, 0, 0) }; Demand fittedDemand = demandList.GetFittedRecord(demand); Assert.IsNull(fittedDemand); }
private void dumpDemand(Demand toDump) { Console.WriteLine(ObjectDumper.Dump(toDump)); }
public void FinishDemand(Demand demand) { demand.ExpectedSubscriber = ExpectedSubscriber; demand.ExpectedProfit = ExpectedProfit; demand.ActualCompleteDate = DateTime.Now; demand.ProjectState = ProjectState.GetProjectStateIndex(); demand.Satisfactory = Satisfactory.GetSatisfactoryIndex(); demand.ProgressDescription = ProgressDescription; demand.Comments = Comments; }
public static FinishDemandView Parse(Demand demand) { return new FinishDemandView() { Id = demand.Id, City = demand.City.GetCityName(), ProjectName = demand.ProjectName, ExpectedSubscriber = demand.ExpectedSubscriber, ExpectedProfit = demand.ExpectedProfit, ProjectState = ProjectStateDef.Complete.GetProjectStateDescription(), Satisfactory = demand.Satisfactory.GetSatisfactoryDescription(), ProgressDescription = demand.ProgressDescription, Comments = demand.Comments }; }
public void GenerateDemand(Random rand) { for (int i = 0; i < demand.Length; i++) { if (demand[i] == null) continue; int randomChange = rand.Next(0, 1000); if (randomChange < 25) { bool eBook = false; int randEbook = rand.Next(0, 100); if (randEbook < currentEbookChance) { eBook = true; currentEbookChance -= 5; if (currentEbookChance < minEBookChance) currentEbookChance = minEBookChance; } Genre genre = (Genre)(rand.Next(0, Book.numberOfGenres)); demand[i] = new Demand(genre, eBook, textures[(int)genre]); } } while (emptyPos.Count != 0) { int randIndex = rand.Next(0, emptyPos.Count - 1); Genre genre = (Genre)(rand.Next(0, Book.numberOfGenres)); bool eBook = false; int randEbook = rand.Next(0, 100); if (randEbook < currentEbookChance) { eBook = true; currentEbookChance -= 5; if (currentEbookChance < minEBookChance) currentEbookChance = minEBookChance; } else { currentEbookChance += 5; if (currentEbookChance > maxEBookChance) currentEbookChance = maxEBookChance; } demand[emptyPos[randIndex]] = new Demand(genre, eBook, textures[(int)genre]); emptyPos.RemoveAt(randIndex); } if (doSort) Sort(); }
private void Sort() { Demand[] tempDemand = new Demand[totalNumber]; int sorted = 0; for (int i = 0; i < Book.numberOfGenres; i++) { for (int j = 0; j < totalNumber; j++) { if ((Genre)i == demand[j].genre) { tempDemand[sorted] = demand[j]; sorted++; } } } demand = tempDemand; }
private void Fill(Random rand) { for (int i = 0; i < demand.Length; i++) { Genre genre = (Genre)(rand.Next(0, Book.numberOfGenres)); demand[i] = new Demand(genre, false, textures[(int)genre]); } if (doSort) Sort(); }
public ActionResult getChildren() { List<Demand> ds = new List<Demand>(); long id = int.Parse(Request.QueryString["id"]); 需求计划 model = 需求计划管理.查找需求计划(id); if (model.来源需求计划列表.Any()) { foreach (var item in model.来源需求计划列表) { Demand d = new Demand(); d.title = item.需求计划数据.需求计划标题; d.contactMan = item.需求计划数据.联系人; d.phone = item.需求计划数据.联系电话; d.status = item.需求计划数据.审核历史列表.Last().审核状态.ToString(); d.time = item.需求计划数据.建议完成时间.ToString("yyyy/MM/dd"); d.cgyear = item.需求计划数据.采购年度.ToString("yyyy/MM/dd"); d.security = (int)item.需求计划数据.秘密等级; d.depart = item.需求计划数据.承办部门; d.bzdw = item.需求计划数据.编制单位; ds.Add(d); } } else { Demand d = new Demand(); d.title = model.需求计划标题; d.contactMan = model.联系人; d.phone = model.联系电话; d.time = model.建议完成时间.ToString("yyyy/MM/dd"); d.cgyear = model.采购年度.ToString("yyyy/MM/dd"); d.security = (int)model.秘密等级; d.depart = model.承办部门; d.bzdw = model.编制单位; ds.Add(d); } JsonResult json = new JsonResult() { Data = new { items = ds } }; return Json(json, JsonRequestBehavior.AllowGet); }
/// <summary> /// Processes operation authorization statement node. /// </summary> /// <param name="node">The node.</param> private void Process_OperationAuthorizationStatement(dynamic node) { if (node.GetBrand() == "Demand") { Demand demand = new Demand(); // Map source location and node to object demand.AddMetaInfo(new SourceLocationInfo(node, context)); context.AddObject(node, demand); // OperationContract demand.OperationAuthorization = (OperationAuthorization)NameContext.Current.Scope; // Text demand.Text = node.Text; // Rule demand.Rule = this.Process(node.Rule); demand.Rule.ExpectedType = BuiltInType.Bool; } }
public ActionResult DemandItems1() { List<Demand> ds = new List<Demand>(); int PageCount = 0; int CurrentPage = int.Parse(Request.QueryString["p"]); string type = Request.QueryString["type"];//2:未提交,3:审核中,4:审核通过,5:审核未通过 IEnumerable<需求计划> d = null; switch (type) { case "1": d = 需求计划管理.查询需求计划(20 * (CurrentPage - 1), 20); d = d.Where(o => o.需求发起单位链接.用户ID == currentUser.Id && o.来源需求计划列表.Any()); break; case "2": d = 需求计划管理.查询需求计划(20 * (CurrentPage - 1), 20); d = d.Where(o => o.审核历史列表.Count == 0 && o.当前处理单位链接.用户ID == o.需求发起单位链接.用户ID && o.需求发起单位链接.用户ID == currentUser.Id && o.来源需求计划列表.Any()); break; case "3": d = 需求计划管理.查询需求计划(20 * (CurrentPage - 1), 20); d = d.Where(o => (o.审核历史列表.Any() && o.审核历史列表.Last().审核状态 != 审核状态.审核未通过 && o.审批流程单位列表.Count > o.审核历史列表.Count && o.需求发起单位链接.用户ID == currentUser.Id && o.来源需求计划列表.Any())); break; case "4": d = 需求计划管理.查询需求计划(20 * (CurrentPage - 1), 20); d = d.Where(o => o.审核历史列表.Any() && o.审核历史列表.Count == o.审批流程单位列表.Count && o.审核历史列表.Last().审核状态 == 审核状态.审核通过 && o.来源需求计划列表.Any() && (o.需求发起单位链接.用户ID == currentUser.Id || currentUser.Id == 10003)); break; case "5": d = 需求计划管理.查询需求计划(20 * (CurrentPage - 1), 20); d = d.Where(o => o.审核历史列表.Any() && o.审核历史列表.Last().审核状态 == 审核状态.审核未通过 && o.需求发起单位链接.用户ID == currentUser.Id && o.来源需求计划列表.Any()); break; case "6": d = 需求计划管理.查询需求计划(20 * (CurrentPage - 1), 20); d = d.Where(o => !o.审核历史列表.Any() && (o.审批流程单位列表.Any() || o.需求发起单位链接.用户ID != o.当前处理单位链接.用户ID) && o.需求发起单位链接.用户ID == currentUser.Id && o.来源需求计划列表.Any()); break; } if (d != null) { PageCount = d.Count() / 20; if (d.Count() % 20 > 0) { PageCount++; } foreach (var item in d) { Demand m = new Demand(); m.Id = item.Id; m.title = item.需求计划标题; m.time = item.建议完成时间.ToString("yyyy/MM/dd"); m.count = item.来源需求计划列表.Count; if (string.IsNullOrWhiteSpace(item.联系人)) { m.contactMan = ""; } else { m.contactMan = item.联系人; } if (string.IsNullOrWhiteSpace(item.联系电话)) { m.phone = ""; } else { m.phone = item.联系电话; } m.lastId = false; if ((item.并入需求计划链接.需求计划ID == -1 || item.并入需求计划链接.需求计划ID != -1) && item.审核历史列表.Any() && item.审核历史列表.Last().审核状态 == 审核状态.审核通过 && item.审批流程单位列表.Count == item.审核历史列表.Count) { m.lastId = true; m.finish = false; if (item.流程已完成) { m.finish = true; } } if (item.审核历史列表.Any() && item.审批流程单位列表.Any() && item.审核历史列表.Count < item.审批流程单位列表.Count && item.审核历史列表.Last().审核状态 != 审核状态.审核未通过) { m.status = "审核中"; m.sum = 1; } else if (item.审核历史列表.Any() && item.审核历史列表.Count >= item.审批流程单位列表.Count && item.审核历史列表.Last().审核状态 == 审核状态.审核通过) { m.status = "审核通过"; m.sum = 1; } else if (!item.审核历史列表.Any() && item.审批流程单位列表.Any()) { m.status = "待审核"; m.sum = 1; } else if (item.审核历史列表.Any() && item.审核历史列表.Last().审核状态 == 审核状态.审核未通过) { m.status = "审核未通过"; m.reason = item.审核历史列表.Last().审核不通过原因; m.sum = 0; } else if (item.需求发起单位链接 == item.当前处理单位链接) { m.status = "未提交"; m.sum = 0; } ds.Add(m); } } JsonResult json = new JsonResult() { Data = new { items = ds, Pcount = PageCount, Cpage = CurrentPage } }; return Json(json, JsonRequestBehavior.AllowGet); }
public void TestGetFittedDemandRecord_Demand_Fit() { demand = new Demand { Id = 4, City = CityDef.Guangzhou, ProjectName = "project1", ReceiveDate = new DateTime(2013, 12, 12, 6, 0, 0) }; Demand fittedDemand = demandList.GetFittedRecord(demand); Assert.IsNotNull(fittedDemand); Assert.AreEqual(fittedDemand.Id, 1); }
/// <summary> /// Solves the current routing problem. /// </summary> private void Solve(int number_of_orders, int number_of_vehicles) { Console.WriteLine("Creating model with " + number_of_orders + " orders and " + number_of_vehicles + " vehicles."); // Finalizing model int number_of_locations = locations_.Length; RoutingModel model = new RoutingModel(number_of_locations, number_of_vehicles, vehicle_starts_, vehicle_ends_); // Setting up dimensions const int big_number = 100000; NodeEvaluator2 manhattan_callback = new Manhattan(locations_, 1); model.AddDimension( manhattan_callback, big_number, big_number, false, "time"); NodeEvaluator2 demand_callback = new Demand(order_demands_); model.AddDimension(demand_callback, 0, vehicle_capacity_, true, "capacity"); // Setting up vehicles for (int vehicle = 0; vehicle < number_of_vehicles; ++vehicle) { int cost_coefficient = vehicle_cost_coefficients_[vehicle]; NodeEvaluator2 manhattan_cost_callback = new Manhattan(locations_, cost_coefficient); model.SetVehicleCost(vehicle, manhattan_cost_callback); model.CumulVar(model.End(vehicle), "time").SetMax( vehicle_end_time_[vehicle]); } // Setting up orders for (int order = 0; order < number_of_orders; ++order) { model.CumulVar(order, "time").SetRange(order_time_windows_[order].start_, order_time_windows_[order].end_); int[] orders = {order}; model.AddDisjunction(orders, order_penalties_[order]); } // Solving RoutingSearchParameters search_parameters = RoutingModel.DefaultSearchParameters(); search_parameters.FirstSolutionStrategy = FirstSolutionStrategy.Types.Value.ALL_UNPERFORMED; Console.WriteLine("Search"); Assignment solution = model.SolveWithParameters(search_parameters); if (solution != null) { String output = "Total cost: " + solution.ObjectiveValue() + "\n"; // Dropped orders String dropped = ""; for (int order = 0; order < number_of_orders; ++order) { if (solution.Value(model.NextVar(order)) == order) { dropped += " " + order; } } if (dropped.Length > 0) { output += "Dropped orders:" + dropped + "\n"; } // Routes for (int vehicle = 0; vehicle < number_of_vehicles; ++vehicle) { String route = "Vehicle " + vehicle + ": "; long order = model.Start(vehicle); if (model.IsEnd(solution.Value(model.NextVar(order)))) { route += "Empty"; } else { for (; !model.IsEnd(order); order = solution.Value(model.NextVar(order))) { IntVar local_load = model.CumulVar(order, "capacity"); IntVar local_time = model.CumulVar(order, "time"); route += order + " Load(" + solution.Value(local_load) + ") " + "Time(" + solution.Min(local_time) + ", " + solution.Max(local_time) + ") -> "; } IntVar load = model.CumulVar(order, "capacity"); IntVar time = model.CumulVar(order, "time"); route += order + " Load(" + solution.Value(load) + ") " + "Time(" + solution.Min(time) + ", " + solution.Max(time) + ")"; } output += route + "\n"; } Console.WriteLine(output); } }
public static DemandView Parse(Demand demand) { return new DemandView() { AcceptPath = demand.AcceptPath.GetAcceptPathDescription(), ActualCompleteDate = demand.ActualCompleteDate, City = demand.City.GetCityName(), Comments = demand.Comments, CustomerLevel = demand.CustomerLevel.GetCustomerLevelValue().ToString(), DemandLevel = demand.DemandLevel.GetDemandLevelDescription(), DemandSource = demand.DemandSource.GetDemandSourceDescription(), DemandType = demand.DemandType.GetDemandTypeDescription(), Department = demand.Department, ExpectedCompleteDate = demand.ExpectedCompleteDate, ExpectedProfit = demand.ExpectedProfit, ExpectedSubscriber = demand.ExpectedSubscriber, Id = demand.Id, MarketingTheme = demand.MarketingTheme.GetMarketingThemeDescription(), ProgressDescription = demand.ProgressDescription, ProjectName = demand.ProjectName, ProjectState = demand.ProjectState.GetProjectStateDescription(), ReceiveDate = demand.ReceiveDate, Recept = demand.Recept, Satisfactory = demand.Satisfactory.GetSatisfactoryDescription(), Supporter = demand.Supporter, AllowFinish = false }; }