Beispiel #1
0
        static void Main(string[] args)
        {
            //string a = "admin";
            //Console.WriteLine(a.To16bitMD5());
            //Console.WriteLine(a.To32bitMD5());
            //Console.WriteLine(a.ToSHA1());
            //Example1();
            //Example2();
            var a2 = "2010-12-12".To<DateTime>(DateTime.Now);

            Dictionary<string, string> dict = new Dictionary<string, string>();
            Dictionary<string, string> dict2 = new Dictionary<string, string>();
            dict2.Add("22222222", "");

            dict.TryAdd("12", "").TryAdd("34", "").AddOrReplace("34", "").AddRange(dict2, false);
            var asdf = "123".CompareTo("1");

            List<string> lst = new List<string>() { "wer", "dsfdsf", "sad" };
            lst.ForEach((item) => { Console.WriteLine(item); });

            List<User> lstUser = new List<User>
            {
                new User{Id=1, Name="柳永法",Age=28,IsMan=true},
                new User{Id=2, Name="柳永法1",Age=28,IsMan=true},
                new User{Id=3, Name="柳永法",Age=29,IsMan=true},
                new User{Id=4, Name="柳永法1",Age=29,IsMan=true},
            };

            var result1 = lstUser.Distinct(p => p.Age);
            var result2 = lstUser.Distinct((x, y) => x.Age == y.Age && x.IsMan == y.IsMan);
        }
Beispiel #2
0
        public Result HandVerifier(List<Card> listCard)
        {
            if(listCard==null)
            throw new ArgumentException("lista de cartas null");

              if (listCard.Count() != NumeroCartasMano)
            throw new ArgumentException("numero de cartas incorrecto");

              if (listCard.Select(card => listCard.Count(x => Equals(x, card))).Any(countOfCards => countOfCards > 1))
            throw new ArgumentException("dos o más cartas iguales");

              if (IsEscalera(listCard) && listCard.Any(x => x.Number == CardNumber.Ace))
            return Result.EscaleraReal;

              if (IsEscalera(listCard) && listCard.Distinct(new CardsEqualsColor()).Count()==1)
            return Result.EscaleraColor;

              if (listCard.Distinct(new CardsEqualsNumber()).Count() == 2)
            return MaxCardsEqualsNumber(listCard, 3) ? Result.Full : Result.Poker;

              if (listCard.Distinct(new CardsEqualsColor()).Count() == 1)
            return Result.Color;

              if (IsEscalera(listCard))
            return Result.Escalera;

              if (listCard.Distinct(new CardsEqualsNumber()).Count() == 3)
            return MaxCardsEqualsNumber(listCard, 2) ? Result.DoblesParejas : Result.Trio;

              return listCard.Distinct(new CardsEqualsNumber()).Count() == 4 ? Result.Pareja : Result.Nada;
        }
        public void ShuffleMultipleAndCompare()
        {
            IShuffler<int> shuffler = new FisherYatesModernShuffler<int>();

            var shuffledLists = new List<IList<int>>();

            for (int i = 0; i < 1000; i++)
            {
                var list = GetListOfIntegers();
                shuffler.Shuffle(list);

                shuffledLists.Add(list);
            }

            // filter the lists for only unique lists
            // if the number of unique lists match the number of lists shuffled
            // then all of the lists have been shuffled
            var uniqueLists = shuffledLists.Distinct();
            Assert.Equal(shuffledLists.Count(), uniqueLists.Count());

            // add one of the lists a second time to make sure our check is valid
            // as a sanity check
            shuffledLists.Add(shuffledLists.First());
            uniqueLists = shuffledLists.Distinct();
            Assert.NotEqual(shuffledLists.Count(), uniqueLists.Count());
        }
Beispiel #4
0
        static void Main(string[] args)
        {
            string[] input = Console.ReadLine().Split('\\');

            List<char> left = input[0].ToCharArray().ToList();
            List<char> right = input[1].ToCharArray().ToList();
            string command = input[2];

            List<char> result = new List<char>();

            switch (command)
            {
                case "join":

                    foreach (char element in right)
                    {
                        result.AddRange(left.FindAll(c => c == element));
                    }

                    result.Sort();

                    Console.WriteLine(String.Join("", result.Distinct()));

                    break;

                case "right exclude":

                    result = left;

                    foreach (char element in right)
                    {
                        result.RemoveAll(c => c == element);
                    }

                    result.Sort();

                    Console.WriteLine(String.Join("", result.Distinct()));

                    break;

                case "left exclude":

                    result = right;

                    foreach (char element in left)
                    {
                        result.RemoveAll(c => c == element);
                    }

                    result.Sort();

                    Console.WriteLine(String.Join("", result.Distinct()));

                    break;

                default:
                    break;
            }
        }
        protected void LoadInvolvements(ITransactionController transactionController, TreeNodeData<ActionKey> node, List<ClaimInvolvementDto> claimInvolvements, List<DtoBase> invToLoad, StaticValues.InternalIOType type)
        {
            ClaimHeaderDto headerDto = ((ClaimModel)transactionController.Model).HeaderDto;

            if (headerDto.ClaimInvolvementLinks != null)
            {
                claimInvolvements.ForEach(CI =>
                {
                    var involvementLinkFrom = headerDto.ClaimInvolvementLinks.Where(CIL => ((ClaimInvolvementLinkData)CIL.Data).ClaimInvolvementFromDataId == CI.Data.DataId);
                    involvementLinkFrom.ForEach(y =>
                    {
                        var involvement = headerDto.ClaimInvolvements.Where(z => z.Data.DataId == ((ClaimInvolvementLinkData)y.Data).ClaimInvolvementToDataId);
                        invToLoad.AddRange(involvement);
                    });


                    var involvementLinkTo = headerDto.ClaimInvolvementLinks.Where(CIL => ((ClaimInvolvementLinkData)CIL.Data).ClaimInvolvementToDataId == CI.Data.DataId);
                    involvementLinkTo.ForEach(y =>
                    {
                        var involvement = headerDto.ClaimInvolvements.Where(z => z.Data.DataId == ((ClaimInvolvementLinkData)y.Data).ClaimInvolvementFromDataId);
                        invToLoad.AddRange(involvement);
                    });
                });
            }

            int invToLoadCount = invToLoad.Distinct().Count();
            int count = 0;
            if (invToLoad.Distinct().Any())
            {
                transactionController.LoadLiteData(
                    Guid.Empty,
                    RetrievalType.WithChildHierarchy,
                    invToLoad.Distinct(),
                    NavigationType.None,
                    null,
                     r =>
                     {
                         if (++count == invToLoadCount)
                         {
                             var model = (ClaimModel)transactionController.Model;
                             model.CreateAllInsuredObjectCollection(type);
                             node.IsLoaded = true;
                         }
                     },
                    true,
                    BusinessDataVariant.Full);
            }
            else
            {
                node.IsLoaded = true;
            }
        }
        public List<string> getpropertyitems(string PropertyName, int NodeId, string NodeTypeAlias, bool UseParent)
        {
            string cachekey = PRE_CACHE_KEY + PropertyName + "_" + NodeId.ToString() + "_" +NodeTypeAlias;
            if (HttpContext.Current.Cache[cachekey] != null)
            {
                return (List<string>)HttpContext.Current.Cache[cachekey];
            }
            else
            {
                List<string> propertyList = new List<string>();
                Node startNode;

                if (UseParent)
                {
                    startNode = new Node(NodeId).Parent;
                }
                else
                {
                    startNode = new Node(NodeId);
                }

                if (startNode != null)
                {
                    string nodeListCacheKey = PRE_CACHE_KEY + NodeId.ToString() + "_" +NodeTypeAlias;
                    List<Node> nodeList;
                    if (HttpContext.Current.Cache[nodeListCacheKey] != null)
                    {
                        nodeList = (List<Node>)HttpContext.Current.Cache[nodeListCacheKey];
                    }
                    else
                    {
                        nodeList = new List<Node>();
                        GetNodesOfType(startNode, NodeTypeAlias, nodeList);
                        HttpContext.Current.Cache.Add(nodeListCacheKey, nodeList, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, 20, 0), CacheItemPriority.Normal, null);
                    }
                    foreach (Node n in nodeList)
                    {
                        if (n.GetProperty(PropertyName) != null)
                        {
                            propertyList.Add(n.GetProperty(PropertyName).Value);
                        }
                    }
                }
                propertyList.Sort();

                HttpContext.Current.Cache.Add(cachekey, propertyList.Distinct().ToList(), null, Cache.NoAbsoluteExpiration, new TimeSpan(0, 20, 0), CacheItemPriority.Normal, null);

                return propertyList.Distinct().ToList();
            }
        }
Beispiel #7
0
        public async Task <CollectionOfEntities <User, UserSortingEnum> > GetManagersAsync(int start, int count,
                                                                                           List <UserSortingEnum> sortings, int langId)
        {
            var         result   = new CollectionOfEntities <User, UserSortingEnum>();
            List <User> entities = null;

            var models = (await _userRoleRepository.WhereAsync(x => x.RoleId != RoleHelper.Current.User.Id &&
                                                               x.RoleId != RoleHelper.Current.Customer.Id))?.ToList();

            if (models != null && models.Count > 0)
            {
                entities = models.Select(x => x.User)?.ToList()
                           .Where(y => y.UserProfile.LanguageId == langId)?.ToList();
            }

            entities = entities?.Distinct().ToList();

            result.Total          = entities?.Count() ?? 0;
            result.Start          = start;
            result.EntitySortings = sortings;

            var x = count == 0 ? result.Total - start : count;

            result.Entities = SortCollection(entities ?? new List <User>(), sortings).Skip(start).Take(x);
            result.Count    = result.Entities.Count();

            return(result);
        }
Beispiel #8
0
        /// <inheritdoc/>
        public virtual IList <string> Validate(TModel model, bool recursive = false)
        {
            var validationResults = new List <ValidationResult>();

            var context = new ValidationContext(model);

            if (recursive == true)
            {
                this.validator.TryValidateObjectRecursive(model, validationResults);
            }
            else
            {
                this.validator.TryValidateObject(model, validationResults);
            }

            Validator.TryValidateObject(
                model, context, validationResults, true);

            List <string> result = new List <string>();

            foreach (var validationResult in validationResults)
            {
                var output = validationResult.ErrorMessage;

                if (validationResult?.MemberNames?.Count() > 0)
                {
                    output += $" - Members: { string.Join(", ", validationResult.MemberNames)}";
                }

                result.Add(output);
            }
            return(result?.Distinct()?.ToList());
        }
Beispiel #9
0
        public List<ESPNGame> GetGames(int year, int seasonType, int weekNum)
        {
            var games = new List<ESPNGame>();
            Regex gameRX = new Regex("gameId=[0-9]+");
            var url = string.Format("{0}/{1}", GAME_URL, string.Format("_/year/{0}/seasontype/{1}/week/{2}", year.ToString(), seasonType.ToString(), weekNum.ToString()));
            var html = HelperMethods.LoadHtmlFromUrl(url);
            var gameIds = gameRX.Matches(html);

            foreach (Match gId in gameIds)
            {
                var gameId = System.Convert.ToInt32(gId.Value.Replace("gameId=", string.Empty));

                if (!games.Select(g => g.GameId).Contains(gameId))
                {
                    try
                    {
                        var teamsForGame = GetTeamsByGame(gameId);

                        ESPNGame game = new ESPNGame();
                        game.GameId = gameId;
                        game.HomeTeamId = teamsForGame["home"];
                        game.AwayTeamId = teamsForGame["away"];
                        games.Add(game);
                    }
                    catch { }
                }
            }

            return games.Distinct().ToList();
        }
