Пример #1
0
        public IAnswer AskAnswer(IQuestion question)
        {
            var j = 0;

            var choices = new Dictionary<char,IChoice>();
            question.Choices.ForEach(c => choices.Add((char)('a' + j++), c));

            var answerChar = '\0';

            do
            {
                Console.Clear();
                Console.WriteLine("Question: {0}", question.QuestionString);

                foreach (var choice in choices)
                {
                    Console.WriteLine("{0}. {1}", choice.Key, choice.Value.ChoiceText);
                }

                Console.Write("\nAnswer: ");
                var readLine = Console.ReadLine();
                if (readLine == null) continue;

                if (new[] { "back", "b", "oops", "p", "prev" }.Contains(readLine.ToLower()))
                {
                    return question.CreateAnswer(Choice.PREVIOUS_ANSWER);
                }

                answerChar = readLine[0];
            } while (!choices.ContainsKey(answerChar));

            return question.CreateAnswer(choices[answerChar]);
        }
Пример #2
0
        public static Dictionary<int, List<Visit>> GetVisitData(string path)
        {
            Dictionary<int, List<Visit>> data = new Dictionary<int, List<Visit>>();
            Random r = new Random();

            foreach (string row in File.ReadLines(path))
            {
                string[] split = row.Split(',');

                if (split.Length > 0)
                {
                    int id = int.Parse(split[0]);
                    Visit visit = new Visit(id, r.Next(1, 10), int.Parse(split[2]), DateTime.Parse(split[1]));

                    if (data.ContainsKey(id))
                    {
                        data[id].Add(visit);
                    }
                    else
                    {
                        data.Add(id, new List<Visit>(){visit});
                    }
                }
            }

            return data;
        }
Пример #3
0
 public override SuggestedMoves ChooseColor(Color[,] board)
 {
     IDictionary<Color, int> count = new Dictionary<Color, int>();
     foreach(MapNode edgeNode in MapBuilder.BuildMap(board).GetNeighbors())
     {
         if (!count.ContainsKey(edgeNode.Color))
         {
             count[edgeNode.Color] = 1;
         }
         else
         {
             count[edgeNode.Color] = count[edgeNode.Color] + 1;
         }
     }
     return new SuggestedMoves(count.OrderByDescending(keyValuePair => keyValuePair.Value).First().Key);
 }
        public SuggestedMoves GetPath(Color[,] board)
        {
            //Get the farthest nodes
            TreeNode head = MapBuilder.BuildTree(board);
            ISet<TreeNode> farthestNodes = new HashSet<TreeNode>();
            int highestDepth = 0;
            foreach (TreeNode node in head.BFS()) //DFS would be better
            {
                int depth = GetDepth(node);
                if (depth > highestDepth)
                {
                    highestDepth = depth;
                    farthestNodes.Clear();
                    farthestNodes.Add(node);
                }
                else if (depth == highestDepth)
                {
                    farthestNodes.Add(node);
                }
            }

            Console.Write("Farthest nodes are ");
            farthestNodes.Select(n => n.Color).ToList().ForEach(c => Console.Write(c + ", "));
            Console.WriteLine("\r\nFarthest node is " + GetDepth(farthestNodes.First()) + " away from the current");

            //get the color that would step towards each color
            IDictionary<Color, int> tally = new Dictionary<Color, int>();
            foreach (TreeNode farthestNode in farthestNodes)
            {
                TreeNode currentNode = farthestNode;
                while (currentNode.Parent != head)
                {
                    currentNode = currentNode.Parent;
                }
                if (!tally.ContainsKey(currentNode.Color))
                {
                    tally.Add(currentNode.Color, 1);
                }
                else
                {
                    tally[currentNode.Color]++;
                }
            }
            SuggestedMoves suggestedMoves = new SuggestedMoves();
            suggestedMoves.AddFirst(new SuggestedMove(tally.OrderByDescending(kvp => kvp.Value).Select(n => n.Key)));
            return suggestedMoves;
        }
Пример #5
0
		public override void Visit(ControllerTreeNode node)
		{
			var type = GenerateTypeDeclaration(@namespace, node.PathNoSlashes + naming.ToActionWrapperName(node.Name));

			occurences = new Dictionary<string, short>();

			// We can only generate empty argument methods for actions that appear once and only once.
			foreach (var child in node.Children)
			{
				if (!(child is ActionTreeNode)) continue;

				if (!occurences.ContainsKey(child.Name))
					occurences[child.Name] = 0;
				
				occurences[child.Name]++;
			}

			typeStack.Push(type);
			base.Visit(node);
			typeStack.Pop();
		}
        public MainViewModel()
        {
            // please adjust this to meet your system layout ...
            // obviously this should be changed to load file dialog usage :)
            try
            {
                _movies = DataLoader.ReadItemLabels("u.item");
                _trainData = DataLoader.ReadTrainingData("u.data");
            }
            catch (Exception)
            {
                MessageBox.Show("Error loading data files! Please check ViewModel.cs for file location!", "Error loading files", MessageBoxButton.OK, MessageBoxImage.Error);
                Application.Current.Shutdown();
            }

            Movies = new ObservableCollection<Movie>(_movies.OrderBy(m=>m.Title));
            NewRank = 1;
            RaisePropertyChanged(() => NewRank);
            SelectedMovie = Movies.First();
            RaisePropertyChanged(() => SelectedMovie);

            Ranking = new Dictionary<int, int>();
            AddRankCommand = new RelayCommand(() => {
                if (!Ranking.ContainsKey(SelectedMovie.Id)) {
                    Log += string.Format("{0} - rank: {1}\n", SelectedMovie, NewRank);
                    RaisePropertyChanged(() => Log);
                    Ranking.Add(SelectedMovie.Id, NewRank);
                    Movies.Remove(SelectedMovie);
                    SelectedMovie = Movies.First();
                    RaisePropertyChanged(() => SelectedMovie);
                }
                var rec = Engine.GetRecommendations(_movies, Ranking, _trainData);
                var foo = rec.OrderByDescending(e => e.Rank);//.Where(e => !Ranking.ContainsKey(e.Id));
                Recomendations =new ObservableCollection<Movie>(foo);
                this.RaisePropertyChanged(() => Recomendations);
            });
        }
Пример #7
0
		public static string DisposerInfo()
		{
			var info = new Dictionary<string, int>();
			foreach (Disposer disposer in Disposers)
			{
				if (info.ContainsKey(disposer.GetType().Name))
				{
					info[disposer.GetType().Name] += 1;
				}
				else
				{
					info[disposer.GetType().Name] = 1;
				}
			}
			info = info.OrderByDescending(s => s.Value).ToDictionary(p => p.Key, p => p.Value);
			StringBuilder sb = new StringBuilder();
			sb.Append("\r\n");
			foreach (string key in info.Keys)
			{
				sb.Append($"{info[key],10} {key}\r\n");
			}
			
			return sb.ToString();
		}
