示例#1
0
        private IEnumerable <string> ExtractPlayers(IEnumerable <IReplay> replays, PlayerType playerType)
        {
            if (playerType == PlayerType.None)
            {
                return(Enumerable.Empty <string>());
            }

            var playerList = new HashSet <string>();

            foreach (var replay in replays)
            {
                var players = GetPlayers(playerType, replay);

                foreach (var player in replay.Players)
                {
                    if (playerList.Contains(player.Name))
                    {
                        continue;
                    }

                    playerList.Add(player.Name);
                }
            }

            return(playerList.AsEnumerable());
        }
 public IEnumerable <Customer> GetAll()
 {
     lock (_customers)
     {
         return(_customers.AsEnumerable());
     }
 }
        public static IEnumerable <string> GetItemDependencies(dynamic response)
        {
            var dependencies = new HashSet <string>();

            if (!IsItemResponse(response))
            {
                return(dependencies);
            }

            var codename = response.Item?.System?.Codename?.ToString();

            if (codename != null)
            {
                var dependencyKey = GetItemDependencyKey(codename);
                dependencies.Add(dependencyKey);
            }

            foreach (var modularItem in response.LinkedItems)
            {
                if (modularItem is JProperty property && !IsComponent(property))
                {
                    var linkedItemCodename = property.Value?["system"]?["codename"]?.Value <string>();
                    if (linkedItemCodename != null)
                    {
                        var dependencyKey = GetItemDependencyKey(linkedItemCodename);
                        dependencies.Add(dependencyKey);
                    }
                }
            }


            return(dependencies.Count > MAX_DEPENDENCY_ITEMS
                ? new[] { GetItemsDependencyKey() }
                : dependencies.AsEnumerable());
        }
示例#4
0
        public List <Activity> GetActivities(HashSet <string> ids, string appId, HashSet <String> fields, HashSet <String> activityIds)
        {
            var activities = db.activities
                             .OrderByDescending(x => x.id)
                             .Where(x => ids.AsEnumerable().Contains(x.person_id.ToString()) && (string.IsNullOrEmpty(appId) ? true : x.app_id.ToString() == appId));

            List <Activity> actList = new List <Activity>();

            if (activityIds != null)
            {
                foreach (var row in activities)
                {
                    if (activityIds.Contains(row.id.ToString()))
                    {
                        var act = new Activity(row.id.ToString(), row.person_id.ToString());
                        act.streamTitle = "activities";
                        act.title       = row.title;
                        act.body        = row.body;
                        act.postedTime  = row.created;
                        act.mediaItems  = GetMediaItems(row.id.ToString());
                        actList.Add(act);
                    }
                }
            }
            return(actList);
        }
示例#5
0
        public List <Activity> GetActivities(HashSet <string> ids, string appId, HashSet <String> fields, CollectionOptions options)
        {
            var activities = db.activities
                             .OrderByDescending(x => x.id)
                             .Where(x => ids.AsEnumerable().Contains(x.person_id.ToString()) && (string.IsNullOrEmpty(appId)?true:x.app_id.ToString() == appId));

            int first = options.getFirst();
            int max   = options.getMax();

            if (first != 0)
            {
                activities = activities.Skip(first);
            }
            if (max != 0)
            {
                activities = activities.Take(max);
            }
            List <Activity> actList = new List <Activity>();

            foreach (var row in activities)
            {
                var act = new Activity(row.id.ToString(), row.person_id.ToString());
                act.streamTitle = "activities";
                act.title       = row.title;
                act.body        = row.body;
                act.postedTime  = row.created;
                act.mediaItems  = GetMediaItems(row.id.ToString());
                actList.Add(act);
            }
            return(actList);
        }
示例#6
0
        private IEnumerable <string> RecurseGetAvailableWordsForWord(string upTiles)
        {
            var words = new HashSet <string>();

            for (int i = 0; i < upTiles.Length; i++)
            {
                string subTiles = upTiles.Remove(i, 1);
                if (subTiles.Length > 2)
                {
                    if (_tilesCache.TryGetValue(subTiles, out var subTileWords))
                    {
                        foreach (var w in subTileWords)
                        {
                            words.Add(w);
                        }
                    }
                    else
                    {
                        var availWords = RecurseGetAvailableWordsForWord(subTiles);

                        var allWords = new List <string>();
                        allWords.AddRange(availWords);
                        allWords.AddRange(GetAvailableWordsFromTrie(subTiles));

                        _tilesCache[subTiles] = allWords;
                        foreach (var w in allWords)
                        {
                            words.Add(w);
                        }
                    }
                }
            }

            return(words.AsEnumerable());
        }
        public void hash() {
            decimal beløb1 = 11.5M;

            decimal beløb2 = beløb1 / 3M;

            beløb2 *= 3M;

            /*
            True
            40270000
            BFD9000F
            True
            False
            False
            True*/

            Console.WriteLine(beløb1 == beløb2); // (A)

            Console.WriteLine(beløb1.GetHashCode().ToString("X8")); // (B)

            Console.WriteLine(beløb2.GetHashCode().ToString("X8")); // (C)

            var list = new List<decimal> { beløb1, };

            Console.WriteLine(list.Contains(beløb2)); // (D)

            var mgd = new HashSet<decimal> { beløb1, };

            Console.WriteLine(mgd.Contains(beløb2)); // (E)

            Console.WriteLine(mgd.AsEnumerable().Contains(beløb2)); // (F)

            Console.WriteLine(mgd.Where(d => true).Contains(beløb2)); // (G)

        }
        public static IEnumerable <string> GetItemJsonDependencies(JObject response)
        {
            var dependencies = new HashSet <string>();

            if (IsItemResponse(response))
            {
                if (TryExtractCodename(response["item"] as JObject, out var codename))
                {
                    var dependencyKey = GetItemDependencyKey(codename);
                    dependencies.Add(dependencyKey);
                }

                foreach (var property in response["modular_content"]?.Children <JProperty>() ?? Enumerable.Empty <JProperty>())
                {
                    if (!IsComponent(property) && TryExtractCodename(property.Value as JObject, out var linkedItemCodename))
                    {
                        var dependencyKey = GetItemDependencyKey(linkedItemCodename);
                        dependencies.Add(dependencyKey);
                    }
                }
            }

            return(dependencies.Count > MAX_DEPENDENCY_ITEMS
                ? new[] { GetItemsDependencyKey() }
                : dependencies.AsEnumerable());

            bool TryExtractCodename(JObject item, out string codename)
            {
                codename = item?["system"]?["codename"]?.Value <string>();
                return(codename != null);
            }
        }