Beispiel #10
0
        /// <summary>
        /// Reads the file list from a .torrent file.
        /// </summary>
        /// <param name="downloadPath"></param>
        /// <returns></returns>
        public static List<string> ReadAnnounceList(string torrentFile)
        {
            if (!File.Exists(torrentFile))
                throw new FileNotFoundException("Can't find file " + torrentFile);

            var ret = new List<string>();

            //read and decode the .torrent file
            byte[] torrentBytes = File.ReadAllBytes(torrentFile);
            var torrentData = BEncodedValue.Decode<BEncodedDictionary>(torrentBytes);

            try
            {
                string announce = (torrentData["announce"] as BEncodedString).Text;
                ret.Add(announce);

                var announceList = torrentData.Item<BEncodedList>("announce-list");
                foreach (BEncodedList urlList in announceList)
                    foreach (BEncodedString url in urlList)
                        ret.Add(url.Text);
            }
            catch { };

            return ret.Distinct().ToList();
        }
    public override ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache)
    {
        List<string> searched = new List<string>();

            if (!string.IsNullOrEmpty(viewName))
            {
                ViewEngineResult result;

                result = base.FindView(controllerContext, string.Format("{0}.{1}", viewName, CultureInfo.CurrentUICulture.Name), masterName, useCache);

                if (result.View != null)
                {
                    return result;
                }

                searched.AddRange(result.SearchedLocations);

                result = base.FindView(controllerContext, string.Format("{0}.{1}", viewName, CultureInfo.CurrentUICulture.TwoLetterISOLanguageName), masterName, useCache);

                if (result.View != null)
                {
                    return result;
                }

                searched.AddRange(result.SearchedLocations);
            }

            return new ViewEngineResult(searched.Distinct().ToList());
    }
Beispiel #12
0
        public static List<string> ParseGoogleKeys(int count, string startKey)
        {
            List<string> keys = new List<string>();
            keys.Add(startKey);

            string pattern = "<p[^>]*><a href=\".*?q=([^&]*)&[^>]*?>.*?</a></p>";
            Regex rx = new Regex(pattern, RegexOptions.Compiled);

            int i = 0;
            while (count > keys.Count & i <= keys.Count - 1)
            {
                string key = Uri.EscapeUriString(keys[i].Replace(' ', '+'));

                Uri uri = new Uri("http://www.google.ru/search?q=" + key + "&sourceid=opera&num=0&ie=utf-8&oe=utf-8&start=0");

                DownloaderObj obj = new DownloaderObj(uri, null, true, null, CookieOptions.NoCookies, 3);
                Downloader.DownloadSync(obj);
                if (obj.DataStr == null) return null;

                MatchCollection results = rx.Matches(obj.DataStr);
                foreach (Match m in results)
                {
                    keys.Add(m.Groups[1].Value);
                }
                keys = keys.Distinct().ToList<string>();
                if (OnKeyPageParsed!=null) OnKeyPageParsed(null, new KeyEventArgs(keys.Count, i, count));
                i++;
            }
            return keys;
        }
        public void AddCommandEnvelopeRouteCentre(CommandEnvelope envelope)
        {
            //add recepient
            List<Guid> centreList = new List<Guid>();
            centreList.Add(envelope.RecipientCostCentreId);
            centreList.Add(envelope.GeneratedByCostCentreId);
            if (envelope.OtherRecipientCostCentreList != null && envelope.OtherRecipientCostCentreList.Count > 0)
            {
                envelope.OtherRecipientCostCentreList.ForEach(centreList.Add);
            }
            foreach (var centreId in centreList.Distinct().ToList())
            {
                _commandEnvelopeRouteOnRequestCostcentreCollection.Save(
               new CommandEnvelopeRouteOnRequestCostcentre
               {
                   CostCentreId = centreId,
                   DocumentType = ((DocumentType)envelope.DocumentTypeId).ToString(),
                   DateAdded = DateTime.Now,
                   EnvelopeId = envelope.Id,
                   IsRetired = false,
                   IsValid = true,
                   Id = Guid.NewGuid(),
                   EnvelopeArrivalAtServerTick = envelope.EnvelopeArrivedAtServerTick,
                   EnvelopeRoutePriority = EnvelopeRoutePriority.Level1,
                   EnvelopeRoutedAtServerTick = DateTime.Now.Ticks,
                   GeneratedByCostCentreApplicationId = envelope.GeneratedByCostCentreApplicationId,
                   DocumentId = envelope.DocumentId,
                   ParentDocumentId = envelope.ParentDocumentId

               });
            }


        }
        public CadastroGrupoDiferencial()
        {
            InitializeComponent();
            GrupoDiferencialCadastro grp = new GrupoDiferencialCadastro(
                btnSalvar,
                btnCancelar,
                this,
                grupoGridView);
            grupoGridView.CellMouseDown += GridView_CellMouseDown;
            grupoGridView.ContextMenuStrip = menuGridView;

            removerLinhaContextButton.Click += (sender, args) =>
            {
                ToolStripMenuItem ts = (ToolStripMenuItem)sender;
                ContextMenuStrip cms = ts.Owner as ContextMenuStrip;
                DataGridView dg = cms.SourceControl as DataGridView;
                List<int> list = new List<int>();
                foreach (DataGridViewCell a in dg.SelectedCells)
                {
                    list.Add(a.RowIndex);
                }
                List<int> result = list.Distinct().ToList();
                result.Sort();
                result.Reverse();
                result.ForEach((n) =>
                {
                    DataGridViewRow row = dg.Rows[n];
                    if (!row.IsNewRow)
                    {
                        dg.Rows.Remove(row);
                    }
                });
            };
        }
 private List<ITreeNode> GetAllChildTreeNodes(InOperator inOperator, string propertyName) {
     var allTreeNodes = new List<ITreeNode>();
     XPCollection treeNodes = GetTreeNodes(propertyName, inOperator);
     if (treeNodes != null)
         allTreeNodes = treeNodes.Cast<ITreeNode>().ToList().GetAllTreeNodes();
     return allTreeNodes.Distinct().ToList();
 }
        /// <inheritdoc />
        public int Apply()
        {
            int retval = -1;

            try
            {
                // set the columns, ignoring duplicates
                _cur.SetColumns(_columns?.Distinct().ToArray());
            }
            catch (CommenceCOMException)
            {
                throw;
            }

            try
            {
                // set the related columns, ignoring duplicates
                _cur.SetRelatedColumns(_relatedcolumns?.Distinct().ToList());
            }
            catch (CommenceCOMException)
            {
                throw;
            }
            retval = _cur.ColumnCount;
            return(retval);
        }
Beispiel #17
0
 public TEX0(EndianBinaryReader er)
 {
     long basepos = er.BaseStream.Position;
     Signature = er.ReadString(Encoding.ASCII, 4);
     if (Signature != "TEX0") throw new SignatureNotCorrectException(Signature, "TEX0", er.BaseStream.Position - 4);
     SectionSize = er.ReadUInt32();
     TexInfo = new texInfo(er);
     Tex4x4Info = new tex4x4Info(er);
     PlttInfo = new plttInfo(er);
     dictTex = new Dictionary<DictTexData>(er);
     for (int i = 0; i < dictTex.numEntry; i++)
     {
         dictTex[i].Value.ReadData(er, TexInfo.ofsTex, Tex4x4Info.ofsTex, Tex4x4Info.ofsTexPlttIdx, basepos);
     }
     dictPltt = new Dictionary<DictPlttData>(er);
     List<UInt32> Offset = new List<uint>();
     for (int i = 0; i < dictPltt.numEntry; i++)
     {
         Offset.Add(dictPltt[i].Value.offset);
     }
     Offset = Offset.Distinct().ToList();
     Offset.Sort();
     for (int i = 0; i < dictPltt.numEntry; i++)
     {
         int idx = Offset.IndexOf(dictPltt[i].Value.offset);
         if (idx == Offset.Count - 1)
         {
             dictPltt[i].Value.ReadData(er, PlttInfo.ofsPlttData, (uint)er.BaseStream.Length - (Offset[idx] + PlttInfo.ofsPlttData + (uint)basepos), basepos);
         }
         else
         {
             dictPltt[i].Value.ReadData(er, PlttInfo.ofsPlttData, Offset[idx + 1] - Offset[idx], basepos);
         }
     }
 }
    //Write a program that takes as input two lists of integers and joins them. The result should hold all numbers from the first list, and all numbers from the second list, without repeating numbers, and arranged in increasing order. The input and output lists are given as integers, separated by a space, each list at a separate line.
    static void Main()
    {
        string firstLine = Console.ReadLine();
        string secondLine = Console.ReadLine();
        string[] firstLineNums = firstLine.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
        string[] secondLineNums = secondLine.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

        List<int> mainList = new List<int>();
        List<int> auxiliaryList = new List<int>();

        for (int i = 0; i < firstLineNums.Length; i++)
        {
            auxiliaryList.Add(int.Parse(firstLineNums[i]));
        }

        for (int i = 0; i < secondLineNums.Length; i++)
        {
            auxiliaryList.Add(int.Parse(secondLineNums[i]));
        }

        auxiliaryList.Sort();

        mainList = auxiliaryList.Distinct().ToList(); //LINQ - Distinct erases the duplicated elements

        foreach (int number in mainList)
        {
            Console.Write(number + " ");
        }
        Console.WriteLine();
    }