Пример #8
0
        public JsonResult DataTable_IgnoreGroups(jQueryDataTableParamModel param, List<String> SubjectID = null, List<String> Class = null, List<String> Check = null, String Search = null, String ShowIgnore = null, String ShowNotIgnore = null)
        {
            if (SubjectID != null && Class != null && Check != null)
            {
                OutputHelper.SaveIgnoreGroups(SubjectID, Class, Check, false);
            }

            Dictionary<String, Group> dbGroups = Clone.Dictionary<String, Group>((Dictionary<String, Group>)(CurrentSession.Get("IgnoreGroups") ?? InputHelper.Groups));
            //Dictionary<String, Group> dbGroups = InputHelper.Groups;

            var Groups = from m in dbGroups.Values select m;

            var total = Groups.Count();

            if (!string.IsNullOrEmpty(Search))
            {
                Groups = Groups.Where(m => m.MaMonHoc.ToLower().Contains(Search.ToLower()) || m.TenMonHoc.ToLower().Contains(Search.ToLower()));
            }

            if (ShowIgnore != null && ShowNotIgnore != null)
            {
                if (ShowIgnore == "checked" && ShowNotIgnore != "checked")
                {
                    Groups = Groups.Where(m => m.IsIgnored == true);
                }
                if (ShowIgnore != "checked" && ShowNotIgnore == "checked")
                {
                    Groups = Groups.Where(m => m.IsIgnored == false);
                }
                if (ShowIgnore != "checked" && ShowNotIgnore != "checked")
                {
                    Groups = Groups.Where(m => false);
                }
            }

            var Result = new List<string[]>();

            var MH = (from m in InputHelper.db.This
                      select new
                      {
                          MaMonHoc = m.MaMonHoc,
                          Nhom = m.Nhom,
                      }).Distinct();

            Dictionary<String, List<String>> CheckMH = new Dictionary<string, List<string>>();

            foreach (var m in MH)
            {
                if (CheckMH.ContainsKey(m.MaMonHoc))
                    CheckMH[m.MaMonHoc].Add(m.Nhom);
                else
                    CheckMH.Add(m.MaMonHoc, new List<String> { m.Nhom });
            }

            foreach (var su in Groups.OrderBy(m => m.TenMonHoc))
            {
                if (CheckMH.ContainsKey(su.MaMonHoc))
                {
                    if (!CheckGroup(CheckMH[su.MaMonHoc], su.Nhom.ToString()))
                    {
                        Result.Add(new string[] {
                                            su.MaMonHoc,
                                            su.TenMonHoc,
                                            su.TenBoMon,
                                            su.TenKhoa,
                                            su.Nhom.ToString(),
                                            su.SoLuongDK.ToString(),
                                            su.IsIgnored ? "checked" : "",
                                        }
                                    );
                    }
                }
                else
                {
                    Result.Add(new string[] {
                                            su.MaMonHoc,
                                            su.TenMonHoc,
                                            su.TenBoMon,
                                            su.TenKhoa,
                                            su.Nhom.ToString(),
                                            su.SoLuongDK.ToString(),
                                            su.IsIgnored ? "checked" : "",
                                        }
                                );
                }

            }

            return Json(new
                            {
                                sEcho = param.sEcho,
                                iTotalRecords = Result.Count(),
                                iTotalDisplayRecords = Result.Count(),
                                //iTotalDisplayedRecords = Subjects.Count(),
                                aaData = Result.Skip(param.iDisplayStart).Take(param.iDisplayLength)
                            },
                            JsonRequestBehavior.AllowGet
                        );
        }