示例#9
0
 public bool CopySave(out string Err, MySqlConnection ConX)
 {
     Err = "";
     try
     {
         var ids = new HashSet <int>();
         ids.Add(this.CopyingFromID);
         foreach (var ct in this.ChildTemplates ?? new Templates())
         {
             ids.Add(ct.TemplateID);
         }
         this.LoadChildTemplates(ref ids, this);
         var srcIDs  = new List <int>();
         var destIDs = new Dictionary <int, int>();
         foreach (var srcID in ids.AsEnumerable().Reverse().ToList())
         {
             srcIDs.Add(srcID);
             destIDs.Add(srcID, -1);
         }
         foreach (int srcID in srcIDs)
         {
             Template t;
             if (srcID == this.CopyingFromID)
             {
                 t = this;
             }
             else
             {
                 t = Template.Load(srcID);
             }
             t.GetIDFromDescription(ConX);
             foreach (var ct in t.ChildTemplates ?? new Templates())
             {
                 ct.TemplateID = destIDs[ct.TemplateID];
             }
             bool success;
             if (t.TemplateID <= 0)
             {
                 success = t.Create(out Err, ConX);
             }
             else
             {
                 success = t.Update(out Err, ConX);
             }
             destIDs[srcID] = t.TemplateID;
             if (!success)
             {
                 return(false);
             }
         }
         return(true);
     }
     catch (Exception ex)
     {
         Err = ex.Message;
         return(false);
     }
 }
示例#10
0
        public override IEnumerable <IFuzzyOption> Children(IFuzzyOption parent, bool ordered)
        {
            if (parent is NamespaceOption namespaceOption)
            {
                var @namespace = namespaceOption.value;

                if ([email protected])
                {
                    var childNamespaces = Enumerable.Empty <Namespace>();
                    if (namespacesInNamespace.TryGetValue(@namespace, out var foundNamespaces))
                    {
                        childNamespaces = foundNamespaces;
                    }

                    if (ordered)
                    {
                        childNamespaces = childNamespaces.OrderBy(ns => ns.DisplayName(false));
                    }

                    foreach (var childNamespace in childNamespaces)
                    {
                        yield return(new NamespaceOption(childNamespace, FuzzyOptionMode.Branch));
                    }
                }

                var childTypes = Enumerable.Empty <Type>();
                if (typesInNamespace.TryGetValue(@namespace, out var foundTypes))
                {
                    childTypes = foundTypes;
                }

                if (ordered)
                {
                    childTypes = childTypes.OrderBy(t => t.DisplayName());
                }

                foreach (var type in childTypes)
                {
                    yield return(new TypeOption(type, FuzzyOptionMode.Leaf));
                }
            }
            else if (parent.value == enumsGroup)
            {
                var childTypes = enumTypes.AsEnumerable();

                if (ordered)
                {
                    childTypes = childTypes.OrderBy(t => t.DisplayName());
                }

                foreach (var type in childTypes)
                {
                    yield return(new TypeOption(type, FuzzyOptionMode.Leaf));
                }
            }
        }
示例#11
0
        public static IEnumerable <Apartment> Union(this IEnumerable <Apartment> first, IEnumerable <Apartment> second)
        {
            HashSet <Apartment> apartments = new HashSet <Apartment>(first);

            foreach (Apartment item in second)
            {
                apartments.Add(item);
            }
            return(apartments.AsEnumerable().ToArray());
        }
示例#12
0
        public bool DeleteActivities(string userId, string appId, HashSet <string> activityIds)
        {
            var res =
                db.activities.Where(
                    x => activityIds.AsEnumerable().Contains(x.id.ToString()) && x.person_id.ToString() == userId && x.app_id.ToString() == appId);

            db.activities.DeleteAllOnSubmit(res);
            db.SubmitChanges();
            return(db.GetChangeSet().Deletes.Count == 0);
        }
示例#13
0
        public IHttpActionResult Vendors()
        {
            var vendors = _purchasingService.GetVendors();
            ICollection<VendorDto> vendorsDto = new HashSet<VendorDto>();

            foreach (var vendor in vendors)
                vendorsDto.Add(new VendorDto() { Id = vendor.Id, Name = vendor.Name });

            return Ok(vendorsDto.AsEnumerable());
        }
示例#14
0
        public IHttpActionResult Accounts()
        {
            var accounts = _financialService.GetAccounts();
            ICollection<AccountDto> accountsDto = new HashSet<AccountDto>();

            foreach (var account in accounts)
                accountsDto.Add(new AccountDto() { Id = account.Id, AccountName = account.AccountName });

            return Ok(accountsDto.AsEnumerable());
        }
示例#15
0
        public IHttpActionResult Customers()
        {
            var customers = _salesService.GetCustomers();
            ICollection<CustomerDto> customersDto = new HashSet<CustomerDto>();
            
            foreach (var customer in customers)
                customersDto.Add(new CustomerDto() { Id = customer.Id, Name = customer.Name });

            return Ok(customersDto.AsEnumerable());
        }
示例#16
0
        /// <summary>
        /// Extract only domain names from remaining links
        /// </summary>
        public IEnumerable <string> ExtractDomainNames(IEnumerable <string> links)
        {
            var uniqeLinks = new HashSet <string>();

            foreach (var link in links)
            {
                uniqeLinks.Add(ExtractDomainName(link));
            }

            return(uniqeLinks.AsEnumerable());
        }
示例#17
0
        public IHttpActionResult Contacts()
        {
            var contacts = _salesService.GetContacts();

            ICollection<ContactDto> contactsDto = new HashSet<ContactDto>();

            foreach (var contact in contacts)
                contactsDto.Add(new ContactDto() { Id = contact.Id,  FirstName = contact.FirstName, LastName = contact.LastName });

            return Ok(contactsDto.AsEnumerable());
        }
示例#18
0
 public void SetTestBeforLoad(HashSet <string> tests)
 {
     if (tests != null && tests.Count > 0)
     {
         this.TestsBeforLoad = new List <string>();
         var list = tests.AsEnumerable();
         for (int i = tests.Count - 1; i > -1; i -= 1)
         {
             this.TestsBeforLoad.Add(list.ElementAt(i));
         }
     }
 }