Beispiel #19
0
        private void sendShipyardInformation()
        {
            if (EDDI.Instance.CurrentStation != null && EDDI.Instance.CurrentStation.shipyard != null)
            {
                List <string> eddnShips = new List <string>();
                foreach (Ship ship in EDDI.Instance.CurrentStation.shipyard)
                {
                    if (ship?.EDName != null)
                    {
                        eddnShips.Add(ship.EDName);
                    }
                }
                eddnShips = eddnShips?.Distinct()?.ToList();

                // Only send the message if we have ships
                if (eddnShips.Count > 0)
                {
                    IDictionary <string, object> data = new Dictionary <string, object>
                    {
                        { "timestamp", DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ") },
                        { "systemName", systemName },
                        { "stationName", stationName },
                        { "marketId", marketId },
                        { "ships", eddnShips },
                        { "horizons", EDDI.Instance.inHorizons }
                    };

                    SendToEDDN("https://eddn.edcd.io/schemas/shipyard/2", data);
                }
            }
        }
Beispiel #20
0
        public static void Run()
        {
            Timer.RecordMiliseconds(() =>
            {
                var abundantNumbers = AbundantNumbers();
                var sumResults = new List<int>();

                foreach (var number1 in abundantNumbers)
                {
                    foreach (var number2 in abundantNumbers)
                        sumResults.Add(number1 + number2);
                }

                var distinctResults = sumResults.Distinct().ToArray();
                var sum = 0;
                for (int i = 1; i <= Limit; i++)
                {
                    if (!distinctResults.Contains(i))
                        sum += i;
                }

                Console.WriteLine(
                    "{0} is the sum of all positive intergers which cannot be written as the sum of two abundant numbers",
                    sum);
            });
        }
        protected IEnumerable<TreeViewResult> GetDistinctDictionaryTablesTree(List<IUserField> userFields, Aspect.Domain.CommonDomain provider)
        {
            List<Guid> list = userFields.Select(s => s.DictionaryTreeID).Distinct().ToList();
            List<Aspect.Domain.GetDictionaryTreeParentsResult> tableList = new List<Aspect.Domain.GetDictionaryTreeParentsResult>();
            foreach (Guid item in list)
            {
                List<Aspect.Domain.GetDictionaryTreeParentsResult> lll = provider.GetDictionaryTreeParents(item).ToList();
                int max =lll.Max(l => l.Level).Value;
                lll.ForEach(delegate(GetDictionaryTreeParentsResult n)
                {
                    n.Level = (n.Level - max) * -1;
                });
                tableList.AddRange(lll);
            }

            //return tableList.Distinct(DictionaryTreeResultEqualityComparer.Instance).OrderByDescending(d => d.Level).ToList().ConvertAll(
            return tableList.Distinct(DictionaryTreeResultEqualityComparer.Instance).OrderBy(d => d.Level).ToList().ConvertAll(
                delegate(GetDictionaryTreeParentsResult n)
                {
                    return new TreeViewResult()
                    {
                        ID = n.ID,
                        Level = (int)n.Level
                    };
                }
                ).ToList();
        }
	public static void MenuGrowSelection()
	{
		foreach(pb_Object pb in pbUtil.GetComponents<pb_Object>(Selection.transforms))
		{
			switch(pb_Editor.instance.selectionMode)
			{
				case SelectMode.Vertex:
					pb.SetSelectedEdges(pbMeshUtils.GetConnectedEdges(pb, pb.SelectedTriangles));
					break;
				
				case SelectMode.Face:
				case SelectMode.Edge:
					List<pb_Face>[][] all = pbMeshUtils.GetConnectedFacesJagged(pb, pb.SelectedFaces);
					List<pb_Face> f = new List<pb_Face>();
					foreach(List<pb_Face>[] fds in all)
						foreach(List<pb_Face> lf in fds)
							f.AddRange(lf);
					f = f.Distinct().ToList();

					pb.SetSelectedFaces(f.ToArray());

					break;
			}
		}
		pb_Editor.instance.UpdateSelection();
	}
 public HostInfo(string hostName, bool hostNotFound, List <string> certificates = null, List <SelectedCipherSuite> selectedCipherSuites = null)
 {
     HostName             = hostName;
     HostNotFound         = hostNotFound;
     Certificates         = certificates?.Distinct().ToList() ?? new List <string>();
     SelectedCipherSuites = selectedCipherSuites ?? new List <SelectedCipherSuite>();
 }
 internal static double MatchConfiguredFPS(double probedFps)
 {
     if (fpsList == null)
     {
         fpsList = new List<double>();
         NumberFormatInfo provider = new NumberFormatInfo() { NumberDecimalSeparator = "." };
         Settings xmlreader = new MPSettings();
         for (int i = 1; i < 100; i++)
         {
             string name = xmlreader.GetValueAsString("general", "refreshrate0" + Convert.ToString(i) + "_name", "");
             if (string.IsNullOrEmpty(name)) continue;
             string fps = xmlreader.GetValueAsString("general", name + "_fps", "");
             string[] fpsArray = fps.Split(';');
             foreach (string fpsItem in fpsArray)
             {
                 double fpsAsDouble = -1;
                 double.TryParse(fpsItem, NumberStyles.AllowDecimalPoint, provider, out fpsAsDouble);
                 if (fpsAsDouble > -1) fpsList.Add(fpsAsDouble);
             }
         }
         fpsList = fpsList.Distinct().ToList();
         fpsList.Sort();
     }
     if (fpsList != null && fpsList.Count > 0)
     {
         return fpsList.FirstOrDefault(f => Math.Abs(f - probedFps) < 0.24f);
     }
     return default(double);
 }
    static void Main()
    {
        string[] nums = Console.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
        string[] joins = Console.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

        List<int> numbers = new List<int>();

        foreach (string num in nums)
        {
            numbers.Add(int.Parse(num));
        }

        foreach (string num in joins)
        {
            numbers.Add(int.Parse(num));
        }

        numbers.Sort();

        numbers = numbers.Distinct().ToList();

        foreach (int num in numbers)
        {
            Console.Write("{0} ", num);
        }
        Console.WriteLine();
        Main();
    }
Beispiel #26
0
        private void sendShipyardInformation(MarketInformationUpdatedEvent theEvent)
        {
            if (theEvent.shipyard != null)
            {
                List <string> eddnShips = new List <string>();
                foreach (Ship ship in theEvent.shipyard)
                {
                    if (ship?.EDName != null)
                    {
                        eddnShips.Add(ship.EDName);
                    }
                }
                eddnShips = eddnShips?.Distinct()?.ToList();

                // Only send the message if we have ships
                if (eddnShips.Count > 0)
                {
                    IDictionary <string, object> data = new Dictionary <string, object>
                    {
                        { "timestamp", theEvent.timestamp.ToString("yyyy-MM-ddTHH:mm:ssZ") },
                        { "systemName", theEvent.starSystem },
                        { "stationName", theEvent.stationName },
                        { "marketId", theEvent.marketId },
                        { "ships", eddnShips },
                        { "horizons", theEvent.inHorizons }
                    };

                    SendToEDDN("https://eddn.edcd.io/schemas/shipyard/2", data);
                }
            }
        }
        public static ICollection<string> ReadAllTasks(string path)
        {
            var list = new List<string>();

            if (path.EndsWith(".ts"))
            {
                path = path.Replace(".ts", ".js").Replace(".coffee",".js");
            }

            if (!File.Exists(path))
            {
                return list;
            }

            // executes the gulpfile with some little additions :)
            try
            {
                var engine = new ScriptEngine();
                engine.Execute(Resources.gulpInit);
                engine.ExecuteFile(path);

                // reads the evaluated tasks
                ArrayInstance names = (ArrayInstance)engine.Evaluate("tasks");
                foreach (var elem in names.ElementValues)
                {
                    list.Add((string)elem);
                }
            }
            catch (Exception)
            {
                list.Add("Cannot parse gulpfile");
            }

            return list.Distinct().ToList();
        }
Beispiel #28
0
        public string GetJsonString()
        {
            var sb         = StringBuilderCache.Acquire();
            var jsonObject = new JsonObject(sb);

            if (string.IsNullOrEmpty(RefAllele))
            {
                RefAllele = "-";
            }
            if (string.IsNullOrEmpty(AltAllele))
            {
                AltAllele = "-";
            }

            jsonObject.AddStringValue("refAllele", RefAllele);
            jsonObject.AddStringValue("altAllele", AltAllele);
            jsonObject.AddStringValues("diseases", _diseases?.Distinct());
            if (_homoplasmy.HasValue)
            {
                jsonObject.AddBoolValue("hasHomoplasmy", _homoplasmy.Value, true);
            }
            if (_heteroplasmy.HasValue)
            {
                jsonObject.AddBoolValue("hasHeteroplasmy", _heteroplasmy.Value, true);
            }
            jsonObject.AddStringValue("status", _status);
            jsonObject.AddStringValue("clinicalSignificance", _clinicalSignificance);
            jsonObject.AddStringValue("scorePercentile", _scorePercentile, false);
            jsonObject.AddIntValue("numGenBankFullLengthSeqs", _numGenBankFullLengthSeqs);
            jsonObject.AddStringValues("pubMedIds", _pubMedIds);
            return(StringBuilderCache.GetStringAndRelease(sb));
        }
Beispiel #29
0
    static void Main()
    {
        string input = Console.ReadLine();
        string[] words = input.Split(new char[] {' ', ',', '.','?','!'},StringSplitOptions.RemoveEmptyEntries);
        List<string> listOfPalindromes = new List<string>();

        foreach(string word in words)
        {
            bool isPalindrome = true;

            for(int i=0; i<word.Length/2; i++)
            {
                if(word[i] != word[word.Length - i - 1])
                {
                    isPalindrome = false;
                }
            }

            if(isPalindrome)
            {
                listOfPalindromes.Add(word);
            }
        }

        listOfPalindromes.Sort();
        Console.WriteLine(string.Join(", ", listOfPalindromes.Distinct()));
    }
 public List<string> GPGetItemName(string catname, string subcatname, string groupname, string appname, string aggName)
 {
     
     var r = new List<string>();
     try
     {
         var db = serverGeneralPerformance.GetDatabase(string.Format("{0}__{1}__{2}__{3}", catname, subcatname, appname, groupname));
         var colNames = db.GetCollectionNames().Where(name => !name.Contains("system.") && !name.Contains("$"));
         if (string.IsNullOrEmpty(aggName))
             colNames = colNames.Where(n => !n.Contains("___")).ToList();
         else
             colNames = colNames.Where(n => n.Contains("___" + aggName)).ToList();
         foreach (var colName in colNames)
         {
             var colKey = colName;
             if (colKey.Contains("___"))
                 colKey = colKey.Substring(0, colKey.IndexOf("___"));
             if (colKey.Contains("__"))
                 r.Add(colKey.Substring(0, colKey.IndexOf("__")));
             else
                 r.Add(colKey);
         }
     }
     catch(Exception ex)
     {
         ex.Handle();
     }
     return r.Distinct().ToList();
 }
        public string AssignProductsAsync(List<String> productIds, string productSetId)
        {
            Guid entityId;
            if (!Guid.TryParse(productSetId, out entityId) || entityId == Guid.Empty)
                return "false";

            using (var uow = new UnitOfWork(UnitOfWorkScopeType.New))
            {
                var productSetEntity = Repository.Data.Get<ProductSet>(Guid.Parse(productSetId));
                if (productSetEntity.Products == null)
                {
                    productSetEntity.Products = new List<Product>();
                }

                foreach (var productId in productIds.Distinct())
                {
                    var product = Repository.Data.Get<Product>(Guid.Parse(productId));
                    product.ProductSets.Add(productSetEntity);
                    Repository.Data.Save(product);
                }

                uow.Commit();
            }

            return "true";
        }
Beispiel #32
0
        static void Main(string[] args)
        {
            string s;
            s = Clipboard.GetText();
            var words = s.Split(' ');

            List<String> l = new List<String>();
            List<String> vyhodnoy_massiv = new List<String>();

            foreach (var word in words)
            {

                var cl = word.Replace(",", " ").Replace(".", " ").Replace(";", " ").Replace(":", " ").Trim();
                l.Add(cl);

            }

            l.Sort(StringComparer.CurrentCultureIgnoreCase);
            vyhodnoy_massiv = l.Distinct().Take(1000).ToList();

            foreach (var item in vyhodnoy_massiv)
            {
                Console.WriteLine(item);
            }

            Console.ReadLine();
        }
        /// <summary>
        /// Calculation method.
        /// </summary>
        /// <param name="chain">
        /// Source sequence.
        /// </param>
        /// <param name="link">
        /// Link of intervals in chain.
        /// </param>
        /// <returns>
        /// Average remoteness dispersion <see cref="double"/> value.
        /// </returns>
        public double Calculate(Chain chain, Link link)
        {
            List<int> intervals = new List<int>();
            for (int i = 0; i < chain.Alphabet.Cardinality; i++)
            {
                intervals.AddRange(chain.CongenericChain(i).GetIntervals(link).ToList());
            }

            List<int> uniqueIntervals = intervals.Distinct().ToList();

            List<int> intervalsCounts = new List<int>();

            for (int i = 0; i < uniqueIntervals.Count; i++)
            {
                var currentInterval = uniqueIntervals[i];
                intervalsCounts.Add(intervals.Count(interval => interval == currentInterval));
            }

            double result = 0;
            double gDelta = geometricMean.Calculate(chain, link);
            int n = (int)intervalsCount.Calculate(chain, link);

            for (int i = 0; i < uniqueIntervals.Count; i++)
            {
                int nk = intervalsCounts[i];
                double kDelta = uniqueIntervals[i];
                double centeredRemoteness = Math.Log(kDelta, 2) - Math.Log(gDelta, 2);
                result += nk == 0 ? 0 : centeredRemoteness * centeredRemoteness * nk / n;
            }

            return result;
        }
        public EmailExtractResult ExtractEmailsFromMarkup(string siteUrl, 
            List<string> aggregatedSiteMarkup)
        {
            var emailRegex = new Regex(EmailRegex);
            var emails = new List<string>();
            var hasMailto = false;

            // iterate each markup string and collect all email matches
            foreach (var markup in aggregatedSiteMarkup)
            {
                if (!hasMailto)
                    hasMailto = markup.Contains("mailto:");

                ExtractEmails(emailRegex, markup, emails);
            }

            // remove duplicate emails
            var distinctEmails = emails.Distinct().ToList();

            return new EmailExtractResult
            {
                SiteUrl = siteUrl,
                Emails = distinctEmails,
                HasMailto = hasMailto
            };
        }
Beispiel #35
0
        // GET api/<controller>
        /// <summary>
        /// Get all tournaments, where the current user has either any role, is speaker, or adjudicator
        /// </summary>
        /// <returns></returns>
        public async Task<IEnumerable<Tournament>> Get()
        {
            var ident = HttpContext.Current.User.Identity as ClaimsIdentity;
            var userId = ident.GetUserId();
            var user = await userManager.FindByIdAsync(userId);


            if (user != null)
            {
                List<DebReg.Models.Tournament> tournaments = new List<DebReg.Models.Tournament>();
                foreach (var team in user.Teams)
                {
                    tournaments.Add(team.Tournament);
                }

                foreach (var adjudicator in user.Adjudicator)
                {
                    tournaments.Add(adjudicator.Tournament);
                }

                foreach (var role in user.TournamentRoles)
                {
                    tournaments.Add(role.Tournament);
                }

                tournaments = tournaments.Distinct(new TournamentComparer()).ToList();
                return from tournament in tournaments
                       select new Tournament(tournament, user);
            }

            return null;
        }
        public IEnumerable<KeyValuePair<int, DateTime>> GetChats(string userId, string token)
        {
            int uId = Convert.ToInt32(userId);
            if (AuthService.ValidateAuthData(uId, token))
            {
                IEnumerable<MessageModel> messages =
                    repository.GetMessages().Where(model => model.From == uId || model.To == uId).
                    OrderByDescending(model => model.time);
                List<int> res = new List<int>();
                foreach (MessageModel messageModel in messages)
                {
                    if (messageModel.From != uId)
                        res.Add(messageModel.From);
                    else
                        res.Add(messageModel.To);
                }
                res = res.Distinct().ToList();
                List<KeyValuePair<int, DateTime>> final = new List<KeyValuePair<int, DateTime>>();
                foreach (var usId in res)
                {
                    DateTime dt = messages.Where(model => model.From == usId || model.To == usId).
                                           OrderByDescending(model => model.time).Select(model => model.time).First();
                    final.Add(new KeyValuePair<int, DateTime>(usId, dt));

                }
                return final;
            }

            return null;
        }
        public JsonResult AddQuestion(string questionData, string answerData, string User_Id)
        {
            var flag = false;
            //|4, |1,3,4, |dfdsf,
            //处理重复值
            questionData = questionData.TrimEnd(',');
            string[] qq = questionData.Split(',');
            string[] aa = answerData.Split('|');
            List<string> allList = new List<string>(qq);
            List<string> qllList = new List<string>(aa);
            allList = allList.Distinct().ToList();
            qllList = qllList.ToList();
            if (allList.Count > 0)
            {
                for (int i = 0; i < allList.Count; i++)
                {
                    //插入提交答案
                    QItemAnswer qitemanswer = new QItemAnswer();
                    //for (int j = 0; j < qllList.Count; j++)
                    //{
                    qitemanswer.SetQuestionID = Convert.ToInt32(allList[i]);
                    qitemanswer.Answer = "," + qllList[i + 1];
                    qitemanswer.AddDate = DateTime.Now;
                    qitemanswer.UserId = Convert.ToInt32(User_Id);
                    //break;
                    //}
                    QItemAnswerRepository.Add(qitemanswer);
                    QItemAnswerRepository.Context.Commit();
                    flag = true; ;
                }
            }

            return Json(new { flag = flag }, JsonRequestBehavior.AllowGet);
        }
Beispiel #38
0
        public static IEnumerable <CouponPriceModel> GetCouponPrice()
        {
            const string            sql    = @"SELECT  PCPC.PID,DPSD.jingdongself_price AS  JDPrice,DPSD.qccr_retailprice AS QCCRPrice,DPSD.cost CostPrice, DPSD.num_week WeekSaleCount,DPSD.num_month MonthSaleCount,DPSD.totalstock Stock FROM [Tuhu_bi].[dbo].[dm_TireSales_Monthly]  AS PCPC  WITH(nolock)   
LEFT JOIN Tuhu_bi..dm_Product_SalespredictData AS DPSD WITH(nolock)  
ON DPSD.PID=PCPC.PID";
            List <CouponPriceModel> result = null;

            using (var dbhelper = DbHelper.CreateLogDbHelper(true))
            {
                using (var cmd = dbhelper.CreateCommand(sql))
                {
                    result = dbhelper.ExecuteSelect <CouponPriceModel>(cmd).ToList();
                }
            }
            result = result?.Distinct()?.ToList();
            if (result != null && result.Any())
            {
                string gw_sql      = @"SELECT  PID,cy_list_price AS GWPrice ,DisplayName,CP_Brand  Brand,OnSale FROM   Tuhu_productcatalog.dbo.vw_Products  WITH ( NOLOCK ) WHERE PID IN('{0}')";
                string execute_sql = string.Format(gw_sql, string.Join("','", result.Select(s => s.PID)));
                Dictionary <string, Tuple <decimal?, string, string, bool> > GwPriceList = null;
                Func <DataTable, Dictionary <string, Tuple <decimal?, string, string, bool> > > action = delegate(DataTable dt)
                {
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        GwPriceList = new Dictionary <string, Tuple <decimal?, string, string, bool> >();
                        foreach (DataRow item in dt.Rows)
                        {
                            if (!GwPriceList.ContainsKey(item.GetValue <string>("PID")))
                            {
                                GwPriceList.Add(item.GetValue <string>("PID"), Tuple.Create(item.GetValue <decimal?>("GWPrice"), item.GetValue <string>("DisplayName"), item.GetValue <string>("Brand"), item.GetValue <bool>("OnSale")));
                            }
                        }
                    }
                    return(GwPriceList);
                };
                using (var cmd = new SqlCommand(execute_sql))
                {
                    DbHelper.ExecuteQuery(true, cmd, action);
                }
                if (GwPriceList != null && GwPriceList.Any())
                {
                    foreach (var item in result)
                    {
                        if (GwPriceList.ContainsKey(item.PID))
                        {
                            item.GWPrice     = GwPriceList[item.PID].Item1;
                            item.DisplayName = GwPriceList[item.PID].Item2;
                            item.Brand       = GwPriceList[item.PID].Item3;
                            item.OnSale      = GwPriceList[item.PID].Item4;
                        }
                    }
                }
            }
            return(result?.Where(w => w.OnSale));
        }