Пример #9
0
        public void VNetTest()
        {
            StartTest(MethodBase.GetCurrentMethod().Name, testStartTime);

            string newAzureQuickVMName = Utilities.GetUniqueShortName(vmNamePrefix);
            if (string.IsNullOrEmpty(imageName))
                imageName = vmPowershellCmdlets.GetAzureVMImageName(new[] { "Windows" }, false);

            // Read the vnetconfig file and get the names of local networks, virtual networks and affinity groups.
            XDocument vnetconfigxml = XDocument.Load(vnetConfigFilePath);
            List<string> localNets = new List<string>();
            List<string> virtualNets = new List<string>();
            HashSet<string> affinityGroups = new HashSet<string>();
            Dictionary<string,string> dns = new Dictionary<string,string>();
            List<LocalNetworkSite> localNetworkSites = new List<LocalNetworkSite>();
            AddressPrefixList prefixlist = null;

            foreach (XElement el in vnetconfigxml.Descendants())
            {
                switch (el.Name.LocalName)
                {
                    case "LocalNetworkSite":
                        {
                            localNets.Add(el.FirstAttribute.Value);
                            List<XElement> elements = el.Elements().ToList<XElement>();
                            prefixlist = new AddressPrefixList();
                            prefixlist.Add(elements[0].Elements().First().Value);
                            localNetworkSites.Add(new LocalNetworkSite()
                                {
                                    VpnGatewayAddress = elements[1].Value,
                                    AddressSpace = new AddressSpace() { AddressPrefixes = prefixlist }
                                }
                            );
                        }
                        break;
                    case "VirtualNetworkSite":
                        virtualNets.Add(el.Attribute("name").Value);
                        affinityGroups.Add(el.Attribute("AffinityGroup").Value);
                        break;
                    case "DnsServer":
                        {
                            dns.Add(el.Attribute("name").Value, el.Attribute("IPAddress").Value);
                            break;
                        }
                    default:
                        break;
                }
            }

            foreach (string aff in affinityGroups)
            {
                if (Utilities.CheckRemove(vmPowershellCmdlets.GetAzureAffinityGroup, aff))
                {

                    vmPowershellCmdlets.NewAzureAffinityGroup(aff, locationName, null, null);
                }
            }

            string vnet1 = virtualNets[0];
            string lnet1 = localNets[0];

            try
            {
                vmPowershellCmdlets.NewAzureQuickVM(OS.Windows, newAzureQuickVMName, serviceName, imageName, username, password, locationName); // New-AzureQuickVM
                Console.WriteLine("VM is created successfully: -Name {0} -ServiceName {1}", newAzureQuickVMName, serviceName);

                vmPowershellCmdlets.SetAzureVNetConfig(vnetConfigFilePath);

                foreach (VirtualNetworkSiteContext site in vmPowershellCmdlets.GetAzureVNetSite(null))
                {
                    Console.WriteLine("Name: {0}, AffinityGroup: {1}", site.Name, site.AffinityGroup);
                }

                foreach (string vnet in virtualNets)
                {
                    VirtualNetworkSiteContext vnetsite = vmPowershellCmdlets.GetAzureVNetSite(vnet)[0];
                    Assert.AreEqual(vnet, vnetsite.Name);
                    //Verify DNS and IPAddress
                    Assert.AreEqual(1, vnetsite.DnsServers.Count());
                    Assert.IsTrue(dns.ContainsKey(vnetsite.DnsServers.First().Name));
                    Assert.AreEqual(dns[vnetsite.DnsServers.First().Name], vnetsite.DnsServers.First().Address);

                    //Verify the Gateway sites
                    Assert.AreEqual(1,vnetsite.GatewaySites.Count);
                    Assert.AreEqual(localNetworkSites[0].VpnGatewayAddress, vnetsite.GatewaySites[0].VpnGatewayAddress);
                    Assert.IsTrue(localNetworkSites[0].AddressSpace.AddressPrefixes.All(c => vnetsite.GatewaySites[0].AddressSpace.AddressPrefixes.Contains(c)));

                    Assert.AreEqual(ProvisioningState.NotProvisioned, vmPowershellCmdlets.GetAzureVNetGateway(vnet)[0].State);
                }

                vmPowershellCmdlets.NewAzureVNetGateway(vnet1);

                Assert.IsTrue(GetVNetState(vnet1, ProvisioningState.Provisioned, 12, 60));

                // Set-AzureVNetGateway -Connect Test
                vmPowershellCmdlets.SetAzureVNetGateway("connect", vnet1, lnet1);

                foreach (GatewayConnectionContext connection in vmPowershellCmdlets.GetAzureVNetConnection(vnet1))
                {
                    Console.WriteLine("Connectivity: {0}, LocalNetwork: {1}", connection.ConnectivityState, connection.LocalNetworkSiteName);
                    Assert.IsFalse(connection.ConnectivityState.ToLowerInvariant().Contains("notconnected"));
                }

                // Get-AzureVNetGatewayKey
                SharedKeyContext result = vmPowershellCmdlets.GetAzureVNetGatewayKey(vnet1,
                    vmPowershellCmdlets.GetAzureVNetConnection(vnet1)[0].LocalNetworkSiteName);
                Console.WriteLine("Gateway Key: {0}", result.Value);


                // Set-AzureVNetGateway -Disconnect
                vmPowershellCmdlets.SetAzureVNetGateway("disconnect", vnet1, lnet1);

                foreach (GatewayConnectionContext connection in vmPowershellCmdlets.GetAzureVNetConnection(vnet1))
                {
                    Console.WriteLine("Connectivity: {0}, LocalNetwork: {1}", connection.ConnectivityState, connection.LocalNetworkSiteName);
                }

                // Remove-AzureVnetGateway
                vmPowershellCmdlets.RemoveAzureVNetGateway(vnet1);

                foreach (string vnet in virtualNets)
                {
                    VirtualNetworkGatewayContext gateway = vmPowershellCmdlets.GetAzureVNetGateway(vnet)[0];

                    Console.WriteLine("State: {0}, VIP: {1}", gateway.State.ToString(), gateway.VIPAddress);
                    if (vnet.Equals(vnet1))
                    {
                        if (gateway.State != ProvisioningState.Deprovisioning &&
                            gateway.State != ProvisioningState.NotProvisioned)
                        {
                            Assert.Fail("The state of the gateway is neither Deprovisioning nor NotProvisioned!");
                        }
                    }
                    else
                    {
                        Assert.AreEqual(ProvisioningState.NotProvisioned, gateway.State);
                    }

                }

                //Utilities.RetryFunctionUntilSuccess<ManagementOperationContext>(vmPowershellCmdlets.RemoveAzureVNetConfig, "in use", 10, 30);
                Utilities.RetryActionUntilSuccess(() => vmPowershellCmdlets.RemoveAzureVNetConfig(), "in use", 10, 30);

                pass = true;

            }
            catch (Exception e)
            {
                pass = false;
                if (cleanupIfFailed)
                {
                    try
                    {
                        vmPowershellCmdlets.RemoveAzureVNetGateway(vnet1);
                    }
                    catch { }
                    Utilities.RetryActionUntilSuccess(() => vmPowershellCmdlets.RemoveAzureVNetConfig(), "in use", 10, 30);
                    //Utilities.RetryFunctionUntilSuccess<ManagementOperationContext>(vmPowershellCmdlets.RemoveAzureVNetConfig, "in use", 10, 30);
                }
                Assert.Fail("Exception occurred: {0}", e.ToString());
            }
            finally
            {
                foreach (string aff in affinityGroups)
                {
                    try
                    {
                        vmPowershellCmdlets.RemoveAzureAffinityGroup(aff);
                    }
                    catch
                    {
                        // Some service uses the affinity group, so it cannot be deleted.  Just leave it.
                    }
                }
            }
        }
        public static void Generate(SupermarketChainContext context, DateTime startDate, DateTime endDate)
        {
            var saleReports = context.SaleReports
                .Where(sl => sl.SaleTime >= startDate && sl.SaleTime <= endDate)
                .Select(sl => new
                {
                    Productname = sl.Product.ProductName,
                    Quantity = sl.Quantity,
                    UnitPrice = sl.Product.Price,
                    Location = sl.Product.Vendor.VendorName,
                    SaleDate = sl.SaleTime
                });

            var groupedByDate = new Dictionary<DateTime, HashSet<SaleReportInfo>>();

            foreach (var i in saleReports)
            {
                if (groupedByDate.ContainsKey(i.SaleDate))
                {
                    groupedByDate[i.SaleDate].Add(new SaleReportInfo(i.Productname, i.Quantity, i.UnitPrice, i.Location));
                }
                else
                {
                    var saleReportsHashSet = new HashSet<SaleReportInfo>()
                    {
                        new SaleReportInfo(i.Productname, i.Quantity, i.UnitPrice, i.Location)
                    };
                    groupedByDate.Add(i.SaleDate, saleReportsHashSet);
                }
            }

            Document doc = new Document(iTextSharp.text.PageSize.LETTER, 35, 35, 70, 60);
            PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream("../../../SaleReports.pdf", FileMode.Create));

            doc.Open();

            PdfPTable table = new PdfPTable(5);
            float[] widths = new float[] { 100f, 100f, 100f, 100f, 100f };
            table.WidthPercentage = 100;

            PdfPCell header = new PdfPCell(new Phrase("Aggregated Sales Report"));
            header.Colspan = 5;
            header.HorizontalAlignment = 1;
            table.AddCell(header);

            foreach (var sl in groupedByDate)
            {
                var date = new PdfPCell(new Phrase(String.Format("{0:dd-MMM-yyyy}", sl.Key)));
                date.Colspan = 5;
                date.BackgroundColor = BaseColor.LIGHT_GRAY;
                table.AddCell(date);

                PdfPCell h1 = new PdfPCell(new Phrase("Product"));
                h1.BackgroundColor = BaseColor.GRAY;
                table.AddCell(h1);

                h1 = new PdfPCell(new Phrase("Quantity"));
                h1.BackgroundColor = BaseColor.GRAY;
                table.AddCell(h1);

                h1 = new PdfPCell(new Phrase("Unit Price"));
                h1.BackgroundColor = BaseColor.GRAY;
                table.AddCell(h1);

                h1 = new PdfPCell(new Phrase("Location"));
                h1.BackgroundColor = BaseColor.GRAY;
                table.AddCell(h1);

                h1 = new PdfPCell(new Phrase("Sum"));
                h1.BackgroundColor = BaseColor.GRAY;
                table.AddCell(h1);

                foreach (var s in sl.Value)
                {
                    table.AddCell(s.ProductName);
                    table.AddCell(s.Quantity.ToString());
                    table.AddCell(s.UnitPrice.ToString());
                    table.AddCell(s.Location);
                    table.AddCell(s.Sum.ToString());
                }

                var msg = new PdfPCell(new Phrase(string.Format("Total sum for {0}: ", String.Format("{0:dd-MMM-yyyy}", sl.Key))));
                msg.HorizontalAlignment = 2;
                msg.Colspan = 4;
                table.AddCell(msg);

                var totalSum = sl.Value.Sum(slr => slr.Sum);

                var totalSumCell = new PdfPCell(new Phrase(totalSum.ToString()));
                table.AddCell(totalSumCell);
            }

            doc.Add(table);
            doc.Close();
        }