示例#19
0
        public bool simular(String regex, Automata automata)
        {
            Estado inicial = automata.getEstadoInicial();
            LinkedList <Estado> estados    = automata.getEstados();
            LinkedList <Estado> aceptacion = new LinkedList <Estado>(automata.getEstadosAceptacion());

            HashSet <Estado> conjunto = eClosure(inicial);

            foreach (char ch in regex.ToCharArray())
            {
                conjunto = move(conjunto, ch.ToString());
                HashSet <Object>     temp = new HashSet <Object>();
                IEnumerable <Estado> iter = conjunto.AsEnumerable();
                int a = 0;
                while (iter.Any())
                {
                    Estado siguiente = iter.ElementAt(a);

                    /**
                     * En esta parte es muy importante el metodo addAll
                     * porque se tiene que agregar el eClosure de todo el conjunto
                     * resultante del move y se utiliza un hashSet temporal porque
                     * no se permite la mutacion mientras se itera
                     */
                    temp.Add(eClosure(siguiente));
                    a++;
                }
                //conjunto = temp;
            }


            bool res = false;

            foreach (Estado estado_aceptacion in aceptacion)
            {
                if (conjunto.Contains(estado_aceptacion))
                {
                    res = true;
                }
            }
            if (res)
            {
                //System.out.println("Aceptado");
                //this.resultado = "Aceptado";
                return(true);
            }
            else
            {
                //System.out.println("NO Aceptado");
                // this.resultado = "No Aceptado";
                return(false);
            }
        }
示例#20
0
 private async void UsersChanged(IEnumerable <long> userIds)
 {
     if (!_members.SyncSet(userIds))
     {
         return;
     }
     if (_receiver.ListId != null)
     {
         await ListProxy.SetListMembers(_receiver.ListId.Value, _members);
     }
     ListMemberChanged?.Invoke(this, Tuple.Create(_listParam, _members.AsEnumerable()));
 }
示例#21
0
        public IEnumerable <ManagedCoroutine> GetAll()
        {
            HashSet <ManagedCoroutine> all = new HashSet <ManagedCoroutine>();

            var values = coroutines.Values;

            foreach (var value in values)
            {
                all.Concat(value);
            }

            return(all.AsEnumerable());
        }
示例#22
0
        protected virtual string Build(HashSet <string> headers, HashSet <string> bodySchema)
        {
            HashSet <string> result = new HashSet <string>();

            result.UnionWith(headers);
            result.Add($"{Environment.NewLine+Environment.NewLine}");
            result.UnionWith(bodySchema);


            string schemaResult = String.Join(Environment.NewLine, result.AsEnumerable());

            return(schemaResult);
        }
示例#23
0
        public IEnumerable <Item> Get()
        {
            var results = new HashSet <Item>(new ItemComparer());

            // re-init DocumentClient for each GET
            // just in case
            Console.WriteLine("First Read");
            ExecuteQuery(primaryClient, results);
            Console.WriteLine("Second");
            ExecuteQuery(secondaryClient, results);

            return(results.AsEnumerable <Item>());
        }
示例#24
0
        public static IEnumerable <T> NoDup <T>(this IEnumerable <T> l)
        {
            HashSet <T> dict = new HashSet <T>();

            foreach (var v in l)
            {
                if (!dict.Contains(v))
                {
                    dict.Add(v);
                }
            }

            return(dict.AsEnumerable());
        }
示例#25
0
        public IHttpActionResult ItemTaxGroups()
        {
            var itemtaxgroups = _financialService.GetItemTaxGroups();
            ICollection <ItemTaxGroupDto> itemtaxgroupsDto = new HashSet <ItemTaxGroupDto>();

            foreach (var itemtaxgroup in itemtaxgroups)
            {
                itemtaxgroupsDto.Add(new ItemTaxGroupDto()
                {
                    Id = itemtaxgroup.Id, Name = itemtaxgroup.Name
                });
            }

            return(Ok(itemtaxgroupsDto.AsEnumerable()));
        }
示例#26
0
        private static Task <IEnumerable <MethodDescriptor> > GetMainMethodsAsync(Compilation compilation)
        {
            var result = new HashSet <MethodDescriptor>();
            var cancellationTokenSource = new CancellationTokenSource();
            var mainMethod = compilation.GetEntryPoint(cancellationTokenSource.Token);

            if (mainMethod != null)
            {
                // only return if there's a main method
                var methodDescriptor = Utils.CreateMethodDescriptor(mainMethod);
                result.Add(methodDescriptor);
            }

            return(Task.FromResult(result.AsEnumerable()));
        }
示例#27
0
        public IEnumerable <TVertex> AdjacentVertices([NotNull] TVertex vertex)
        {
            IEnumerable <TEdge> adjacentEdges = AdjacentEdges(vertex);
            var adjacentVertices = new HashSet <TVertex>();

            foreach (TEdge edge in adjacentEdges)
            {
                adjacentVertices.Add(edge.Source);
                adjacentVertices.Add(edge.Target);
            }

            adjacentVertices.Remove(vertex);

            return(adjacentVertices.AsEnumerable());
        }
示例#28
0
 public static IEnumerable <TSource> SafeFilter <TSource, TKey>
     (this IQueryable <TSource> source,
     Expression <Func <TSource, TKey> > keySelector,
     HashSet <TKey> filterSet,
     int threshold = 500)
 {
     if (filterSet.Count > threshold)
     {
         var selector = keySelector.Compile();
         return(source.AsEnumerable()
                .Where(x => filterSet.Contains(selector(x)))); //In memory
     }
     return(source.Where(keySelector.Compose(
                             key => filterSet.AsEnumerable().Contains(key)))); //In SQL
 }
示例#29
0
        public IHttpActionResult Items()
        {
            var items = _inventoryService.GetAllItems();
            ICollection <ItemDto> itemsDto = new HashSet <ItemDto>();

            foreach (var item in items)
            {
                itemsDto.Add(new ItemDto()
                {
                    No = item.No, Description = item.Description
                });
            }

            return(Ok(itemsDto.AsEnumerable()));
        }