Beispiel #39
0
    public void MakeDict()
    {
        dict = new Dictionary <string, T>();

        list = list?.Distinct().ToList();
        foreach (var item in list)
        {
            dict.Add(item.UniqueName, item);
        }

        //Debug.Log("Dictionary of type " + typeof(T).ToString() + " created from " + dict.Count.ToString() + " items");
    }
Beispiel #40
0
        internal List <UdpProcessRecord> LookupForUdpConnectedProcesses()
        {
            int bufferSize = 0;
            List <UdpProcessRecord> activeUdpConnections = new List <UdpProcessRecord>();
            // Getting the size of UDP table, that is returned in 'bufferSize' variable.
            uint   result            = GetExtendedUdpTable(IntPtr.Zero, ref bufferSize, true, AF_INET, UdpTableClass.UDP_TABLE_OWNER_PID);
            IntPtr udpTableRecordPtr = Marshal.AllocHGlobal(bufferSize);

            try
            {
                // The size of the table returned in 'bufferSize' variable in previous
                // call must be used in this subsequent call to 'GetExtendedUdpTable'
                // function in order to successfully retrieve the table.
                result = GetExtendedUdpTable(udpTableRecordPtr, ref bufferSize, true, AF_INET, UdpTableClass.UDP_TABLE_OWNER_PID);

                if (result != 0)
                {
                    throw new Exception("GetExtendedUdpTable failed");
                }

                // Marshals data from an unmanaged block of memory to a newly allocated
                // managed object 'udpRecordsTable' of type 'MIB_UDPTABLE_OWNER_PID'
                // to get number of entries of the specified TCP table structure.
                MIB_UDPTABLE_OWNER_PID udpRecordsTable = (MIB_UDPTABLE_OWNER_PID)Marshal.PtrToStructure(udpTableRecordPtr, typeof(MIB_UDPTABLE_OWNER_PID));
                IntPtr tableRowPtr = (IntPtr)((long)udpTableRecordPtr + Marshal.SizeOf(udpRecordsTable.dwNumEntries));

                // Reading and parsing the UDP records one by one from the table and
                // storing them in a list of 'UdpProcessRecord' structure type objects.
                for (int i = 0; i < udpRecordsTable.dwNumEntries; i++)
                {
                    MIB_UDPROW_OWNER_PID udpRow = (MIB_UDPROW_OWNER_PID)Marshal.PtrToStructure(tableRowPtr, typeof(MIB_UDPROW_OWNER_PID));
                    UdpProcessRecord     record = new UdpProcessRecord(new IPAddress(udpRow.localAddr),
                                                                       BitConverter.ToUInt16(new byte[2] {
                        udpRow.localPort[1], udpRow.localPort[0]
                    }, 0),
                                                                       udpRow.owningPid);
                    tableRowPtr = (IntPtr)((long)tableRowPtr + Marshal.SizeOf(udpRow));
                    activeUdpConnections.Add(record);
                }
            }

            catch (Exception ex)
            {
                Logger.Write("LookupForUdpConnectedProcesses(): " + ex.Message);
            }
            finally
            {
                Marshal.FreeHGlobal(udpTableRecordPtr);
            }

            return(activeUdpConnections?.Distinct().ToList <UdpProcessRecord>());
        }
Beispiel #41
0
        public async Task <IEnumerable <User> > GetUsersInRolesAsync(params string[] roleNames)
        {
            var users = new List <User>();

            if (roleNames?.Count() > 0)
            {
                foreach (var role in roleNames.Where(t => !string.IsNullOrWhiteSpace(t)))
                {
                    users.AddRange(await _userManager.GetUsersInRoleAsync(role));
                }
            }
            return(users?.Distinct()?.OrderBy(t => t.Id));
        }
Beispiel #42
0
        /// <summary>
        /// Returns the nodes that match this selector.
        /// </summary>
        /// <param name="nodes">Nodes to be searched.</param>
        /// <returns>The matching nodes.</returns>
        public IEnumerable <HtmlElementNode> Find(IEnumerable <HtmlNode> nodes)
        {
            List <HtmlElementNode> results = null;
            bool matchTopLevelNodes        = true;

            for (Selector selector = this; selector != null; selector = selector.ChildSelector)
            {
                results = new List <HtmlElementNode>();
                FindRecursive(nodes, selector, matchTopLevelNodes, true, results);
                nodes = results;
                matchTopLevelNodes = false;
            }
            return(results?.Distinct() ?? Enumerable.Empty <HtmlElementNode>());
        }
Beispiel #43
0
        public async Task LoadAsync()
        {
            var volunteers = await _httpClientService.GetListTAsync <Volunteer>("volunteer/getall");

            _highSchoolList = volunteers?.Select(h => h.HighSchool).ToList();
            var lastIndex = _highSchoolList?.Count != 0 || _highSchoolList?.Count == 1 ? _highSchoolList?.Count - 1 : 0;

            _highSchoolList.Insert((int)lastIndex, "Other");
            _highSchoolList = _highSchoolList?.Distinct().ToList();
            RaisePropertyChanged(nameof(HighSchoolList));
            _schools = await GetSchoolDtos(_httpClientService);

            RaisePropertyChanged(nameof(Schools));
        }