Пример #11
0
        /// <summary>
        /// Asks each AILogic for it's vote of color for the next move and chooses the highest vote
        /// </summary>
        private void QueryMultipleLogics()
        {
            Controller controller = GetController();
            Dictionary<Color, int> colorVote = new Dictionary<Color, int>();
            foreach (AILogicWeight logic in _logics)
            {
                SuggestedMoves colorsChosen = logic.Logic.ChooseColor(controller.GetUpdate()); //reaches across other thread to get the current Board

                if (colorsChosen.BestMoves.Any()) //if there are any moves returned
                {
                    Color color = colorsChosen.BestMoves.First();
                    if (!colorVote.ContainsKey(color))
                    {
                        colorVote.Add(color, 0);
                    }
                    colorVote[color] += logic.Weight;
                }
            }

            if (colorVote.Count > 0)
            {
                Color highestVote = colorVote.OrderByDescending(keyValuePair => keyValuePair.Value).First().Key;
                Console.WriteLine(highestVote);
                controller.PickColor(highestVote);
            }
            else
            {
                Console.WriteLine("No colors were suggested!");
            }
        }
Пример #12
0
        public Dictionary<string, int> GetNextWords(List<Verse> verses, string text, bool at_word_start, bool with_diacritics)
        {
            Dictionary<string, int> result = new Dictionary<string, int>();
            if (verses != null)
            {
                if (!String.IsNullOrEmpty(text))
                {
                    text = text.Trim();
                    while (text.Contains("  "))
                    {
                        text = text.Replace("  ", " ");
                    }
                    while (text.Contains("+"))
                    {
                        text = text.Replace("+", "");
                    }
                    while (text.Contains("-"))
                    {
                        text = text.Replace("-", "");
                    }

                    if ((this.Title.Contains("Original")) && (!with_diacritics))
                    {
                        text = text.Simplify29();
                    }

                    string[] text_words = text.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                    if (text_words.Length > 0)
                    {
                        foreach (Verse verse in verses)
                        {
                            string verse_text = verse.Text;
                            if ((this.Title.Contains("Original")) && (!with_diacritics))
                            {
                                verse_text = verse_text.Simplify29();
                            }

                            verse_text = verse_text.Trim();
                            while (verse_text.Contains("  "))
                            {
                                verse_text = verse_text.Replace("  ", " ");
                            }
                            string[] verse_words = verse_text.Split();

                            if (verse_words.Length == verse_words.Length)
                            {
                                for (int i = 0; i < verse_words.Length; i++)
                                {
                                    bool start_of_text_words_found = false;
                                    if (at_word_start)
                                    {
                                        start_of_text_words_found = verse_words[i].Equals(text_words[0]);
                                    }
                                    else
                                    {
                                        start_of_text_words_found = verse_words[i].EndsWith(text_words[0]);
                                    }

                                    if (start_of_text_words_found)
                                    {
                                        if (verse_words.Length >= (i + text_words.Length))
                                        {
                                            // check rest of text_words if matching
                                            bool is_text_matched = true;
                                            for (int j = 1; j < text_words.Length; j++)
                                            {
                                                if (verse_words[j + i] != text_words[j])
                                                {
                                                    is_text_matched = false;
                                                    break;
                                                }
                                            }

                                            if (is_text_matched)
                                            {
                                                // skip text_words
                                                i += text_words.Length;

                                                // add next word to result (if not added already)
                                                if (i < verse_words.Length)
                                                {
                                                    string matching_word = verse_words[i];
                                                    if (!result.ContainsKey(matching_word))
                                                    {
                                                        result.Add(matching_word, 1);
                                                    }
                                                    else
                                                    {
                                                        result[matching_word]++;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return result;
        }
        /// <summary>
        /// GetRetByDept
        /// </summary>
        /// <param name="RetID">Retrieval ID</param>
        /// <returns></returns>
        public List<ReqAllocation> getRetByDept(string RetID)
        {
            int retID = Convert.ToInt32(RetID);
            List<ReqAllocation> reqAllocationList = new List<ReqAllocation>();

            //hashmap-like to store itemID and collated qty
            Dictionary<string, int> itemQtyENGL = new Dictionary<string, int>();
            Dictionary<string, int> itemQtyCPSC = new Dictionary<string, int>();
            Dictionary<string, int> itemQtyCOMM = new Dictionary<string, int>();
            Dictionary<string, int> itemQtyREGR = new Dictionary<string, int>();
            Dictionary<string, int> itemQtyZOOL = new Dictionary<string, int>();

            //obtain list of requisition with specified RetID
            List<Requisition> reqList = ctx.Requisition.Where(x => x.RetID == retID).ToList();

            foreach(Requisition req in reqList)
            {
                //obtain list of requisition detail with ReqID
                List<RequisitionDetail> reqDetailList = ctx.RequisitionDetail.Where(x => x.ReqID == req.ReqID).ToList();

                foreach(RequisitionDetail reqDetail in reqDetailList)
                {
                    if (req.DeptID == "ENGL")
                    {
                        //if itemQty does not contain the item, add item to itemQty
                        if (!itemQtyENGL.ContainsKey(reqDetail.ItemID))
                        {
                            itemQtyENGL.Add(reqDetail.ItemID, (int)reqDetail.IssueQty);
                        }
                        //else if itemQty contains item, add the qty to existing qty
                        else
                        {
                            itemQtyENGL["reqDetail.ItemID"] += (int)reqDetail.IssueQty;
                        }
                    }

                    if (req.DeptID == "CPSC")
                    {
                        //if itemQty does not contain the item, add item to itemQty
                        if (!itemQtyCPSC.ContainsKey(reqDetail.ItemID))
                        {
                            itemQtyCPSC.Add(reqDetail.ItemID, (int)reqDetail.IssueQty);
                        }
                        //else if itemQty contains item, add the qty to existing qty
                        else
                        {
                            itemQtyCPSC["reqDetail.ItemID"] += (int)reqDetail.IssueQty;
                        }
                    }

                    if (req.DeptID == "COMM")
                    {
                        //if itemQty does not contain the item, add item to itemQty
                        if (!itemQtyCOMM.ContainsKey(reqDetail.ItemID))
                        {
                            itemQtyCOMM.Add(reqDetail.ItemID, (int)reqDetail.IssueQty);
                        }
                        //else if itemQty contains item, add the qty to existing qty
                        else
                        {
                            itemQtyCOMM["reqDetail.ItemID"] += (int)reqDetail.IssueQty;
                        }
                    }

                    if (req.DeptID == "REGR")
                    {
                        //if itemQty does not contain the item, add item to itemQty
                        if (!itemQtyREGR.ContainsKey(reqDetail.ItemID))
                        {
                            itemQtyREGR.Add(reqDetail.ItemID, (int)reqDetail.IssueQty);
                        }
                        //else if itemQty contains item, add the qty to existing qty
                        else
                        {
                            itemQtyREGR["reqDetail.ItemID"] += (int)reqDetail.IssueQty;
                        }
                    }

                    if (req.DeptID == "ZOOL")
                    {
                        //if itemQty does not contain the item, add item to itemQty
                        if (!itemQtyZOOL.ContainsKey(reqDetail.ItemID))
                        {
                            itemQtyZOOL.Add(reqDetail.ItemID, (int)reqDetail.IssueQty);
                        }
                        //else if itemQty contains item, add the qty to existing qty
                        else
                        {
                            itemQtyZOOL["reqDetail.ItemID"] += (int)reqDetail.IssueQty;
                        }
                    }

                }
            }

            //extract all keys and values in itemQty
            string[] itemQtyENGLKeys = itemQtyENGL.Keys.ToArray();
            int[] itemQtyENGLValues = itemQtyENGL.Values.ToArray();

            string[] itemQtyCPSCKeys = itemQtyCPSC.Keys.ToArray();
            int[] itemQtyCPSCValues = itemQtyCPSC.Values.ToArray();

            string[] itemQtyCOMMKeys = itemQtyCOMM.Keys.ToArray();
            int[] itemQtyCOMMValues = itemQtyCOMM.Values.ToArray();

            string[] itemQtyREGRKeys = itemQtyREGR.Keys.ToArray();
            int[] itemQtyREGRValues = itemQtyREGR.Values.ToArray();

            string[] itemQtyZOOLKeys = itemQtyZOOL.Keys.ToArray();
            int[] itemQtyZOOLValues = itemQtyZOOL.Values.ToArray();

            //create and add ReqAllocation for ENGL Dept
            for (int i = 0; i < itemQtyENGL.Count; i++)
            {
                ReqAllocation reqAllocation = new ReqAllocation();
                reqAllocation.ItemID = itemQtyENGLKeys[i];
                reqAllocation.RequestQty = itemQtyENGLValues[i];
                reqAllocation.Dept = "ENGL";
                reqAllocationList.Add(reqAllocation);
            }

            //create and add ReqAllocation for CPSC Dept
            for (int i = 0; i < itemQtyCPSC.Count; i++)
            {
                //create and add new ReqAllocation
                ReqAllocation reqAllocation = new ReqAllocation();
                reqAllocation.ItemID = itemQtyCPSCKeys[i];
                reqAllocation.RequestQty = itemQtyCPSCValues[i];
                reqAllocation.Dept = "CPSC";
                reqAllocationList.Add(reqAllocation);
            }

            //create and add ReqAllocation for COMM Dept
            for (int i = 0; i < itemQtyCOMM.Count; i++)
            {
                //create and add new ReqAllocation
                ReqAllocation reqAllocation = new ReqAllocation();
                reqAllocation.ItemID = itemQtyCOMMKeys[i];
                reqAllocation.RequestQty = itemQtyCOMMValues[i];
                reqAllocation.Dept = "COMM";
                reqAllocationList.Add(reqAllocation);
            }

            //create and add ReqAllocation for REGR Dept
            for (int i = 0; i < itemQtyREGR.Count; i++)
            {
                //create and add new ReqAllocation
                ReqAllocation reqAllocation = new ReqAllocation();
                reqAllocation.ItemID = itemQtyREGRKeys[i];
                reqAllocation.RequestQty = itemQtyREGRValues[i];
                reqAllocation.Dept = "REGR";
                reqAllocationList.Add(reqAllocation);
            }

            //create and add ReqAllocation for ZOOL Dept
            for (int i = 0; i < itemQtyZOOL.Count; i++)
            {
                //create and add new ReqAllocation
                ReqAllocation reqAllocation = new ReqAllocation();
                reqAllocation.ItemID = itemQtyZOOLKeys[i];
                reqAllocation.RequestQty = itemQtyZOOLValues[i];
                reqAllocation.Dept = "ZOOL";
                reqAllocationList.Add(reqAllocation);
            }

            return reqAllocationList;
        }
 /// <summary>
 /// 根据输入的字段自动添加修改日志
 /// </summary>
 /// <param name="_classID"></param>
 /// <param name="_itemID"></param>
 /// <param name="_itemName"></param>
 /// <param name="_itemPrice"></param>
 /// <param name="_itemDiscount"></param>
 /// <param name="_itemExtraNote"></param>
 /// <param name="_itemCount"></param>
 private void DictionaryAdd(Dictionary<string, Model.Item> _dictionary, string _classID, string _itemID, string _itemName, string _itemPrice, string _itemDiscount, string _itemExtraNote, string _itemCount )
 {
     if (_dictionary.ContainsKey(_itemName))
     {
         try
         {
             _dictionary[_itemName].ItemPrice = decimal.Parse(_itemPrice);
             _dictionary[_itemName].ItemDiscount = int.Parse(_itemDiscount);
             _dictionary[_itemName].ItemExtraNote = _itemExtraNote;
             _dictionary[_itemName].ItemCount = int.Parse(_itemCount);
         }
         catch (FormatException)
         {
             MessageBox.Show("输入的数值不正确");
         }
     }
     else
     {
         _dictionary.Add(_itemName, new Item(_classID, _itemID, _itemName, decimal.Parse(_itemPrice), int.Parse(_itemDiscount), _itemExtraNote, int.Parse(_itemCount)));
     }
 }
        /// <summary>
        /// Verify a deployment exists
        /// </summary>
        private void VerifyDeployment()
        {
            try
            {
                SafeWriteObjectWithTimestamp(Resources.PublishStartingMessage);
                SafeWriteObjectWithTimestamp(Resources.PublishInitializingMessage);

                Dictionary<string, RoleInstance> roleInstanceSnapshot = new Dictionary<string, RoleInstance>();

                // Continue polling for deployment until all of the roles
                // indicate they're ready
                Deployment deployment = new Deployment();
                do
                {
                    deployment = RetryCall<Deployment>(subscription =>
                        Channel.GetDeploymentBySlot(
                            subscription,
                            _hostedServiceName,
                            _deploymentSettings.ServiceSettings.Slot));

                    // The goal of this loop is to output a message whenever the status of a role
                    // instance CHANGES. To do that, we have to remember the last status of all role instances
                    // and that's what the roleInstanceSnapshot array is for
                    foreach (RoleInstance currentInstance in deployment.RoleInstanceList)
                    {
                        // We only care about these three statuses, ignore other intermediate statuses
                        if (String.Equals(currentInstance.InstanceStatus, RoleInstanceStatus.Busy) ||
                            String.Equals(currentInstance.InstanceStatus, RoleInstanceStatus.Ready) ||
                            String.Equals(currentInstance.InstanceStatus, RoleInstanceStatus.Initializing))
                        {
                            bool createdOrChanged = false;

                            // InstanceName is unique and concatenates the role name and instance name
                            if (roleInstanceSnapshot.ContainsKey(currentInstance.InstanceName))
                            {
                                // If we already have a snapshot of that role instance, update it
                                RoleInstance previousInstance = roleInstanceSnapshot[currentInstance.InstanceName];
                                if (!String.Equals(previousInstance.InstanceStatus, currentInstance.InstanceStatus))
                                {
                                    // If the instance status changed, we need to output a message
                                    previousInstance.InstanceStatus = currentInstance.InstanceStatus;
                                    createdOrChanged = true;
                                }
                            }
                            else
                            {
                                // If this is the first time we run through, we also need to output a message
                                roleInstanceSnapshot[currentInstance.InstanceName] = currentInstance;
                                createdOrChanged = true;
                            }

                            if (createdOrChanged)
                            {
                                string statusResource;
                                switch (currentInstance.InstanceStatus)
                                {
                                    case RoleInstanceStatus.Busy:
                                        statusResource = Resources.PublishInstanceStatusBusy;
                                        break;

                                    case RoleInstanceStatus.Ready:
                                        statusResource = Resources.PublishInstanceStatusReady;
                                        break;

                                    default:
                                        statusResource = Resources.PublishInstanceStatusCreating;
                                        break;
                                }

                                SafeWriteObjectWithTimestamp(String.Format(Resources.PublishInstanceStatusMessage,
                                    currentInstance.InstanceName, currentInstance.RoleName, statusResource));

                            }
                        }
                    }

                    // If a deployment has many roles to initialize, this
                    // thread must throttle requests so the Azure portal
                    // doesn't reply with a "too many requests" error
                    Thread.Sleep(int.Parse(Resources.StandardRetryDelayInMs));
                }
                while (deployment.RoleInstanceList.Any(
                    r => r.InstanceStatus != RoleInstanceStatus.Ready));

                if (CanGenerateUrlForDeploymentSlot())
                {
                    SafeWriteObjectWithTimestamp(
                        Resources.PublishCreatedWebsiteMessage,
                        string.Format(Resources.ServiceUrl, _hostedServiceName));
                }
                else
                {
                    SafeWriteObjectWithTimestamp(
                        Resources.PublishCreatedWebsiteLaunchNotSupportedMessage);
                }

            }
            catch (EndpointNotFoundException)
            {
                throw new InvalidOperationException(
                    string.Format(
                        Resources.CannotFindDeployment,
                        _hostedServiceName,
                        _deploymentSettings.ServiceSettings.Slot));
            }
        }
Пример #16
0
		public void ContainsKey2()
		{
			var arr = new Dictionary<int,int>
			{
				{ 1, 1 },
				{ 2, 2 },
			};

			ForEachProvider(db => AreEqual(
				from p in    Parent where arr.ContainsKey(p.ParentID) select p,
				from p in db.Parent where arr.ContainsKey(p.ParentID) select p));
		}
Пример #17
0
        /// <summary>
        /// 根据给定的命令描述对象返回转化得到的信息字符串
        /// </summary>
        /// <param name="infoItems"></param>
        /// <returns></returns>
        public string ToInfoString(IEnumerable<DataItem> infoItems)
        {
            if (infoItems == null)
            {
                return "<InfoItems></InfoItems>";
            }
            var infoValueDic = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
            foreach (var item in infoItems.Where(a => a != null && a.Key != null))
            {
                if (!infoValueDic.ContainsKey(item.Key))
                {
                    infoValueDic.Add(item.Key, item.Value);
                }
            }

            return XmlSerializer.SerializeToString(infoValueDic);
        }
Пример #18
0
        // get words
        public Dictionary<string, int> GetWordsWith(List<Verse> verses, string text, bool at_word_start, bool with_diacritics)
        {
            Dictionary<string, int> result = new Dictionary<string, int>();
            if (verses != null)
            {
                if (!String.IsNullOrEmpty(text))
                {
                    text = text.Trim();
                    if (!text.Contains(" "))
                    {
                        if ((this.Title.Contains("Original")) && (!with_diacritics))
                        {
                            text = text.Simplify29();
                        }

                        foreach (Verse verse in verses)
                        {
                            string verse_text = verse.Text;
                            if ((this.Title.Contains("Original")) && (!with_diacritics))
                            {
                                verse_text = verse_text.Simplify29();
                            }

                            verse_text = verse_text.Trim();
                            while (verse_text.Contains("  "))
                            {
                                verse_text = verse_text.Replace("  ", " ");
                            }
                            string[] verse_words = verse_text.Split();

                            if (verse_words.Length == verse_words.Length)
                            {
                                for (int i = 0; i < verse_words.Length; i++)
                                {
                                    if (at_word_start)
                                    {
                                        if (verse_words[i].StartsWith(text))
                                        {
                                            if (!result.ContainsKey(verse_words[i]))
                                            {
                                                result.Add(verse_words[i], 1);
                                            }
                                            else
                                            {
                                                result[verse_words[i]]++;
                                            }
                                        }
                                    }
                                    else
                                    {
                                        if (verse_words[i].Contains(text))
                                        {
                                            if (!result.ContainsKey(verse_words[i]))
                                            {
                                                result.Add(verse_words[i], 1);
                                            }
                                            else
                                            {
                                                result[verse_words[i]]++;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return result;
        }
Пример #19
0
        private void UpdateNumbersAndDistances(SelectionScope scope)
        {
            ////////////////////////////////////////////////////////////////////////////////////
            // update numbers
            ////////////////////////////////////////////////////////////////////////////////////
            int chapter_number = 1;
            int verse_number = 1;
            int word_number = 1;
            int letter_number = 1;
            if (this.chapters != null)
            {
                // update verse/word/letter numbers
                foreach (Chapter chapter in this.chapters)
                {
                    chapter.Number = chapter_number++;

                    int verse_number_in_chapter = 1;
                    int word_number_in_chapter = 1;
                    int letter_number_in_chapter = 1;
                    foreach (Verse verse in chapter.Verses)
                    {
                        verse.Number = verse_number++;
                        verse.NumberInChapter = verse_number_in_chapter++;

                        int word_number_in_verse = 1;
                        int letter_number_in_verse = 1;
                        foreach (Word word in verse.Words)
                        {
                            word.Number = word_number++;
                            word.NumberInChapter = word_number_in_chapter++;
                            word.NumberInVerse = word_number_in_verse++;

                            int letter_number_in_word = 1;
                            foreach (Letter letter in word.Letters)
                            {
                                letter.Number = letter_number++;
                                letter.NumberInChapter = letter_number_in_chapter++;
                                letter.NumberInVerse = letter_number_in_verse++;
                                letter.NumberInWord = letter_number_in_word++;
                            }
                        }
                    }
                }
            }
            ////////////////////////////////////////////////////////////////////////////////////

            ////////////////////////////////////////////////////////////////////////////////////
            // update positions and distances
            ////////////////////////////////////////////////////////////////////////////////////
            // foreach chapter: no repeated chapters so no distances to previous same chapter

            // foreach verse: calculate distance to its previous occurrence
            Dictionary<string, int> verse_previous_verse_numbers = new Dictionary<string, int>();
            Dictionary<string, int> verse_previous_chapter_numbers = new Dictionary<string, int>();

            // foreach word: calculate distance to its previous occurrence
            Dictionary<string, int> word_previous_word_numbers = new Dictionary<string, int>();
            Dictionary<string, int> word_previous_verse_numbers = new Dictionary<string, int>();
            Dictionary<string, int> word_previous_chapter_numbers = new Dictionary<string, int>();

            // foreach letter: calculate distance to its previous occurrence
            Dictionary<char, int> letter_previous_letter_numbers = new Dictionary<char, int>();
            Dictionary<char, int> letter_previous_word_numbers = new Dictionary<char, int>();
            Dictionary<char, int> letter_previous_verse_numbers = new Dictionary<char, int>();
            Dictionary<char, int> letter_previous_chapter_numbers = new Dictionary<char, int>();

            if (this.chapters != null)
            {
                foreach (Chapter chapter in this.chapters)
                {
                    if (scope == SelectionScope.Chapter)
                    {
                        // there are no repeated chapters so there is no chapter_previous_chapter_numbers to clear

                        verse_previous_verse_numbers.Clear();
                        verse_previous_chapter_numbers.Clear();

                        word_previous_word_numbers.Clear();
                        word_previous_verse_numbers.Clear();
                        word_previous_chapter_numbers.Clear();

                        letter_previous_letter_numbers.Clear();
                        letter_previous_word_numbers.Clear();
                        letter_previous_verse_numbers.Clear();
                        letter_previous_chapter_numbers.Clear();
                    }

                    foreach (Verse verse in chapter.Verses)
                    {
                        string verse_text = verse.Text;
                        if (!verse_previous_verse_numbers.ContainsKey(verse_text))
                        {
                            verse.DistanceToPrevious.dL = -1; // non-applicable
                            verse.DistanceToPrevious.dW = -1; // non-applicable
                            verse.DistanceToPrevious.dV = 0;
                            verse.DistanceToPrevious.dC = 0;

                            verse_previous_verse_numbers.Add(verse_text, verse.Number);
                            verse_previous_chapter_numbers.Add(verse_text, verse.Chapter.Number);
                        }
                        else
                        {
                            verse.DistanceToPrevious.dL = -1; // non-applicable
                            verse.DistanceToPrevious.dW = -1; // non-applicable
                            verse.DistanceToPrevious.dV = verse.Number - verse_previous_verse_numbers[verse_text];
                            verse.DistanceToPrevious.dC = verse.Chapter.Number - verse_previous_chapter_numbers[verse_text];

                            // save latest chapter and verse numbers for next iteration
                            verse_previous_verse_numbers[verse_text] = verse.Number;
                            verse_previous_chapter_numbers[verse_text] = verse.Chapter.Number;
                        }

                        foreach (Word word in verse.Words)
                        {
                            string word_text = word.Text;
                            if (!word_previous_verse_numbers.ContainsKey(word_text))
                            {
                                word.DistanceToPrevious.dL = -1; // non-applicable
                                word.DistanceToPrevious.dW = 0;
                                word.DistanceToPrevious.dV = 0;
                                word.DistanceToPrevious.dC = 0;

                                word_previous_word_numbers.Add(word_text, word.Number);
                                word_previous_verse_numbers.Add(word_text, word.Verse.Number);
                                word_previous_chapter_numbers.Add(word_text, word.Verse.Chapter.Number);
                            }
                            else
                            {
                                word.DistanceToPrevious.dL = -1; // non-applicable
                                word.DistanceToPrevious.dW = word.Number - word_previous_word_numbers[word_text];
                                word.DistanceToPrevious.dV = word.Verse.Number - word_previous_verse_numbers[word_text];
                                word.DistanceToPrevious.dC = word.Verse.Chapter.Number - word_previous_chapter_numbers[word_text];

                                // save latest chapter, verse and word numbers for next iteration
                                word_previous_word_numbers[word_text] = word.Number;
                                word_previous_verse_numbers[word_text] = word.Verse.Number;
                                word_previous_chapter_numbers[word_text] = word.Verse.Chapter.Number;
                            }

                            foreach (Letter letter in word.Letters)
                            {
                                if (!letter_previous_verse_numbers.ContainsKey(letter.Character))
                                {
                                    letter.DistanceToPrevious.dL = 0;
                                    letter.DistanceToPrevious.dW = 0;
                                    letter.DistanceToPrevious.dV = 0;
                                    letter.DistanceToPrevious.dC = 0;

                                    letter_previous_letter_numbers.Add(letter.Character, letter.Number);
                                    letter_previous_word_numbers.Add(letter.Character, letter.Word.Number);
                                    letter_previous_verse_numbers.Add(letter.Character, letter.Word.Verse.Number);
                                    letter_previous_chapter_numbers.Add(letter.Character, letter.Word.Verse.Chapter.Number);
                                }
                                else
                                {
                                    letter.DistanceToPrevious.dL = letter.Number - letter_previous_letter_numbers[letter.Character];
                                    letter.DistanceToPrevious.dW = letter.Word.Number - letter_previous_word_numbers[letter.Character];
                                    letter.DistanceToPrevious.dV = letter.Word.Verse.Number - letter_previous_verse_numbers[letter.Character];
                                    letter.DistanceToPrevious.dC = letter.Word.Verse.Chapter.Number - letter_previous_chapter_numbers[letter.Character];

                                    // save latest chapter, verse, word and letter numbers for next iteration
                                    letter_previous_letter_numbers[letter.Character] = letter.Number;
                                    letter_previous_word_numbers[letter.Character] = letter.Word.Number;
                                    letter_previous_verse_numbers[letter.Character] = letter.Word.Verse.Number;
                                    letter_previous_chapter_numbers[letter.Character] = letter.Word.Verse.Chapter.Number;
                                }
                            }
                        }
                    }
                }
            }
            ////////////////////////////////////////////////////////////////////////////////////
        }
Пример #20
0
        private void VerifyDeployment(PublishContext context)
        {
            try
            {
                WriteVerboseWithTimestamp(Resources.PublishInitializingMessage);

                var roleInstanceSnapshot = new Dictionary<string, RoleInstance>();

                // Continue polling for deployment until all of the roles
                // indicate they're ready
                Deployment deployment;
                do
                {
                    deployment = new Deployment(
                        ComputeClient.Deployments.GetBySlot(context.ServiceName, GetSlot(context.ServiceSettings.Slot)));

                    // The goal of this loop is to output a message whenever the status of a role 
                    // instance CHANGES. To do that, we have to remember the last status of all role instances
                    // and that's what the roleInstanceSnapshot array is for
                    foreach (RoleInstance currentInstance in deployment.RoleInstanceList)
                    {
                        // We only care about these three statuses, ignore other intermediate statuses
                        if (string.Equals(currentInstance.InstanceStatus, RoleInstanceStatus.BusyRole) ||
                            string.Equals(currentInstance.InstanceStatus, RoleInstanceStatus.ReadyRole) ||
                            string.Equals(currentInstance.InstanceStatus, RoleInstanceStatus.CreatingRole))
                        {
                            bool createdOrChanged = false;

                            // InstanceName is unique and concatenates the role name and instance name
                            if (roleInstanceSnapshot.ContainsKey(currentInstance.InstanceName))
                            {
                                // If we already have a snapshot of that role instance, update it
                                RoleInstance previousInstance = roleInstanceSnapshot[currentInstance.InstanceName];
                                if (!string.Equals(previousInstance.InstanceStatus, currentInstance.InstanceStatus))
                                {
                                    // If the instance status changed, we need to output a message
                                    previousInstance.InstanceStatus = currentInstance.InstanceStatus;
                                    createdOrChanged = true;
                                }
                            }
                            else
                            {
                                // If this is the first time we run through, we also need to output a message
                                roleInstanceSnapshot[currentInstance.InstanceName] = currentInstance;
                                createdOrChanged = true;
                            }

                            if (createdOrChanged)
                            {
                                string statusResource;
                                switch (currentInstance.InstanceStatus)
                                {
                                    case RoleInstanceStatus.BusyRole:
                                        statusResource = Resources.PublishInstanceStatusBusy;
                                        break;

                                    case RoleInstanceStatus.ReadyRole:
                                        statusResource = Resources.PublishInstanceStatusReady;
                                        break;

                                    default:
                                        statusResource = Resources.PublishInstanceStatusCreating;
                                        break;
                                }

                                WriteVerboseWithTimestamp(
                                    Resources.PublishInstanceStatusMessage,
                                    currentInstance.InstanceName,
                                    currentInstance.RoleName,
                                    statusResource);
                            }
                        }
                    }

                    // If a deployment has many roles to initialize, this
                    // thread must throttle requests so the Azure portal
                    // doesn't reply with a "too many requests" error
                    Thread.Sleep(SleepDuration);
                }
                while (deployment.RoleInstanceList.Any(r => r.InstanceStatus != RoleInstanceStatus.ReadyRole));

                WriteVerboseWithTimestamp(Resources.PublishCreatedWebsiteMessage, deployment.Url);

            }
            catch (CloudException)
            {
                throw new InvalidOperationException(
                    string.Format(Resources.CannotFindDeployment, context.ServiceName, context.ServiceSettings.Slot));
            }
        }
Пример #21
0
        public Dictionary<string, int> GetCurrentWords(List<Verse> verses, string text, bool at_word_start, bool with_diacritics)
        {
            Dictionary<string, int> result = new Dictionary<string, int>();
            if (!String.IsNullOrEmpty(text))
            {
                text = text.Trim();
                while (text.Contains("  "))
                {
                    text = text.Replace("  ", " ");
                }
                while (text.Contains("+"))
                {
                    text = text.Replace("+", "");
                }
                while (text.Contains("-"))
                {
                    text = text.Replace("-", "");
                }

                if ((this.Title.Contains("Original")) && (!with_diacritics))
                {
                    text = text.Simplify29();
                }

                string[] text_words = text.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                if (text_words.Length > 0)
                {
                    foreach (Verse verse in verses)
                    {
                        string verse_text = verse.Text;
                        if ((this.Title.Contains("Original")) && (!with_diacritics))
                        {
                            verse_text = verse_text.Simplify29();
                        }

                        verse_text = verse_text.Trim();
                        while (verse_text.Contains("  "))
                        {
                            verse_text = verse_text.Replace("  ", " ");
                        }
                        string[] verse_words = verse_text.Split();

                        if (verse_words.Length == verse_words.Length)
                        {
                            for (int i = 0; i < verse_words.Length; i++)
                            {
                                bool is_text_matched = false;
                                if (text_words.Length == 1) // 1 text_word
                                {
                                    if (at_word_start)
                                    {
                                        if (verse_words[i].StartsWith(text_words[0])) // start found
                                        {
                                            is_text_matched = true;
                                        }
                                    }
                                    else
                                    {
                                        if (verse_words[i].Contains(text_words[0])) // start found
                                        {
                                            is_text_matched = true;
                                        }
                                    }
                                }
                                else if (text_words.Length > 1)// more than 1 text_word
                                {
                                    if (verse_words[i].EndsWith(text_words[0])) // start found
                                    {
                                        if (verse_words.Length >= (i + text_words.Length))
                                        {
                                            // match text minus last word
                                            bool is_text_matched_minus_last_word = true;
                                            for (int j = 1; j < text_words.Length - 1; j++)
                                            {
                                                if (verse_words[j + i] != text_words[j])
                                                {
                                                    is_text_matched_minus_last_word = false;
                                                    break;
                                                }
                                            }

                                            // is still true, check the last word
                                            if (is_text_matched_minus_last_word)
                                            {
                                                int last_j = text_words.Length - 1;
                                                if (verse_words[last_j + i].StartsWith(text_words[last_j])) // last text_word
                                                {
                                                    is_text_matched = true;
                                                }
                                            }
                                        }
                                    }
                                }

                                if (is_text_matched)
                                {
                                    // skip all text but not found good_word in case it followed by good_word too
                                    i += text_words.Length - 1;

                                    // get last word variation
                                    if (i < verse_words.Length)
                                    {
                                        string matching_word = verse_words[i];
                                        if (!result.ContainsKey(matching_word))
                                        {
                                            result.Add(matching_word, 1);
                                        }
                                        else
                                        {
                                            result[matching_word]++;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return result;
        }
Пример #22
0
        public void Listas()
        {
            List<Produto> produtos = new List<Produto>();

            var produto = new Produto
            {
                Nome = "Xbox One"
            };

            produtos.Add(produto);
            produtos.Add(produto);

            Assert.AreEqual(2, produtos.Count);

            HashSet<Produto> produtosUnicos = new HashSet<Produto>();

            produtosUnicos.Add(produto);
            produtosUnicos.Add(produto);

            Assert.AreEqual(1, produtosUnicos.Count);

            Stack<Produto> pilha = new Stack<Produto>();

            var produto2 = new Produto
            {
                Nome = "PS4"
            };

            pilha.Push(produto);
            pilha.Push(produto2);

            var produtoPeek = pilha.Peek();
            var produtoPop = pilha.Pop();
            var produtoPop2 = pilha.Pop();

            if (pilha.Any())
            {
                produtoPeek = pilha.Peek();
            }

            Queue<Produto> fila = new Queue<Produto>();

            fila.Enqueue(produto);
            fila.Enqueue(produto2);

            var primeiroDaFila = fila.Peek();
            primeiroDaFila = fila.Dequeue();

            Console.WriteLine(primeiroDaFila);

            var dic = new Dictionary<int, Produto>();

            dic.Add(50, produto);
            dic.Add(90, produto2);

            Console.WriteLine(dic[50]);
            Console.WriteLine(dic[90]);

            if (dic.ContainsKey(5))
            {
                Console.WriteLine(dic[5]);
            }
            else
            {
                dic[5] = produto;

                Console.WriteLine(dic[5]);
            }
        }
        /// <summary>
        /// CreateRetrieval
        /// </summary>
        /// <param name="processRetList">ProcessRetrieval List (EmpID, ReqID)</param>
        /// <returns></returns>
        public int createRetrieval(List<ProcessRetrieval> processRetList)
        {
            int result = 0;

            //create and add new retrieval
            Retrieval ret = new Retrieval();
            ret.Date = DateTime.Now;
            ret.EmpID = processRetList.First().EmpID;
            ret.Status = "PENDING";
            ctx.Retrieval.Add(ret);
            ctx.SaveChanges();

            //obtain retID of newly added retrieval
            int empID = processRetList.First().EmpID;
            Retrieval retLast = ctx.Retrieval.Where(x=> x.EmpID == empID).ToList().Last();
            int RetID = retLast.RetID;

            //hashmap-like to store itemID and collated qty
            Dictionary<string, int> itemQty = new Dictionary<string, int>();

            foreach (ProcessRetrieval processRet in processRetList)
            {
                //update RetID of requisition
                Requisition requisition = ctx.Requisition.Where(x => x.ReqID == processRet.ReqID).First();
                requisition.RetID = RetID;
                requisition.StatusID = 3;

                //obtain requisition detail list
                List<RequisitionDetail> reqDetailList = ctx.RequisitionDetail.Where(x => x.ReqID == processRet.ReqID).ToList();

                foreach (RequisitionDetail reqDetail in reqDetailList)
                {
                    //if itemQty does not contain the item, add item to itemQty
                    if (!itemQty.ContainsKey(reqDetail.ItemID))
                    {
                        itemQty.Add(reqDetail.ItemID, (int)reqDetail.RequestQty);
                    }
                    //else if itemQty contains item, add the qty to existing qty
                    else
                    {
                        itemQty[reqDetail.ItemID] += (int) reqDetail.RequestQty;
                    }
                }
            }

            //extract all keys and values in itemQty
            string[] itemQtyKeys = itemQty.Keys.ToArray();
            int[] itemQtyValues = itemQty.Values.ToArray();

            for (int i = 0; i < itemQty.Count; i++)
            {
                //create and add new retrieval detail
                RetrievalDetail retrievalDetail = new RetrievalDetail();
                retrievalDetail.RetID = RetID;
                retrievalDetail.ItemID = itemQtyKeys[i];
                retrievalDetail.RequestQty = itemQtyValues[i];
                ctx.RetrievalDetail.Add(retrievalDetail);
            }

            int count = ctx.SaveChanges();

            if (count > 0)
                result = RetID;

            if (result == RetID)
            {
                foreach (ProcessRetrieval processRet in processRetList)
                {
                    //send notification:
                    NotificationController nt = new NotificationController();
                    nt.sendNotification(4, empID, Convert.ToString(processRet.ReqID));
                }
            }

            return result;
        }