示例#30
0
        public IHttpActionResult Accounts()
        {
            var accounts = _financialService.GetAccounts();
            ICollection <AccountDto> accountsDto = new HashSet <AccountDto>();

            foreach (var account in accounts)
            {
                accountsDto.Add(new AccountDto()
                {
                    Id = account.Id, AccountName = account.AccountName
                });
            }

            return(Ok(accountsDto.AsEnumerable()));
        }
示例#31
0
        public IHttpActionResult ItemCategories()
        {
            var itemcategories = _inventoryService.GetItemCategories();
            ICollection <ItemCategoryDto> itemcategoriesDto = new HashSet <ItemCategoryDto>();

            foreach (var itemcategory in itemcategories)
            {
                itemcategoriesDto.Add(new ItemCategoryDto()
                {
                    Id = itemcategory.Id, Name = itemcategory.Name
                });
            }

            return(Ok(itemcategoriesDto.AsEnumerable()));
        }
示例#32
0
        public IHttpActionResult Vendors()
        {
            var vendors = _purchasingService.GetVendors();
            ICollection <VendorDto> vendorsDto = new HashSet <VendorDto>();

            foreach (var vendor in vendors)
            {
                vendorsDto.Add(new VendorDto()
                {
                    Id = vendor.Id, Name = vendor.Party.Name
                });
            }

            return(Ok(vendorsDto.AsEnumerable()));
        }
示例#33
0
        public static IEnumerable <string> GetDistinctTokens(string noteContents)
        {
            string[] tokens = noteContents.ToLowerInvariant().Split(new char[] { ' ', '\r', '\n', ',', ';', '.', '!', '\'', '"', '+', '(', ')', '?', '' }); // contains invisible char
            // de-dupe
            HashSet <string> uniqueTokens = new HashSet <string>();

            foreach (string token in tokens)
            {
                if (!stopWords.Contains(token))
                {
                    uniqueTokens.Add(token);
                }
            }
            return(uniqueTokens.AsEnumerable());
        }
示例#34
0
        public IHttpActionResult Customers()
        {
            var customers = _salesService.GetCustomers();
            ICollection <CustomerDto> customersDto = new HashSet <CustomerDto>();

            foreach (var customer in customers)
            {
                customersDto.Add(new CustomerDto()
                {
                    Id = customer.Id, Name = customer.Party.Name
                });
            }

            return(Ok(customersDto.AsEnumerable()));
        }
示例#35
0
        public IHttpActionResult Contacts()
        {
            var contacts = _salesService.GetContacts();

            ICollection <ContactDto> contactsDto = new HashSet <ContactDto>();

            foreach (var contact in contacts)
            {
                contactsDto.Add(new ContactDto()
                {
                    Id = contact.Id, FirstName = contact.FirstName, LastName = contact.LastName
                });
            }

            return(Ok(contactsDto.AsEnumerable()));
        }
示例#36
0
 /// <summary>
 /// Enumerates the normalized versions of all of the variables that occur in this 
 /// formula.  No normalization may appear more than once in the enumeration, even 
 /// if it appears more than once in this Formula.
 /// 
 /// For example, if N is a method that converts all the letters in a string to upper case:
 /// 
 /// new Formula("x+y*z", N, s => true).GetVariables() should enumerate "X", "Y", and "Z"
 /// new Formula("x+X*z", N, s => true).GetVariables() should enumerate "X" and "Z".
 /// new Formula("x+X*z").GetVariables() should enumerate "x", "X", and "z".
 /// </summary>
 public IEnumerable<String> GetVariables()
 {
     HashSet<string> variables = new HashSet<string>();
     List<string> tokens = GetTokens(originalFormula).ToList();
     foreach (string s in tokens)
     {
         if (varCheckFirst.Contains(s.ElementAt(0)))
         {
             if (isValid(normalize(s)))
                 variables.Add(normalize(s));
         }
     }
     return variables.AsEnumerable();
 }
示例#37
0
        public Tuple<IEnumerable<int>, FunctionPerfData> GetCorrections(string word)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            FunctionPerfData fpd = new FunctionPerfData();

            #region Get corrections with edit distance 1
            FunctionPerfData stagePerfData = new FunctionPerfData();
            fpd.StagesPerfData.Add("GetCandidates1", stagePerfData);
            HashSet<int> ret = new HashSet<int>();
            Stopwatch sws = new Stopwatch();
            sws.Start();
            List<CandidateWord> candidates = GetCorrectionsWithEditDistanceOne(new CandidateWord(word, 0)).ToList();
            sws.Stop();
            stagePerfData.TimeTaken = sws.ElapsedMilliseconds;
            stagePerfData.OtherData.Add("Num Actual Candidates", candidates.Count);
            stagePerfData.OtherData.Add("Num Candidates Formula", "52N + 25");
            stagePerfData.OtherData.Add("Num Candidates by Formula", (52 * word.Length + 25));
            #endregion
            #region Get corrections with edit distance 2
            sws = new Stopwatch();
            sws.Start();
            stagePerfData = new FunctionPerfData();
            fpd.StagesPerfData.Add("GetCandidates2", stagePerfData);
            List<CandidateWord> copy = new List<CandidateWord>(candidates);
            foreach (CandidateWord c in copy)
            {
                candidates.AddRange(GetCorrectionsWithEditDistanceOne(c));
            }
            sws.Stop();
            stagePerfData.TimeTaken = sws.ElapsedMilliseconds;
            stagePerfData.OtherData.Add("Num Actual Candidates", candidates.Count);
            stagePerfData.OtherData.Add("Num Candidates Formula", "(52N + 25)(52N + 25)");
            stagePerfData.OtherData.Add("Num Candidates by Formula", (52 * word.Length + 25) * (52 * word.Length + 25));
            #endregion

            #region Get unique candidates
            sws = new Stopwatch();
            sws.Start();
            stagePerfData = new FunctionPerfData();
            fpd.StagesPerfData.Add("GetCandidatesUnique", stagePerfData);
            //HashSet<string> hs = new HashSet<string>(candidates.Select(x => x.Word));
            IEnumerable<string> hs = candidates.Select(x => x.Word).Distinct();
            stagePerfData.OtherData.Add("Unique Candidates", hs.Count());
            sws.Stop();
            stagePerfData.TimeTaken = sws.ElapsedMilliseconds;
            #endregion

            #region Filter valid candidates
            sws = new Stopwatch();
            sws.Start();
            stagePerfData = new FunctionPerfData();
            fpd.StagesPerfData.Add("FilterValidCandidates", stagePerfData);
            foreach(string c in hs)
            {
                var positions = this.FindWord(c);
                if(positions.Any())
                {
                    ret.Add(positions.First());
                }
            }
            sws.Stop();
            stagePerfData.TimeTaken = sws.ElapsedMilliseconds;
            #endregion

            fpd.TimeTaken = sw.ElapsedMilliseconds;
            return new Tuple<IEnumerable<int>,FunctionPerfData>(ret.AsEnumerable(), fpd);
        }