Beispiel #44
0
        /// <summary>
        /// Recursively searches the list of nodes and returns the nodes that match this
        /// selector.
        /// </summary>
        /// <param name="nodes">Nodes to search.</param>
        /// <returns>The matching nodes.</returns>
        public IEnumerable <HtmlElementNode> Find(IEnumerable <HtmlNode> nodes)
        {
            List <HtmlElementNode>?results = null;
            bool matchTopLevelNodes        = true;

            // Search from this selector on down through its child selectors
            for (Selector?selector = this; selector != null; selector = selector.ChildSelector)
            {
                results = new List <HtmlElementNode>();
                FindRecursive(nodes, selector, matchTopLevelNodes, true, results);
                // In next iteration, apply nodes that matched this iteration
                nodes = results;
                matchTopLevelNodes = false;
            }
            return(results?.Distinct() ?? Enumerable.Empty <HtmlElementNode>());
        }
        static void set_settingsFieldFullNames2SettingsFieldInfo()
        {
            lock (settingsFieldFullNames2SettingsFieldInfo)
            {
                ExplicitlyTrackedAssemblies = ExplicitlyTrackedAssemblies?.Distinct().ToList();
                if (AssemblyChainMaxLength < 1)
                {
                    throw new Exception("AssemblyChainMaxLength cannot be < 1");
                }

                if (settingsFieldFullNames2SettingsFieldInfo_is_set)
                {
                    //ExplicitlyTrackedAssemblies is the parameter that can change SettingsFieldInfo collection
                    if (lastExplicitlyTrackedAssemblies?.Count == ExplicitlyTrackedAssemblies?.Count)
                    {
                        if (ExplicitlyTrackedAssemblies == null)
                        {
                            return;
                        }
                        if (!lastExplicitlyTrackedAssemblies.Except(ExplicitlyTrackedAssemblies).Any() && !ExplicitlyTrackedAssemblies.Except(lastExplicitlyTrackedAssemblies).Any())
                        {
                            return;
                        }
                    }

                    //AssemblyChainMaxLength is the parameter that can change SettingsFieldInfo collection
                    if (lastAssemblyChainMaxLength == AssemblyChainMaxLength)
                    {
                        return;
                    }
                }
                settingsFieldFullNames2SettingsFieldInfo_is_set = true;
                lastExplicitlyTrackedAssemblies = ExplicitlyTrackedAssemblies;
                lastAssemblyChainMaxLength      = AssemblyChainMaxLength;

                foreach (SettingsFieldInfo settingsFieldInfo in getSettingsFieldInfos())
                {                                                                                          //SettingsFieldInfo's parameters for a Settings field are expected to be unchangable so no need to re-create it.
                    //!!!Exposing of SettingsFieldInfo to the custom code is one more reason not to re-create it.
                    if (!settingsFieldFullNames2SettingsFieldInfo.ContainsKey(settingsFieldInfo.FullName)) //!!!do not replace existing SettingsFieldInfo's
                    {
                        settingsFieldFullNames2SettingsFieldInfo[settingsFieldInfo.FullName] = settingsFieldInfo;
                    }
                }
            }
        }
Beispiel #46
0
        public void Write(ExtendedBinaryWriter writer)
        {
            writer.WriteOptArray(_alleleOrigins?.Distinct().ToArray(), writer.WriteOptAscii);
            writer.WriteOptAscii(SaAltAllele);
            writer.WriteOptAscii(ReferenceAllele);
            writer.WriteOptAscii(ID);
            writer.Write((byte)ReviewStatus);
            writer.WriteOptAscii(IsAlleleSpecific);
            writer.WriteOptArray(_medgenIds?.Distinct().ToArray(), writer.WriteOptAscii);
            writer.WriteOptArray(_omimIds?.Distinct().ToArray(), writer.WriteOptAscii);
            writer.WriteOptArray(_orphanetIds?.Distinct().ToArray(), writer.WriteOptAscii);

            writer.WriteOptArray(SupplementaryAnnotationUtilities.ConvertMixedFormatStrings(_phenotypes)?.Distinct().ToArray(), writer.WriteOptUtf8);
            writer.WriteOptAscii(Significance);

            writer.WriteOpt(LastUpdatedDate);
            writer.WriteOptArray(_pubmedIds.ToArray(), writer.WriteOpt);
        }
Beispiel #47
0
        /// <summary>
        /// 修饰数组
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <param name="Distinct">去重</param>
        /// <param name="ClearEmpty">去掉空值</param>
        /// <returns></returns>
        public static IEnumerable <T> Fixed <T>(this IEnumerable <T> list, bool Distinct = true, bool ClearEmpty = true)
        {
            List <T> res = new List <T>();

            list.ForEach(a =>
            {
                if (ClearEmpty && (a == null || string.IsNullOrWhiteSpace(a.ToString())))
                {
                    return;
                }
                res.Add(a);
            });
            if (Distinct)
            {
                res = res?.Distinct().ToList();
            }
            return(res);
        }
        public ActionResult AddAuthorsAjax(List <int> autorIds)
        {
            autorIds = autorIds?.Distinct()?.ToList() ?? new List <int>();
            var autors = db.Authors
                         .FilterByOwner(User)
                         .Where(a => autorIds.Contains(a.Id))
                         .ToList();
            var autorsOrdered = (from autorId in autorIds join o in autors on autorId equals o.Id select o).ToList();
            var other         = db.Authors.Include(a => a.Owner)
                                .FilterByOwner(User)
                                .Where(a => !autorIds.Contains(a.Id))
                                .OrderBy(a => a.RusSurname).ThenBy(a => a.RusInitials)
                                .ToList();
            var model = new ArticleAuthorsViewModel()
            {
                ArticleAuthors = autorsOrdered, AvailableAuthors = other
            };

            return(PartialView("AuthorList", model));
        }
Beispiel #49
0
        public static void ReadAlternativeDnsNames(Uri serverUri, X509Certificate2 cert)
        {
            try
            {
                if (AlternativeUris != null)
                {
                    return;
                }

                AlternativeUris = new List <Uri>();
                var dnsNames = new List <string>();
                var cnName   = cert.Subject?.Split(',')?.FirstOrDefault()?.Replace("CN=", "");
                if (cnName != null)
                {
                    dnsNames.Add(cnName);
                }
                var bytehosts = cert?.Extensions["2.5.29.17"] ?? null;
                if (bytehosts != null)
                {
                    var names = bytehosts.Format(false)?.Split(',', StringSplitOptions.RemoveEmptyEntries);
                    foreach (var name in names)
                    {
                        dnsNames.Add(name.Replace("DNS-Name=", "").Trim());
                    }
                }

                foreach (var dnsName in dnsNames)
                {
                    var uriBuilder = new UriBuilder(serverUri)
                    {
                        Host = dnsName
                    };
                    AlternativeUris.Add(uriBuilder.Uri);
                }
                AlternativeUris = AlternativeUris?.Distinct()?.ToList() ?? new List <Uri>();
            }
            catch (Exception ex)
            {
                logger.Error(ex, "The alternative dns names could´t not read.");
            }
        }
 /// <summary>
 /// 获取时间段内商品的活动信息列表
 /// </summary>
 /// <param name="pidList"></param>
 /// <param name="startTime"></param>
 /// <param name="endTime"></param>
 /// <returns></returns>
 public async Task <OperationResult <IEnumerable <ProductActivityInfoForTag> > > GetProductDiscountInfoForTagAsync(List <string> pidList, DateTime startTime, DateTime endTime)
 {
     if (!(pidList?.Count > 0))
     {
         return(OperationResult.FromError <IEnumerable <ProductActivityInfoForTag> >("1", "请传入商品pid"));
     }
     if (startTime == null || startTime == new DateTime())
     {
         return(OperationResult.FromError <IEnumerable <ProductActivityInfoForTag> >("2", "请传入活动开始时间"));
     }
     if (endTime == null || endTime == new DateTime())
     {
         return(OperationResult.FromError <IEnumerable <ProductActivityInfoForTag> >("3", "请传入活动结束时间"));
     }
     if (startTime >= endTime)
     {
         return(OperationResult.FromError <IEnumerable <ProductActivityInfoForTag> >("4", "开始时间应小于结束时间"));
     }
     pidList = pidList?.Distinct().ToList();
     return(await DiscountActivityInfoManager.GetProductDiscountInfoForTagAsync(pidList, startTime, endTime));
 }
Beispiel #51
0
        private List <int> RetornaDivisores(int numero)
        {
            List <int> divisores = new List <int>();

            divisores.Add(1);

            if (numero == 1)
            {
                return(divisores);
            }

            var query =
                from idx in ParallelEnumerable.Range(2, (numero / 2) + 1)
                where numero % idx == 0
                select idx;

            query.ForAll((num) => divisores.Add(num));
            divisores.Add(numero);

            return(divisores?.Distinct()?.OrderBy(x => x)?.ToList());
        }
Beispiel #52
0
        static void Main(string[] args)
        {
            var nullGmtIds = new List <long>
            {
                557,
                3463,
                5086,
                5645,
                10363,
                12198,
                38563,
                43441,
                55406,
                56152,
                60251,
                64150
            };

            //SaveUploadedImagesToDisk();
            RenameImageFiles();
            var dtStarted = DateTime.Now;

            using (var db = new borsvarldenContext())
                using (var dbMS = new borsvarlden_MSSql.borsvarldenContext())
                {
                    db.Database.SetCommandTimeout(30 * 60);//30 minutes
                    //  SaveUploadedImagesNew(db);
                    Console.WriteLine($"{DateTime.Now.ToString()} ================= Begin     ====================");
                    //db.GetService<ILoggerFactory>().AddProvider(new MyLoggerProvider());
                    // DbContextOptionsBuilder.EnableSensitiveDataLogging(true);

                    var uploadedImages = db.WpPosts.Where(x => x.PostType == "attachment").ToList();
                    var guids          = db.WpPostmeta.Where(x => x.MetaKey == "article_finwire_guid").ToList();
                    var imageSources   = db.WpPostmeta.Where(x => x.MetaKey == "article_imagesrc").ToList();

                    var metaAuthorsArticle = db.WpPostmeta
                                             .Where(x => x.MetaKey == "article_sponsored_company" || x.MetaKey == "article_aktuellt_deadline" ||
                                                    x.MetaKey == "article_prio_deadline" || x.MetaKey == "article_prio_position" ||
                                                    x.MetaKey == "article_sponsored").ToList();

                    var term = db.WpTermRelationships
                               .Join(db.WpTermTaxonomy.Where(p => p.Taxonomy == "article_socialtag" || p.Taxonomy == "article_company"),
                                     x => x.TermTaxonomyId, y => y.TermTaxonomyId,
                                     (x, y) => new { WpTermRelationships = x, WpTermTaxonomy = y })
                               .Join(db.WpTerms,
                                     x => x.WpTermTaxonomy.TermId, y => y.TermId,
                                     (x, y) => new { WpTermTaxonomy = x, WpTerms = y })
                               .Join(db.WpPosts.Where(u => !nullGmtIds.Contains(u.Id)),
                                     x => x.WpTermTaxonomy.WpTermRelationships.ObjectId,
                                     y => y.Id,
                                     (x, y) => new { WpTermRelationships = x, WpPosts = y })
                               .AsNoTracking()
                               .ToList();

                    var allSocialTags = term.FindAll(x =>
                                                     x.WpTermRelationships.WpTermTaxonomy.WpTermTaxonomy.Taxonomy == "article_socialtag")
                                        .Select(x => x.WpTermRelationships.WpTerms.Name)
                                        .Distinct()
                                        .Select(x => new FinwireSocialTags {
                        Tag = x
                    });

                    dbMS.FinwireSocialTags.AddRange(allSocialTags);

                    var allCompanies = term.FindAll(x =>
                                                    x.WpTermRelationships.WpTermTaxonomy.WpTermTaxonomy.Taxonomy == "article_company")
                                       .Select(x => x.WpTermRelationships.WpTerms.Name)
                                       .Distinct()
                                       .Select(x => new FinwireCompanies {
                        Company = x
                    });

                    dbMS.FinwireCompanies.AddRange(allCompanies);
                    dbMS.SaveChanges();

                    var posts = db.WpPosts
                                .Where(x => !nullGmtIds.Contains(x.Id) && x.PostType == "article" && x.PostStatus == "publish")
                                //.Where(x=>x.Id ==66289) //FOR DIAGNOTICS
                                .Join(db.WpPostmeta.Where(a => a.MetaKey == "_thumbnail_id"),
                                      post => post.Id, meta => meta.PostId,
                                      (post, meta) => new { Post = post, Meta = meta })
                                //.Take(2000) //FOR DIAGNOTICS
                                .AsNoTracking()
                                .ToList();

                    var files         = db.WpPostmeta.Where(b => b.MetaKey == "_wp_attached_file").AsNoTracking().ToList();
                    var articleLabels = db.WpPostmeta.Where(b => b.MetaKey == "article_label").AsNoTracking().ToList();

                    Console.WriteLine($"{DateTime.Now.ToString()} ================= Main transformation     ====================");

                    var listPosts = posts.Join(files,
                                               x => Convert.ToInt32(x.Meta.MetaValue),
                                               y => y.PostId,
                                               (x, y) => new { Post = x, Meta = y })
                                    .ToList();

                    var total = listPosts.Count;
                    int i     = 0;
                    //  db.ChangeTracker.AutoDetectChangesEnabled = false;

                    listPosts.ForEach(p =>
                    {
                        var r1 = term.FindAll(x => x.WpPosts.Id == p.Post.Post.Id);
                        var socialTagsAdded = new List <string>();
                        var companiesAdded  = new List <string>();

                        r1.ForEach(x =>
                        {
                            if (x.WpTermRelationships.WpTermTaxonomy.WpTermTaxonomy.Taxonomy == "article_socialtag")
                            {
                                var socialTag = new FinwireSocialTags {
                                    Tag = x.WpTermRelationships.WpTerms.Name
                                };
                                socialTagsAdded.Add(socialTag.Tag);
                            }
                            else if (x.WpTermRelationships.WpTermTaxonomy.WpTermTaxonomy.Taxonomy == "article_company")
                            {
                                var company = new FinwireCompanies {
                                    Company = x.WpTermRelationships.WpTerms.Name
                                };
                                companiesAdded.Add(company.Company);
                            }
                        });

                        /* var finwireXmlNewsAdded =  dbMS.FinwireXmlNews.Add(new FinwireXmlNews
                         * {
                         *   DateTime = DateTime.Now,
                         *   //FileContent =  .RoughXml,
                         *   FileName = p.Post.Post.Guid
                         * });*/

                        var customMainImage = uploadedImages.FirstOrDefault(x => x.PostParent == p.Post.Post.Id);

                        var newsEntityAdded = new FinwireNews()
                        {
                            IsConvertedFromMySql = true,
                            NewsText             = p.Post.Post.PostContent.ChangeImagePathInPost(),
                            Date             = p.Post.Post.PostDate,
                            ImageRelativeUrl = customMainImage != null ?  customMainImage.Guid.ChangeImagePathForTitle() :
                                               p.Meta.MetaValue.ToNewImageFilePath(),
                            Slug          = p.Post.Post.PostName,
                            FinautoPassed = true,
                            ImageLabel    = articleLabels.FirstOrDefault(x => x.PostId == p.Post.Post.Id)?.MetaValue,
                            Guid          = guids.FirstOrDefault(x => x.PostId == p.Post.Post.Id)?.MetaValue,
                            ImageSource   = imageSources.FirstOrDefault(x => x.PostId == p.Post.Post.Id)?.MetaValue
                        };

                        if (newsEntityAdded.Guid != null)
                        {
                            newsEntityAdded.IsFinwireNews = true;
                            newsEntityAdded.FinautoPassed = true;
                        }

                        (newsEntityAdded.Title, newsEntityAdded.Subtitle) =
                            p.Post.Post.PostTitle.SplitSubtitleAndNews();

                        var authorArticlesData = metaAuthorsArticle.Where(x => x.PostId == p.Post.Post.Id).ToList();

                        if (authorArticlesData.Count > 0)
                        {
                            newsEntityAdded.IsBorsvarldenArticle = true;
                            newsEntityAdded.PrioDeadLine         = Convert.ToDateTime(authorArticlesData.FirstOrDefault(x => x.MetaKey == "article_prio_deadline")?.MetaValue);
                            newsEntityAdded.ActualDeadLine       = Convert.ToDateTime(authorArticlesData.FirstOrDefault(x => x.MetaKey == "article_aktuellt_deadline")?.MetaValue);
                            newsEntityAdded.Order       = Convert.ToInt32(authorArticlesData.FirstOrDefault(x => x.MetaKey == "article_prio_position")?.MetaValue);
                            newsEntityAdded.CompanyName = authorArticlesData.FirstOrDefault(x => x.MetaKey == "article_sponsored_company")?.MetaValue;

                            if (newsEntityAdded.CompanyName != null)
                            {
                                newsEntityAdded.IsAdvertising = true;
                            }
                        }

                        dbMS.FinwireNews.Add(newsEntityAdded);
                        //todo make generic method in helper etc, find better solution using EF Core
                        socialTagsAdded?.Distinct().ToList().ForEach(x =>
                        {
                            dbMS.FinwireNew2FirnwireSocialTag.Add(new FinwireNew2FirnwireSocialTag
                            {
                                FinwireNew         = newsEntityAdded,
                                FinwireSocialTagId = (dbMS.FinwireSocialTags.Where(y => y.Tag == x)?.FirstOrDefault().Id).Value
                            });
                        }
                                                                     );

                        companiesAdded?.Distinct().ToList().ForEach(x =>
                        {
                            dbMS.FinwireNew2FinwireCompany.Add(new FinwireNew2FinwireCompany
                            {
                                FinwireNew       = newsEntityAdded,
                                FinwareCompanyId = (dbMS.FinwireCompanies.Where(y => y.Company == x)?.FirstOrDefault().Id).Value
                            });
                        }
                                                                    );

                        i++;

                        Console.WriteLine($"{Math.Round((DateTime.Now - dtStarted).TotalMinutes)} {i} / {total} - {Math.Round((double)i / total * 100)}%");
                    });
                    Console.WriteLine($"{DateTime.Now.ToString()} ================= Finish main transformation     ====================");
                    dbMS.SaveChanges();
                    Console.WriteLine($"{DateTime.Now.ToString()} ================= SAVED DATA. FINISHED     ====================");
                }
        }