示例#38
0
 public bool DeleteActivities(string userId, string appId, HashSet<string> activityIds) 
 {
     var res =
         db.activities.Where(
             x => activityIds.AsEnumerable().Contains(x.id.ToString()) && x.person_id.ToString() == userId && x.app_id.ToString() == appId);
     db.activities.DeleteAllOnSubmit(res);
     db.SubmitChanges();
     return (db.GetChangeSet().Deletes.Count == 0);
 }
        /// <summary>
        /// Given a set of content templates, is capable of returning their 
        /// </summary>
        /// <param name="contentTemplates"></param>
        /// <returns></returns>
        private IEnumerable<string> GetUniqueContentCategories(IEnumerable<IContentTemplate> contentTemplates)
        {
            var categorySet = new HashSet<string>();

            foreach (var template in contentTemplates)
            {
                if (!string.IsNullOrEmpty(template.VirtualCategory))
                    categorySet.Add(template.VirtualCategory);
            }

            return categorySet.AsEnumerable();
        }
示例#40
0
        public List<Activity> GetActivities(HashSet<string> ids, string appId, HashSet<String> fields, CollectionOptions options) 
        {
            var activities = db.activities
                .OrderByDescending(x => x.id)
                .Where(x => ids.AsEnumerable().Contains(x.person_id.ToString()) && (string.IsNullOrEmpty(appId)?true:x.app_id.ToString() == appId));

            int first = options.getFirst();
            int max = options.getMax();
            if (first != 0)
            {
                activities = activities.Skip(first);
            }
            if (max != 0)
            {
                activities = activities.Take(max);
            }
            List<Activity> actList = new List<Activity>();
            foreach (var row in activities)
            {
                var act = new Activity(row.id.ToString(), row.person_id.ToString());
                act.streamTitle = "activities";
                act.title = row.title;
                act.body = row.body;
                act.postedTime = row.created;
                act.mediaItems = GetMediaItems(row.id.ToString());
                actList.Add(act);
            }
            return actList;
        }
示例#41
0
        public IHttpActionResult ItemTaxGroups()
        {
            var itemtaxgroups = _financialService.GetItemTaxGroups();
            ICollection<ItemTaxGroupDto> itemtaxgroupsDto = new HashSet<ItemTaxGroupDto>();

            foreach (var itemtaxgroup in itemtaxgroups)
                itemtaxgroupsDto.Add(new ItemTaxGroupDto() { Id = itemtaxgroup.Id, Name = itemtaxgroup.Name });

            return Ok(itemtaxgroupsDto.AsEnumerable());
        }
示例#42
0
        public IHttpActionResult Items()
        {
            var items = _inventoryService.GetAllItems();
            ICollection<ItemDto> itemsDto = new HashSet<ItemDto>();

            foreach (var item in items)
                itemsDto.Add(new ItemDto() { No = item.No, Description = item.Description });

            return Ok(itemsDto.AsEnumerable());
        }
示例#43
0
        public IHttpActionResult ItemCategories()
        {
            var itemcategories = _inventoryService.GetItemCategories();
            ICollection<ItemCategoryDto> itemcategoriesDto = new HashSet<ItemCategoryDto>();

            foreach (var itemcategory in itemcategories)
                itemcategoriesDto.Add(new ItemCategoryDto() { Id = itemcategory.Id, Name = itemcategory.Name });

            return Ok(itemcategoriesDto.AsEnumerable());
        }
示例#44
0
        public List<Activity> GetActivities(HashSet<string> ids, string appId, HashSet<String> fields, HashSet<String> activityIds)
        {
            var activities = db.activities
                .OrderByDescending(x => x.id)
                .Where(x => ids.AsEnumerable().Contains(x.person_id.ToString()) && (string.IsNullOrEmpty(appId) ? true : x.app_id.ToString() == appId));

            List<Activity> actList = new List<Activity>();
            if (activityIds != null)
            {
                foreach (var row in activities)
                {
                    if (activityIds.Contains(row.id.ToString()))
                    {
                        var act = new Activity(row.id.ToString(), row.person_id.ToString());
                        act.streamTitle = "activities";
                        act.title = row.title;
                        act.body = row.body;
                        act.postedTime = row.created;
                        act.mediaItems = GetMediaItems(row.id.ToString());
                        actList.Add(act);
                    }
                }
            }
            return actList;
        }
示例#45
0
        /// <summary>
        /// Return an IEnumerable of PDAResults after applying this PDA to the
        /// given input.
        /// </summary>
        public IEnumerable<PDAResult> MatchResults(string input)
        {
            // Catch empty initial string, which trivially matches an empty
            // stack acceptance PDA.
            if (input == "")
            {
                return new List<PDAResult> { new PDAResult(0, 0, true) };
            }

            // If there are no transitions that can move on the initial
            // configuration, or can remove items from the stack, fail quickly.
            if (!Transitions.Any(t => t.StackHead == '_' &&
                                       t.OldState == StartState &&
                                       t.InputChar == input[0]) ||
                !Transitions.Any(t => t.StackReplace.Length == 0))
            {
                return new List<PDAResult> { new PDAResult(0, 0, false) };
            }

            // HashSet to remove duplicate results.
            var resultList = new HashSet<PDAResult>();

            var stateList = new List<PDARunState> { new PDARunState(input, 0,
                "", StartState) };

            while (stateList.Count() > 0)
            {
                // HashSet to remove duplicate states.
                var newStateList = new HashSet<PDARunState>();

                foreach (var state in stateList)
                {
                    // Obtain the list of states reachable from this state.
                    var nextStates = FindNextStates(state).ToList();

                    // No further states, so fail.
                    if (nextStates.Count == 0)
                    {
                        resultList.Add(new PDAResult(state.MatchedSoFar,
                                                     state.Stack.Length,
                                                     false));
                        continue;
                    }

                    foreach (var nextState in nextStates)
                    {
                        // Check for accept/reject state with acceptance by
                        // empty stack.
                        if (nextState.Failure || nextState.Input == "" &&
                                                 nextState.Stack.Length == 0)
                        {
                            resultList.Add(new PDAResult(nextState.MatchedSoFar,
                                nextState.Stack.Count(), !nextState.Failure));
                        }
                        else
                        {
                            newStateList.Add(nextState);
                        }
                    }
                }

                stateList = newStateList.ToList();
            }

            return resultList.AsEnumerable();
        }