Beispiel #53
0
        public async Task Executar(FiltroRelatorioDto request)
        {
            var filtros = request.ObterObjetoFiltro <FiltroRelatorioAtribuicaoCJDto>();

            var relatorio = new RelatorioAtribuicaoCjDto();

            await MontarCabecalho(relatorio, filtros.DreCodigo, filtros.UeCodigo, filtros.Modalidade,
                                  filtros.Semestre, filtros.TurmaCodigo, filtros.UsuarioRf,
                                  request.UsuarioLogadoRF);

            var lstAtribuicaoEsporadica = await mediator.Send(new ObterAtribuicoesEsporadicasPorFiltroQuery(filtros.AnoLetivo,
                                                                                                            filtros.UsuarioRf,
                                                                                                            filtros.DreCodigo,
                                                                                                            filtros.UsuarioRf,
                                                                                                            filtros.UeCodigo));

            var lstAtribuicaoCJ = await mediator.Send(new ObterAtribuicoesCJPorFiltroQuery()
            {
                AnoLetivo  = filtros.AnoLetivo,
                DreCodigo  = filtros.DreCodigo,
                UeId       = filtros.UeCodigo,
                UsuarioRf  = filtros.UsuarioRf,
                TurmaId    = filtros.TurmaCodigo,
                Modalidade = filtros.Modalidade,
                Semestre   = filtros.Semestre
            });

            var lstServidores = new List <string>();

            lstServidores.AddRange(lstAtribuicaoEsporadica.Select(s => s.ProfessorRf));
            lstServidores.AddRange(lstAtribuicaoCJ.Select(cj => cj.ProfessorRf));

            var lstServidoresArray = lstServidores?.Distinct().ToArray();

            var cargosServidores = await mediator.Send(new ObterCargosAtividadesPorRfQuery(lstServidoresArray));

            var lstProfServidorTitulares = await mediator.Send(new ObterProfessorTitularComponenteCurricularPorCodigosRfQuery(lstServidoresArray));

            if (filtros.ExibirAtribuicoesExporadicas)
            {
                AdicionarAtribuicoesEsporadicas(relatorio, lstAtribuicaoEsporadica, cargosServidores);
            }

            var turmasId = lstAtribuicaoCJ.Select(t => t.Turma.Codigo)?.Distinct().ToArray();

            var componentesId = lstAtribuicaoCJ.Select(t => t.ComponenteCurricularId.ToString())?.Distinct().ToArray();

            var lstProfTitulares = await mediator.Send(new ObterProfessorTitularComponenteCurricularPorTurmaQuery(turmasId));

            var aulas = Enumerable.Empty <AulaVinculosDto>();

            if (filtros.ExibirAulas)
            {
                aulas = await mediator.Send(new ObterAulaVinculosPorTurmaComponenteQuery(turmasId, componentesId, true));
            }

            AdicionarAtribuicoesCJ(relatorio, lstAtribuicaoCJ, lstProfTitulares, lstProfServidorTitulares, lstAtribuicaoEsporadica, cargosServidores, aulas,
                                   filtros.TipoVisualizacao, filtros.ExibirAulas, filtros.Modalidade);

            if (string.IsNullOrEmpty(filtros.DreCodigo) || string.IsNullOrEmpty(filtros.UeCodigo))
            {
                relatorio.ExibirDre = true;
                relatorio           = await mediator.Send(new AgruparRelatorioAtribuicaoCJPorDreUeQuery(relatorio));
            }

            OrdernarRelatorio(relatorio, filtros.TipoVisualizacao);

            await mediator.Send(new GerarRelatorioHtmlParaPdfCommand("RelatorioAtribuioesCj", relatorio, request.CodigoCorrelacao));
        }
        /// <summary>
        /// Metoden filtrerar sökresultatet.
        /// Om vi har flera matchande ord i sökningen så skall dessa tillsammans filtrera resltatet
        /// </summary>
        /// <param name="lsVehicles">List med alla vehicle som vi har fått matchning på</param>
        /// <param name="lsMatchedRegistrationnumbers">Registreringsnummer vi har fått matchning på</param>
        /// <param name="lsMatchedColors">Färger vi har fått matchning på</param>
        /// <param name="lsMatchedTypes">Typer som vi har fått matchning på</param>
        /// <param name="lsMatchedNumberOfWheels">Antal hjul som vi har fårr matchning på</param>
        /// <param name="lsMatchedNumberOfSeatedPassengers">Antal sittande passagerare som vi har fått matchning på</param>
        /// <returns>List med vehicle som har filtrerats</returns>
        private List <ICanBeParkedInGarage> FilterSearchResult(List <ICanBeParkedInGarage> lsVehicles, List <string> lsMatchedRegistrationnumbers, List <string> lsMatchedColors, List <string> lsMatchedTypes, List <int> lsMatchedNumberOfWheels, List <int> lsMatchedNumberOfSeatedPassengers)
        {
            List <ICanBeParkedInGarage> lsResultVehicles = null;

            if (lsVehicles?.Count > 0)
            {// Vi har hittat några vehicle som matchar något av orden som användaren har sökt på
                // Se till att alla dubbletter försvinner
                lsVehicles = lsVehicles.Distinct().ToList();

                // Nu måste jag kolla om vi har flera sökningar som skall matcha ett resultat
                List <ICanBeParkedInGarage> lsTmpVehicles = new List <ICanBeParkedInGarage>(lsVehicles.Count);

                if (lsMatchedRegistrationnumbers?.Count > 0)
                {// Vi har haft matchning på registreringsnummer. Filtrera bort alla som inte har registreringsnummer som har matchat
                    List <ICanBeParkedInGarage> lsTmpMatchedRegistrationnumbersVehicles = new List <ICanBeParkedInGarage>();
                    foreach (string str in lsMatchedRegistrationnumbers)
                    {
                        lsTmpMatchedRegistrationnumbersVehicles.AddRange(lsVehicles.Where(v => ((IVehicle)v).RegistrationNumber.Equals(str, StringComparison.OrdinalIgnoreCase)).ToList());
                    }

                    if (lsTmpMatchedRegistrationnumbersVehicles?.Count > 0)
                    {
                        lsTmpVehicles.AddRange(lsTmpMatchedRegistrationnumbersVehicles);
                    }
                }


                if (lsMatchedColors?.Count > 0)
                {// Vi har haft matchande färger. Filtrera bort alla som inte har sökt färg
                    List <ICanBeParkedInGarage> lsTmpMatchedColorsVehicles = new List <ICanBeParkedInGarage>();
                    foreach (string str in lsMatchedColors)
                    {
                        if (lsTmpVehicles?.Count > 0)    // Vi har tidigare filtreringar av vehicle. Använd den listan med vehicles
                        {
                            lsTmpMatchedColorsVehicles.AddRange(lsTmpVehicles.Where(v => ((IVehicle)v).Color.Equals(str, StringComparison.OrdinalIgnoreCase)).ToList());
                        }
                        else
                        {
                            lsTmpMatchedColorsVehicles.AddRange(lsVehicles.Where(v => ((IVehicle)v).Color.Equals(str, StringComparison.OrdinalIgnoreCase)).ToList());
                        }
                    }

                    if (lsTmpMatchedColorsVehicles?.Count > 0)
                    {
                        if (lsTmpVehicles?.Count == 0)
                        {
                            lsTmpVehicles.AddRange(lsTmpMatchedColorsVehicles);
                        }
                        else
                        {
                            lsTmpVehicles = lsTmpMatchedColorsVehicles;
                        }
                    }
                }


                if (lsMatchedTypes?.Count > 0)
                {// Vi har haft matchande typer av fordon. Filtrerar bort dom som inte har matchningar
                    List <ICanBeParkedInGarage> lsTmpMatchedTypesVehicles = new List <ICanBeParkedInGarage>();
                    foreach (string str in lsMatchedTypes)
                    {
                        if (lsTmpVehicles?.Count > 0)    // Vi har tidigare filtreringar av vehicle. Använd den listan med vehicles
                        {
                            lsTmpMatchedTypesVehicles.AddRange(lsTmpVehicles.Where(v => v.GetType().Name.Equals(str, StringComparison.OrdinalIgnoreCase)).ToList());
                        }
                        else
                        {
                            lsTmpMatchedTypesVehicles.AddRange(lsVehicles.Where(v => v.GetType().Name.Equals(str, StringComparison.OrdinalIgnoreCase)).ToList());
                        }
                    }

                    if (lsTmpMatchedTypesVehicles?.Count > 0)
                    {
                        if (lsTmpVehicles?.Count == 0)
                        {
                            lsTmpVehicles.AddRange(lsTmpMatchedTypesVehicles);
                        }
                        else
                        {
                            lsTmpVehicles = lsTmpMatchedTypesVehicles;
                        }
                    }
                }


                if (lsMatchedNumberOfWheels?.Count > 0)
                {// Vi har haft matchande antal hjul på fordon. Filtrerar bort dom som inte har matchningen
                    List <ICanBeParkedInGarage> lsTmpMatchedNumberOfWheelsVehicles = new List <ICanBeParkedInGarage>();
                    foreach (int number in lsMatchedNumberOfWheels)
                    {
                        if (lsTmpVehicles?.Count > 0)   // Vi har tidigare filtreringar av vehicle. Använd den listan med vehicles
                        {
                            lsTmpMatchedNumberOfWheelsVehicles.AddRange(lsTmpVehicles.Where(v => ((WheeledVehicle)v).NumberOfWheels == number).ToList());
                        }
                        else
                        {
                            lsTmpMatchedNumberOfWheelsVehicles.AddRange(lsVehicles.Where(v => ((WheeledVehicle)v).NumberOfWheels == number).ToList());
                        }
                    }

                    if (lsTmpMatchedNumberOfWheelsVehicles?.Count > 0)
                    {
                        if (lsTmpVehicles?.Count == 0)
                        {
                            lsTmpVehicles.AddRange(lsTmpMatchedNumberOfWheelsVehicles);
                        }
                        else
                        {
                            lsTmpVehicles = lsTmpMatchedNumberOfWheelsVehicles;
                        }
                    }
                }


                if (lsMatchedNumberOfSeatedPassengers?.Count > 0)
                {// Vi har haft matchande antal sittande passagerare. Filtrerar bort dom som inte har matchningen
                    List <ICanBeParkedInGarage> lsTmpMatchedNumberOfSeatedPassengersVehicles = new List <ICanBeParkedInGarage>();
                    foreach (int number in lsMatchedNumberOfSeatedPassengers)
                    {
                        if (lsTmpVehicles?.Count > 0)   // Vi har tidigare filtreringar av vehicle. Använd den listan med vehicles
                        {
                            lsTmpMatchedNumberOfSeatedPassengersVehicles.AddRange(lsTmpVehicles.Where(v => ((WheeledVehicle)v).NumberOfSeatedPassengers == number).ToList());
                        }
                        else
                        {
                            lsTmpMatchedNumberOfSeatedPassengersVehicles.AddRange(lsVehicles.Where(v => ((WheeledVehicle)v).NumberOfSeatedPassengers == number).ToList());
                        }
                    }

                    if (lsTmpMatchedNumberOfSeatedPassengersVehicles?.Count > 0)
                    {
                        if (lsTmpVehicles?.Count == 0)
                        {
                            lsTmpVehicles.AddRange(lsTmpMatchedNumberOfSeatedPassengersVehicles);
                        }
                        else
                        {
                            lsTmpVehicles = lsTmpMatchedNumberOfSeatedPassengersVehicles;
                        }
                    }
                }


                // Se till att alla dubbletter försvinner
                lsResultVehicles = lsTmpVehicles?.Distinct()?.ToList();
            }

            return(lsResultVehicles);
        }
Beispiel #55
0
 public List <String> getAtributeMList()
 {
     return(atributesModify.Distinct().ToList());
 }
Beispiel #56
0
        private static async Task ActivityChanged(ProcessActivityChangedEventArgs args, WorkflowRuntime runtime)
        {
            if (!args.TransitionalProcessWasCompleted)
            {
                return;
            }

            var historyModel = await MetadataToModelConverter.GetEntityModelByModelAsync("DocumentTransitionHistory");

            var emptyHistory = (await historyModel.GetAsync(Filter.And.Equal(Null.Value, "EmployeeId").Equal(args.ProcessId, "DocumentId")
                                                            .Equal(Null.Value, "TransitionTime"))).Select(h => h.GetId()).ToList();
            await historyModel.DeleteAsync(emptyHistory);

            await runtime.PreExecuteFromCurrentActivityAsync(args.ProcessId);

            var nextState     = WorkflowInit.Runtime.GetLocalizedStateName(args.ProcessId, args.ProcessInstance.CurrentState);
            var documentModel = await MetadataToModelConverter.GetEntityModelByModelAsync("Document");

            var document = (await documentModel.GetAsync(Filter.And.Equal(args.ProcessId, "Id"))).FirstOrDefault() as dynamic;

            if (document == null)
            {
                return;
            }

            document.StateName = nextState;
            document.State     = args.ProcessInstance.CurrentState;
            await documentModel.UpdateSingleAsync(document as DynamicEntity);

            var newActors = await Runtime.GetAllActorsForDirectCommandTransitionsAsync(args.ProcessId);

            var newInboxes = new List <dynamic>();

            foreach (var newActor in newActors)
            {
                var newInboxItem = new DynamicEntity() as dynamic;
                newInboxItem.Id         = Guid.NewGuid();
                newInboxItem.IdentityId = newActor;
                newInboxItem.ProcessId  = args.ProcessId;
                newInboxes.Add(newInboxItem);
            }

            var userIdsForNotification = new List <string>();

            userIdsForNotification.AddRange(newInboxes.Select(a => (string)(a as dynamic).IdentityId));

            using (var shared = new SharedTransaction())
            {
                await shared.BeginTransactionAsync();

                var inboxModel = await MetadataToModelConverter.GetEntityModelByModelAsync("WorkflowInbox");

                var existingInboxes = (await inboxModel.GetAsync(Filter.And.Equal(args.ProcessId, "ProcessId")));
                userIdsForNotification.AddRange(existingInboxes.Select(a => (string)(a as dynamic).IdentityId));
                var existingInboxesIds = existingInboxes.Select(i => i.GetId()).ToList();
                await inboxModel.DeleteAsync(existingInboxesIds);

                await inboxModel.InsertAsync(newInboxes);

                await shared.CommitAsync();
            }

            userIdsForNotification = userIdsForNotification.Distinct().ToList();
            Func <Task> task = async() => { await ClientNotifiers.NotifyClientsAboutInboxStatus(userIdsForNotification); };

            task.FireAndForgetWithDefaultExceptionLogger();
        }
Beispiel #57
0
        public ActionResult jobListingajax(int?page, string keyword = "", string city = "", string level = "", string time = "", string cat = "", string type = "")
        {
            DateTime today = DateTime.Now;
            int      span;

            int pageSize  = 10;
            int pageIndex = 1;

            pageIndex = page.HasValue ? Convert.ToInt16(page) : 1;
            var        predicate1 = PredicateBuilder.New <job>(true);
            var        predicate2 = PredicateBuilder.New <job>(true);
            List <job> job        = new List <Models.job>();

            if (!string.IsNullOrEmpty(keyword))
            {
                predicate1.And(p => p.title.Contains(keyword));
            }
            if (!string.IsNullOrEmpty(city))
            {
                predicate1.And(p => p.city.Contains(city));
            }
            if (!string.IsNullOrEmpty(level))
            {
                predicate1.And(p => p.job_level.Equals(level));
            }
            predicate1.And(a => a.status == 1);

            if (string.IsNullOrEmpty(keyword) && string.IsNullOrEmpty(level) && string.IsNullOrEmpty(city) && string.IsNullOrEmpty(time) && string.IsNullOrEmpty(cat) && string.IsNullOrEmpty(type))
            {
                if (Session["js_id"] != null)
                {
                    int    ssid   = Convert.ToInt16(Session["js_id"].ToString());
                    string skills = db.jobseeker_info.Where(a => a.js_id == ssid).Select(a => a.skills).First();
                    predicate2.And(a => a.status == 1);
                    if (skills != null)
                    {
                        foreach (var d in skills.Split(',').ToList())
                        {
                            job.AddRange(db.jobs.Where(a => a.status == 1 && a.skills.Contains(d)).ToList());
                        }
                    }
                    job.AddRange(db.jobs.Where(a => a.status == 1));
                    job = job.GroupBy(g => g.job_id).OrderByDescending(g => g.Count()).SelectMany(g => g).ToList();
                    job = job.Distinct().ToList();
                }
                else
                {
                    job = db.jobs.Where(predicate1).OrderByDescending(c => Guid.NewGuid()).ToList();
                }
            }
            else
            {
                job = db.jobs.Where(predicate1).OrderByDescending(c => Guid.NewGuid()).ToList();
            }
            // predicate1.And(a => a.submission_date > DateTime.Now);
            List <job_model> jobs      = new List <job_model>();
            List <job_model> temp      = new List <job_model>();
            List <job_model> jobsfinal = new List <job_model>();
            List <job_model> temptype  = new List <job_model>();

            foreach (var item in job)
            {
                job_model jobmodel = new job_model();
                jobmodel.category    = item.category.ToString();
                jobmodel.city        = item.city;
                jobmodel.created_at  = item.created_at;
                jobmodel.description = item.description;
                jobmodel.district    = item.district;
                jobmodel.job_level   = item.job_level;
                jobmodel.gender      = item.gender;
                jobmodel.salaryfrom  = item.salaryfrom;
                jobmodel.salaryto    = item.salaryto;
                jobmodel.experience  = item.experience;
                employer_info name = db.employer_info
                                     .Where(c => c.emp_id == item.employer)
                                     .SingleOrDefault();
                jobmodel.image           = name.logo;
                jobmodel.submission_date = item.submission_date;
                jobmodel.employer        = name.company_name;
                jobmodel.full_address    = item.full_address;
                jobmodel.state           = item.state;
                jobmodel.district        = item.district;
                jobmodel.job_id          = item.job_id;
                jobmodel.title           = item.title;
                jobmodel.job_type        = item.job_type;
                jobmodel.emp_id          = item.employer.HasValue ? Convert.ToInt32(item.employer) : 0;
                jobmodel.category        = db.job_categories.Find(Convert.ToInt32(item.category)).category_name.ToString();
                jobs.Add(jobmodel);
            }
            jobsfinal = jobs;
            var predicate = PredicateBuilder.New <job_model>(true);

            if (!string.IsNullOrEmpty(cat))
            {
                string[] cat_ = cat.Split(',');
                foreach (string item in cat_)
                {
                    int    item__ = Convert.ToInt16(item);
                    string name   = db.job_categories
                                    .Where(c => c.jobcat_id == item__)
                                    .Select(cc => cc.category_name)
                                    .SingleOrDefault().ToString();
                    predicate.Or(p => p.category.Equals(name));
                }
            }

            if (!string.IsNullOrEmpty(type))
            {
                string[] type_ = type.Split(',');
                foreach (var text in type_)
                {
                    predicate.Or(p => p.job_type.Contains(text));
                }
            }
            jobsfinal = jobsfinal.Where(predicate).ToList();

            if (!string.IsNullOrEmpty(time))
            {
                if (time == "all")
                {
                    span = 2500000;
                }
                else
                {
                    span = Convert.ToInt32(time);
                }
                foreach (var variable in jobsfinal.ToList())
                {
                    TimeSpan t    = (today - Convert.ToDateTime(variable.created_at));
                    double   days = t.TotalHours;
                    if (!(days <= span))
                    {
                        jobsfinal.Remove(variable);
                    }
                }
            }

            if (!string.IsNullOrEmpty(type) || !string.IsNullOrEmpty(cat) || !string.IsNullOrEmpty(time))
            {
                return(PartialView(jobsfinal.ToPagedList(pageIndex, pageSize)));
            }
            else
            {
                return(PartialView(jobsfinal.ToPagedList(pageIndex, pageSize)));
            }
        }
Beispiel #58
0
 public List <int> DefaultDistinct(List <int> items)
 {
     return(items?.Distinct()
            .ToList());
 }
Beispiel #59
0
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            EF.Options options = new EF.Extension().Options;

            // Ignore common unsupported array of primitive types
            modelBuilder
            .Ignore <int[]>()
            .Ignore <long[]>()
            .Ignore <Guid[]>()
            .Ignore <string[]>();

            // Ignore custom type
            var ignoreTypes = new List <Type>();

            if (options != null && options.Ignore != null && options.Ignore.Length > 0)
            {
                foreach (var type in options.Ignore)
                {
                    try
                    {
                        Type t = Type.GetType(type);
                        if (t != null)
                        {
                            ignoreTypes.Add(t);
                            modelBuilder.Ignore(t);
                        }
                    }
                    catch { }
                }
            }

            // JsonConvert: map field with text columun, serializing/deserializing value
            IEnumerable <Type> jsonConvertTypes = null;

            if (options != null && options.JsonConvert != null && options.JsonConvert.Length > 0)
            {
                jsonConvertTypes = options.JsonConvert.Select(_ => Type.GetType(_));
            }

            // Mappings
            var tKeys = new KeyValuePair <Type, int>[] {
                new KeyValuePair <Type, int>(typeof(IEntity <int>), 11),
                new KeyValuePair <Type, int>(typeof(IEntity <long>), 20),
                new KeyValuePair <Type, int>(typeof(IEntity <Guid>), 36),
                new KeyValuePair <Type, int>(typeof(IEntity <string>), 255)
            };

            foreach (KeyValuePair <Type, int> tKey in tKeys)
            {
                var types = Base.Util.GetAllTypesOf(tKey.Key)?.Where(t => t != null && !ignoreTypes?.Distinct().Any(i => i == t) == true);
                foreach (Type type in types)
                {
                    try
                    {
                        EF.Options.MappingConfig opt = (options?.Mappings ?? new List <EF.Options.MappingConfig>())
                                                       .FirstOrDefault(_ =>
                                                                       _.Name == type.Name &&
                                                                       (string.IsNullOrEmpty(_.NameSpace) || _.NameSpace == type.Namespace)
                                                                       );

                        // Map to db schema,table
                        var entityBuilder = modelBuilder.Entity(type);

                        // https://docs.microsoft.com/en-us/ef/core/what-is-new/ef-core-3.0/breaking-changes#totable-on-a-derived-type-throws-an-exception
                        // https://github.com/aspnet/EntityFrameworkCore/issues/11811
                        if (
                            type.BaseType == typeof(object)           // i.e. partial class
                            ||
                            type.BaseType == type                     // IEntity<T>
                            ||
                            type.BaseType?.BaseType == typeof(object) // i.e. Entity<T>
                            )
                        {
                            entityBuilder.ToTable(opt?.Table ?? type.Name, opt?.Schema ?? null);
                        }

                        // Map Id column
                        var idBuilder = entityBuilder.Property("Id").HasColumnName(opt?.IdColumnName ?? "Id")
                                        .IsUnicode(false)
                                        .HasMaxLength(tKey.Value)
                                        //.HasColumnType(tKey.Value)
                        ;

                        // https://github.com/aspnet/EntityFrameworkCore/issues/16814
                        if ((opt?.IdHasDefaultValue ?? true) == true)
                        {
                            idBuilder.HasDefaultValue();
                        }

                        // Map complex type (or interface) on a text column, serializing/deserializing value
                        if (jsonConvertTypes != null && jsonConvertTypes.Any())
                        {
                            foreach (var property in type.GetProperties()
                                     .Where(p => jsonConvertTypes
                                            .Any(jT => jT.IsInterface ? jT.IsAssignableFrom(p.PropertyType) : jT == p.PropertyType)
                                            )
                                     )
                            {
                                if (null == opt?.Properties?.FirstOrDefault(_ => _.Name == property.Name && _.JsonConvert.HasValue && _.JsonConvert.Value == false))
                                {
                                    entityBuilder.Property(property.Name).HasJsonConversion(property.PropertyType);
                                }
                            }
                        }

                        // Property based settings
                        if (opt?.Properties != null)
                        {
                            foreach (var p in opt.Properties.Where(_ => !string.IsNullOrEmpty(_.Name)))
                            {
                                // Ignore field
                                if (p.Ignore)
                                {
                                    entityBuilder.Ignore(p.Name);
                                }
                                else
                                {
                                    try
                                    {
                                        // Custom map
                                        if (!string.IsNullOrEmpty(p.Column))
                                        {
                                            entityBuilder.Property(p.Name).HasColumnName(p.Column);
                                        }
                                    }
                                    catch { }
                                }

                                // Map specific property on a text column, serializing/deserializing value
                                if (p.JsonConvert.HasValue && p.JsonConvert.Value == true)
                                {
                                    entityBuilder.Property(p.Name).HasJsonConversion(type.GetProperty(p.Name).PropertyType);
                                }

                                if (!string.IsNullOrEmpty(p.HasConversion))
                                {
                                    var _type = p.HasConversion.ToLower();
                                    if (_type == "json")
                                    {
                                        entityBuilder.Property(p.Name).HasJsonConversion(type.GetProperty(p.Name).PropertyType);
                                    }
                                    else
                                    {
                                        Type clrType = EF.Options.MappingConfig.PropertyConfig.ColumnClrTypeConversions.FirstOrDefault(_ => _.Name.ToLower() == _type);
                                        if (clrType != null)
                                        {
                                            entityBuilder.Property(p.Name).HasConversion(clrType);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    catch
                    {
                        throw;
                    }
                }
            }
        }
        private void ChatRefresh()
        {
            if (cUsers == null || nChatQueue == null)
            {
                return;
            }

            // 채팅 수집
            GetChat("return document.getElementById('chat_memoyo').innerHTML", "//dl");

            // 하단에 추가
            string html = string.Empty;

            var userJoinChats  = new List <ChatModel>();
            var tmpnChats      = new List <ChatModel>();
            var check          = new List <ChatModel>();
            var cChatQueueTemp = cChatQueue;

            // 접속 사용자 채팅만 가져오기
            userJoinChats = (from nChat in nChatQueue
                             join cUser in cUsers on nChat.ID equals cUser.ID
                             select nChat)?.ToList();

            // 기존 채팅 데이터 새 채팅에서 제외 후 중복 제거
            tmpnChats = (from nChat in userJoinChats
                         join cChat in cChatQueueTemp on new { nChat.ID, nChat.Html } equals new { cChat.ID, cChat.Html } into chat
                         from cChat in chat.DefaultIfEmpty()
                         where cChat is null
                         select nChat)?.Distinct()?.ToList();

            // 하... 중복제거 린큐로 하는거 실패해서 이걸로 다시 체크..

            foreach (var tt in tmpnChats)
            {
                if (check.Any(t => t.ID == tt.ID && t.Html == tt.Html))
                {
                    continue;
                }

                check.Add(tt);
            }

            if (ChkDisplayInOut.Checked && InChatUsersQueue != null && InChatUsersQueue.Count > 0)
            {
                var inUsers    = new List <UserModel>();
                var inUsersTmp = InChatUsersQueue.Dequeue();

                for (int Idx = 0; Idx < inUsersTmp.Count; Idx++)
                {
                    var user = inUsersTmp[Idx];
                    if (inUsers.Any(i => i.ID == user.ID) || inUsers.Any(i => i.Nic == user.Nic))
                    {
                        continue;
                    }

                    inUsers.Add(user);
                }

                foreach (var inUser in inUsers)
                {
                    html += string.Format(HtmlFormat.ChatHtmlInUser, inUser.ID, inUser.Nic);
                }
            }

            if (ChkDisplayInOut.Checked && OutChatUsersQueue != null && OutChatUsersQueue.Count > 0)
            {
                var outUsers = OutChatUsersQueue.Dequeue();
                foreach (var outUser in outUsers)
                {
                    html += string.Format(HtmlFormat.ChatHtmlOutUser, outUser.ID, outUser.Nic);
                }
            }

            //}

            // 채팅 추가
            foreach (var chat in check)
            {
                html += chat.Html;
                cChatQueue.Add(chat);
            }

            nChatQueue.Clear();
            cChatQueue = cChatQueue?.Distinct()?.ToList();

            SetChat(html);
        }