示例#46
0
文件: Method.cs 项目: ichynul/vowstag
 public void SetTestBeforLoad(HashSet<string> tests)
 {
     if (tests != null && tests.Count > 0)
     {
         this.TestsBeforLoad = new List<string>();
         var list = tests.AsEnumerable();
         for (int i = tests.Count - 1; i > -1; i -= 1)
         {
             this.TestsBeforLoad.Add(list.ElementAt(i));
         }
     }
 }
示例#47
0
        public Dictionary<string,Person> GetPeople(HashSet<String> ids, HashSet<String> fields, CollectionOptions options)
        {
            var result = new Dictionary<string, Person>();
            var persons = db.persons.Where(x => ids.AsEnumerable().Contains(x.id.ToString()));

            // TODO filter first then fill dictionary

            foreach (var p in persons)
            {
                int personId = p.id;
                var name = new Name();
                var person = new Person();
                
                name.givenName = p.first_name;
                name.familyName = p.last_name;
                name.formatted = p.first_name + " " + p.last_name;
                person.displayName = name.formatted;
                person.name = name;
                person.id = personId.ToString();
                if (fields.Contains("about_me") || fields.Contains("@all"))
                {
                    person.aboutMe = p.about_me;
                }
                if (fields.Contains("age") || fields.Contains("@all"))
                {
                    person.age = p.age;
                }
                if (fields.Contains("children") || fields.Contains("@all"))
                {
                    person.children = p.children;
                }
                if (fields.Contains("date_of_birth") || fields.Contains("@all"))
                {
                    if (p.date_of_birth.HasValue)
                    {
                        person.birthday = UnixTime.ToDateTime(p.date_of_birth.Value);
                    }
                }
                if (fields.Contains("ethnicity") || fields.Contains("@all"))
                {
                    person.ethnicity = p.ethnicity;
                }
                if (fields.Contains("fashion") || fields.Contains("@all"))
                {
                    person.fashion = p.fashion;
                }
                if (fields.Contains("happiest_when") || fields.Contains("@all"))
                {
                    person.happiestWhen = p.happiest_when;
                }
                if (fields.Contains("humor") || fields.Contains("@all"))
                {
                    person.humor = p.humor;
                }
                if (fields.Contains("job_interests") || fields.Contains("@all"))
                {
                    person.jobInterests = p.job_interests;
                }
                if (fields.Contains("living_arrangement") || fields.Contains("@all"))
                {
                    person.livingArrangement = p.living_arrangement;
                }
                if (fields.Contains("looking_for") || fields.Contains("@all"))
                {
                    person._lookingFor = p.looking_for;
                }
                if (fields.Contains("nickname") || fields.Contains("@all"))
                {
                    person.nickname = p.nickname;
                }
                if (fields.Contains("pets") || fields.Contains("@all"))
                {
                    person.pets = p.pets;
                }
                if (fields.Contains("political_views") || fields.Contains("@all"))
                {
                    person.politicalViews = p.political_views;
                }
                if (fields.Contains("profile_song") || fields.Contains("@all"))
                {
                    if (!string.IsNullOrEmpty(p.profile_song))
                    {
                        person.profileSong = new Url(p.profile_song, "", "");
                    }
                }
                if (fields.Contains("profileUrl") || fields.Contains("@all"))
                {
                    person.profileUrl = urlPrefix + "/profile/" + personId;
                }
                if (fields.Contains("profile_video") || fields.Contains("@all"))
                {
                    if (!string.IsNullOrEmpty(p.profile_video))
                    {
                        person.profileVideo = new Url(p.profile_video, "", "");
                    }
                }
                if (fields.Contains("relationship_status") || fields.Contains("@all"))
                {
                    person.relationshipStatus = p.relationship_status;
                }
                if (fields.Contains("religion") || fields.Contains("@all"))
                {
                    person.religion = p.religion;
                }
                if (fields.Contains("romance") || fields.Contains("@all"))
                {
                    person.romance = p.romance;
                }
                if (fields.Contains("scared_of") || fields.Contains("@all"))
                {
                    person.scaredOf = p.scared_of;
                }
                if (fields.Contains("sexual_orientation") || fields.Contains("@all"))
                {
                    person.sexualOrientation = p.sexual_orientation;
                }
                if (fields.Contains("status") || fields.Contains("@all"))
                {
                    person.status = p.status;
                }
                if (fields.Contains("thumbnailUrl") || fields.Contains("@all"))
                {
                    person.thumbnailUrl = !string.IsNullOrEmpty(p.thumbnail_url) ? urlPrefix + p.thumbnail_url : "";
                    if (!string.IsNullOrEmpty(p.thumbnail_url))
                    {
                        person.photos = new List<ListField>
                                            {
                                                new Url(urlPrefix + p.thumbnail_url, "thumbnail", "thumbnail")
                                            };
                    }
                }
                if (fields.Contains("time_zone") || fields.Contains("@all"))
                {
                    person.utcOffset = p.time_zone; // force "-00:00" utc-offset format
                }
                if (fields.Contains("drinker") || fields.Contains("@all"))
                {
                    if (!String.IsNullOrEmpty(p.drinker))
                    {
                        person.drinker = (Drinker)Enum.Parse(typeof(Drinker), p.drinker);
                    }
                }
                if (fields.Contains("gender") || fields.Contains("@all"))
                {
                    if (!String.IsNullOrEmpty(p.gender))
                    {
                        person.gender = (Person.Gender)Enum.Parse(typeof(Person.Gender), p.gender, true);
                    }
                }
                if (fields.Contains("smoker") || fields.Contains("@all"))
                {
                    if (!String.IsNullOrEmpty(p.smoker))
                    {
                        person.smoker = (Smoker)Enum.Parse(typeof(Smoker), p.smoker); 
                    }
                }
                if (fields.Contains("activities") || fields.Contains("@all"))
                {
                    var activities = db.person_activities.Where(a => a.person_id == personId).Select(a => a.activity);
                    person.activities = activities.ToList();
                }

                if (fields.Contains("addresses") || fields.Contains("@all"))
                {
                    var person_addresses = db.addresses.
                        Join(db.person_addresses, a => a.id, b => b.address_id, (a, b) => new { a, b }).
                        Where(x => x.b.person_id == personId).
                        Select(x => x.a);
                    List<Address> _addresses = new List<Address>();
                    foreach (address _row in person_addresses)
                    {
                        if (String.IsNullOrEmpty(_row.unstructured_address))
                        {
                            _row.unstructured_address = (_row.street_address + " " + _row.region + " " + _row.country).Trim();
                        }
                        var _addres = new Address(_row.unstructured_address);
                        _addres.country = _row.country;
                        _addres.latitude = _row.latitude;
                        _addres.longitude = _row.longitude;
                        _addres.locality = _row.locality;
                        _addres.postalCode = _row.postal_code;
                        _addres.region = _row.region;
                        _addres.streetAddress = _row.street_address;
                        _addres.type = _row.address_type;
                        //FIXME quick and dirty hack to demo PC
                        _addres.primary = true;
                        _addresses.Add(_addres);
                    }
                    person.addresses = _addresses;
                }

                if (fields.Contains("bodyType") || fields.Contains("@all"))
                {
                    var _row = db.person_body_types.Where(x => x.person_id == personId).SingleOrDefault();
                    if (_row != null)
                    {
                        BodyType _bodyType = new BodyType();
                        _bodyType.build = _row.build;
                        _bodyType.eyeColor = _row.eye_color;
                        _bodyType.hairColor = _row.hair_color;
                        if (_row.height.HasValue)
                            _bodyType.height = float.Parse(_row.height.Value.ToString());
                        if (_row.weight.HasValue)
                            _bodyType.weight = float.Parse(_row.weight.Value.ToString());
                        person.bodyType = _bodyType;
                    }
                }

                if (fields.Contains("books") || fields.Contains("@all"))
                {
                    var books = db.person_books.Where(x => x.person_id == personId).Select(x => x.book);
                    person.books = books.ToList();
                }

                if (fields.Contains("cars") || fields.Contains("@all"))
                {
                    var _cars = db.person_cars.Where(x => x.person_id == personId).Select(x => x.car);
                    person.cars = _cars.ToList();
                }

                if (fields.Contains("currentLocation") || fields.Contains("@all"))
                {
                    var _row = db.addresses.
                        Join(db.person_current_locations, a => a.id, b => b.address_id, (a, b) => new { a, b }).
                        Where(x => x.b.person_id == personId).Select(x => x.a).SingleOrDefault();
                    if (_row != null)
                    {
                        if (string.IsNullOrEmpty(_row.unstructured_address))
                        {
                            _row.unstructured_address = (_row.street_address + " " + _row.region + " " + _row.country).Trim();
                        }
                        var _addres = new Address(_row.unstructured_address);
                        _addres.country = _row.country;
                        _addres.latitude = _row.latitude;
                        _addres.longitude = _row.longitude;
                        _addres.locality = _row.locality;
                        _addres.postalCode = _row.postal_code;
                        _addres.region = _row.region;
                        _addres.streetAddress = _row.street_address;
                        _addres.type = _row.address_type;
                        person.currentLocation = _addres;
                    }
                }

                if (fields.Contains("emails") || fields.Contains("@all"))
                {
                    var _emails = db.person_emails.Where(x => x.person_id == personId);
                    List<ListField> _emailList = new List<ListField>();
                    foreach (person_email _email in _emails)
                    {
                        _emailList.Add(new ListField(_email.email_type, _email.address)); // TODO: better email canonicalization; remove dups
                    }
                    person.emails = _emailList;
                }

                if (fields.Contains("food") || fields.Contains("@all"))
                {
                    var _foods = db.person_foods.Where(x => x.person_id == personId).Select(x => x.food);
                    person.food = _foods.ToList();
                }

                if (fields.Contains("heroes") || fields.Contains("@all"))
                {
                    var _strings = db.person_heroes.Where(x => x.person_id == personId).Select(x => x.hero);
                    person.heroes = _strings.ToList();
                }

                if (fields.Contains("interests") || fields.Contains("@all"))
                {
                    var _strings = db.person_interests.Where(x => x.person_id == personId).Select(x => x.interest);
                    person.interests = _strings.ToList();
                }
                List<Organization> _organizations = new List<Organization>();
                bool _fetchedOrg = false;
                if (fields.Contains("jobs") || fields.Contains("@all"))
                {
                    var _org = db.organizations.
                        Join(db.person_jobs, a => a.id, b => b.organization_id, (a, b) => new { a, b }).
                        Where(x => x.b.person_id == personId).
                        Select(x => x.a);
                    foreach (var _row in _org)
                    {
                        var _organization = new Organization();
                        _organization.description = _row.description;
                        if (_row.end_date.HasValue)
                            _organization.endDate = UnixTime.ToDateTime(_row.end_date.Value);
                        _organization.field = _row.field;
                        _organization.name = _row.name;
                        _organization.salary = _row.salary;
                        if (_row.start_date.HasValue)
                            _organization.startDate = UnixTime.ToDateTime(_row.start_date.Value);
                        _organization.subField = _row.sub_field;
                        _organization.title = _row.title;
                        _organization.webpage = _row.webpage;
                        _organization.type = "job";
                        if (_row.address_id.HasValue)
                        {
                            int addressid = _row.address_id.Value;
                            var _res3 = db.addresses.Where(x => x.id == addressid).Single();
                            if (string.IsNullOrEmpty(_res3.unstructured_address))
                            {
                                _res3.unstructured_address = (_res3.street_address + " " + _res3.region + " " + _res3.country).Trim();
                            }
                            var _addres = new Address(_res3.unstructured_address);
                            _addres.country = _res3.country;
                            _addres.latitude = _res3.latitude;
                            _addres.longitude = _res3.longitude;
                            _addres.locality = _res3.locality;
                            _addres.postalCode = _res3.postal_code;
                            _addres.region = _res3.region;
                            _addres.streetAddress = _res3.street_address;
                            _addres.type = _res3.address_type;
                            _organization.address = _addres;
                        }
                        _organizations.Add(_organization);
                    }
                    _fetchedOrg = true;
                }

                if (fields.Contains("schools") || fields.Contains("@all"))
                {
                    var _res2 = db.organizations.
                        Join(db.person_schools, a => a.id, b => b.organization_id, (a, b) => new { a, b }).
                        Where(x => x.b.person_id == personId).
                        Select(x => x.a);
                    foreach (var _row in _res2)
                    {
                        var _organization = new Organization();
                        _organization.description = _row.description;
                        if (_row.end_date.HasValue)
                            _organization.endDate = UnixTime.ToDateTime(_row.end_date.Value);
                        _organization.field = _row.field;
                        _organization.name = _row.name;
                        _organization.salary = _row.salary;
                        if (_row.start_date.HasValue)
                            _organization.startDate = UnixTime.ToDateTime(_row.start_date.Value);
                        _organization.subField = _row.sub_field;
                        _organization.title = _row.title;
                        _organization.webpage = _row.webpage;
                        _organization.type = "school";
                        if (_row.address_id.HasValue)
                        {
                            int addressid = _row.address_id.Value;
                            var _res3 = db.addresses.Where(x => x.id == addressid).Single();
                            if (string.IsNullOrEmpty(_res3.unstructured_address))
                            {
                                _res3.unstructured_address = (_res3.street_address + " " + _res3.region + " " + _res3.country).Trim();
                            }
                            var _addres = new Address(_res3.unstructured_address);
                            _addres.country = _res3.country;
                            _addres.latitude = _res3.latitude;
                            _addres.longitude = _res3.longitude;
                            _addres.locality = _res3.locality;
                            _addres.postalCode = _res3.postal_code;
                            _addres.region = _res3.region;
                            _addres.streetAddress = _res3.street_address;
                            _addres.type = _res3.address_type;
                            _organization.address = _addres;
                        }
                        _organizations.Add(_organization);
                    }
                    _fetchedOrg = true;
                }
                if (_fetchedOrg)
                {
                    person.organizations = _organizations;
                }
                //TODO languagesSpoken, currently missing the languages / countries tables so can"t do this yet

                if (fields.Contains("movies") || fields.Contains("@all"))
                {
                    var _strings = db.person_movies.Where(x => x.person_id == personId).Select(x => x.movie);
                    person.movies = _strings.ToList();
                }
                if (fields.Contains("music") || fields.Contains("@all"))
                {
                    var _strings = db.person_musics.Where(x => x.person_id == personId).Select(x => x.music);
                    person.music = _strings.ToList();
                }
                if (fields.Contains("phoneNumbers") || fields.Contains("@all"))
                {
                    List<ListField> numList = new List<ListField>();
                    var _numbers = db.person_phone_numbers.Where(x => x.person_id == personId);
                    foreach (var _number in _numbers)
                    {
                        numList.Add(new ListField(_number.number_type, _number.number));
                    }
                    person.phoneNumbers = numList;
                }
                /*
                if (_fields.Contains("ims") || _fields.Contains("@all")) 
                {
                    var _ims = array();
                    _res2 = mysqli_query(this._db, "select value, value_type from person_ims where person_id = " + _person_id);
                    while (list(_value, _type) = @mysqli_fetch_row(_res2)) 
                    {
                    _ims[] = new Im(_value, _type);
                    }
                    _person.Ims = _ims;
                }
                if (_fields.Contains("accounts") || _fields.Contains("@all")) {
                _accounts = array();
                _res2 = mysqli_query(this._db, "select domain, userid, username from person_accounts where person_id = " + _person_id);
                while (list(_domain, _userid, _username) = @mysqli_fetch_row(_res2)) {
                _accounts[] = new Account(_domain, _userid, _username);
                }
                _person.Accounts = _accounts;
                }*/
                if (fields.Contains("quotes") || fields.Contains("@all"))
                {
                    var _strings = db.person_quotes.Where(x => x.person_id == personId).Select(x => x.quote);
                    person.quotes = _strings.ToList();
                }
                if (fields.Contains("sports") || fields.Contains("@all"))
                {
                    var _strings = db.person_sports.Where(x => x.person_id == personId).Select(x => x.sport);
                    person.sports = _strings.ToList();
                }
                if (fields.Contains("tags") || fields.Contains("@all"))
                {
                    var _strings = db.person_tags.Where(x => x.person_id == personId).Select(x => x.tag);
                    person.tags = _strings.ToList();
                }

                if (fields.Contains("turnOns") || fields.Contains("@all"))
                {
                    var _strings = db.person_turn_ons.Where(x => x.person_id == personId).Select(x => x.turn_on);
                    person.turnOns = _strings.ToList();
                }
                if (fields.Contains("turnOffs") || fields.Contains("@all"))
                {
                    var _strings = db.person_turn_offs.Where(x => x.person_id == personId).Select(x => x.turn_off);
                    person.turnOffs = _strings.ToList();
                }
                
                if (fields.Contains("urls") || fields.Contains("@all"))
                {
                    var _strings = db.person_urls.Where(x => x.person_id == personId).Select(x => x.url);
                    List<ListField> urllist = new List<ListField>();
                    foreach (string s in _strings)
                    {
                        var url = new Url(s, null, null);
                        urllist.Add(url);
                    }
                    //urllist.Add(new Url(urlPrefix + "/profile/" + personId, null, "profile"));
                    person.urls = urllist;
                }
                 
                result.Add(personId.ToString(), person);
            } // foreach

            return result;  
        }
示例#48
0
 public DataCollection GetAppData(HashSet<String> ids, HashSet<String> keys, String appId) 
 {
     var data = new Dictionary<string, Dictionary<string, string>>();
     var res = db.application_settings
         .Where(x => (!String.IsNullOrEmpty(appId)?x.application_id.ToString() == appId : true) && ids.AsEnumerable().Contains(x.person_id.ToString()) && (keys.Count == 0 ? true : keys.AsEnumerable().Contains(x.name)))
         .Select(x => new { x.person_id, x.name, x.value });
     
     foreach (var re in res)
     {
         if (!data.ContainsKey(re.person_id.ToString()))
         {
             data.Add(re.person_id.ToString(), new Dictionary<string, string>());
         }
         data[re.person_id.ToString()].Add(re.name, re.value);
     }
     return new DataCollection(data);
 }