private static void SetDepartmentProperties(Taxon department, string departmentName)
        {
            department.Name = Regex.Replace(departmentName.ToLower(), @"[^\w\-\!\$\'\(\)\=\@\d_]+", "-");
            department.Title = departmentName;

            department.Description = departmentName;
            department.UrlName = department.Name;
        }
Ejemplo n.º 2
0
        private static void SetTagProperties(Taxon tag, string tagName)
        {
            tag.Name = Regex.Replace(tagName.ToLower(), @"[^\w\-\!\$\'\(\)\=\@\d_]+", "-");
            tag.Title = tagName;

            tag.Description = tagName;
            tag.UrlName = tag.Name;
        }
        private static TaxonViewModel BuildTaxaTreeBfs(
            Taxon taxon,
            Func<ITaxon, TaxonViewModel> viewModelBuilder,
            Func<IQueryable<Taxon>, IQueryable<Taxon>> sort,
            TaxonomyManager manager,
            int taxaCountLimit,
            ref int currentTaxaCount)
        {
            var queue = new Queue<TaxonData>();
            TaxonViewModel rootViewModel = null;

            queue.Enqueue(new TaxonData() { Taxon = taxon });

            while (queue.Count > 0)
            {
                var currentNode = queue.Dequeue();

                var currentViewModel = viewModelBuilder.Invoke(currentNode.Taxon);

                if (currentViewModel != null)
                {
                    // If this is the first created view model, set it to be the root one.
                    if (rootViewModel == null) rootViewModel = currentViewModel;

                    if (currentNode.LastKnownParent != null)
                    {
                        currentNode.LastKnownParent.SubTaxa.Add(currentViewModel);
                    }

                    currentTaxaCount++;
                    if (taxaCountLimit > 0 && currentTaxaCount == taxaCountLimit)
                    {
                        return rootViewModel;
                    }
                }

                // If the current taxon is included in the tree, it should be the parent of the inner taxa.
                var lastKnownParent = currentViewModel ?? currentNode.LastKnownParent;

                var subTaxa = manager.GetTaxa<Taxon>().Where(t => t.Parent.Id == currentNode.Taxon.Id);
                var sortedSubtaxa = sort.Invoke(subTaxa);

                foreach (var childTaxon in sortedSubtaxa)
                {
                    queue.Enqueue(new TaxonData()
                    {
                        LastKnownParent = lastKnownParent,
                        Taxon = childTaxon
                    });
                }
            }

            return rootViewModel;
        }
Ejemplo n.º 4
0
        // 更新可见性。
        private void _UpdateVisibility()
        {
            Taxon currentTaxon = Common.CurrentTaxon;

            grid_Tags.Visibility     = currentTaxon.Tags.Count > 0 ? Visibility.Visible : Visibility.Collapsed;
            grid_Synonyms.Visibility = currentTaxon.Synonyms.Count > 0 ? Visibility.Visible : Visibility.Collapsed;
            stackPanel_TagsAndSynonyms.Visibility = currentTaxon.Tags.Count > 0 || currentTaxon.Synonyms.Count > 0 ? Visibility.Visible : Visibility.Collapsed;
            grid_Parents.Visibility  = !currentTaxon.IsRoot ? Visibility.Visible : Visibility.Collapsed;
            grid_Children.Visibility = taxonButtonGroup_Children.GetGroupCount() > 0 ? Visibility.Visible : Visibility.Collapsed;
            grid_Excludes.Visibility = currentTaxon.Excludes.Count > 0 ? Visibility.Visible : Visibility.Collapsed;
            grid_Desc.Visibility     = !string.IsNullOrWhiteSpace(currentTaxon.Description) ? Visibility.Visible : Visibility.Collapsed;
        }
Ejemplo n.º 5
0
        // 获取类群的长名称。
        public static string GetLongName(this Taxon taxon)
        {
            if (taxon is null)
            {
                throw new ArgumentNullException();
            }

            //

            if (taxon.IsAnonymous)
            {
                return("<节点>");
            }
            else
            {
                StringBuilder taxonName = new StringBuilder();

                if (!string.IsNullOrEmpty(taxon.ChineseName))
                {
                    taxonName.Append(taxon.ChineseName);

                    if (!string.IsNullOrEmpty(taxon.ScientificName))
                    {
                        taxonName.Append(' ');
                        taxonName.Append(taxon.ScientificName);
                    }
                }
                else
                {
                    Rank rank = taxon.Rank;

                    if (rank.IsPrimaryOrSecondaryRank())
                    {
                        taxonName.Append(rank.GetChineseName());

                        if (!string.IsNullOrEmpty(taxon.ScientificName))
                        {
                            taxonName.Append(' ');
                            taxonName.Append(taxon.ScientificName);
                        }
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(taxon.ScientificName))
                        {
                            taxonName.Append(taxon.ScientificName);
                        }
                    }
                }

                return(taxonName.ToString());
            }
        }
Ejemplo n.º 6
0
 public void ImportOrders()
 {
     //GET ALL FROM EXCEL
     for (int i = 2; i <= worksheetGeneral.Dimension.Rows; i++)
     {
         if (worksheetGeneral.Cells[i, orderCol].Value != null)
         {
             string orderName = worksheetGeneral.Cells[i, orderCol].Value.ToString().Trim();
             string className = worksheetGeneral.Cells[i, classCol].Value.ToString().Trim();
             try
             {
                 Taxon newTaxon = new Taxon
                 {
                     TaxonName       = worksheetGeneral.Cells[i, orderCol].Value.ToString().Trim(),
                     TaxonomyStateId = Constants.stateId_order,
                     KingdomId       = _kingdomId,
                     PhylumId        = _getPhylumIdFromExcel(i),
                     SubphylumId     = _getSubPhylumIdFromExcel(i),
                     ClassId         = _getClassIdFromExcel(i),
                     SubclassId      = _getSubClassIdFromExcel(i),
                     Group           = _getGroupInfo(i)
                 };
                 if (!_checkTaxonExists(newTaxon.TaxonName))
                 {
                     if (newTaxon.PhylumId != null && newTaxon.ClassId != null)
                     {
                         newTaxon.PhylumId = _infContext.Taxon.Where(tax => tax.TaxonName == "Gliederfüßer (Arthropoda)").Select(tax => tax.TaxonId).FirstOrDefault();
                     }
                     _infContext.Taxon.Add(newTaxon);
                     SaveToContext();
                     _uniqueOrdersDict.Add(newTaxon.TaxonName, newTaxon.TaxonId);
                     Logger.Debug("--- Added Taxon " + newTaxon.TaxonName);
                     IncrementCounter();
                 }
                 else
                 {
                     var alreadyTax = _infContext.Taxon.Where(tax => tax.TaxonName == newTaxon.TaxonName).FirstOrDefault();
                     if (!alreadyTax.Group.Contains(newTaxon.Group))
                     {
                         alreadyTax.Group += "," + newTaxon.Group;
                         _infContext.Update(alreadyTax);
                     }
                 }
             }
             catch (Exception e)
             {
                 Logger.Error(e, "Error adding new Order Taxon " + worksheetGeneral.Cells[i, orderCol].Value.ToString().Trim() + " to Context");
             }
         }
     }
     Logger.Info("-- Finished Import of Orders");
 }
Ejemplo n.º 7
0
        private static List <Taxon> getCenters(List <FObject> points, int eps)
        {
            double[] dists      = new double[points.Count];
            int[]    centers    = new int[eps];
            int      startinpos = (new Random()).Next(0, points.Count);

            centers[0] = startinpos;

            for (int i = 1; i < eps; i++)
            {
                double sum = 0.0;
                dists = getdists(points, centers, i);
                for (int j = 0; j < dists.Length; j++)
                {
                    if (exists(j, centers, i))
                    {
                        continue;
                    }
                    else
                    {
                        sum += dists[j];
                    }
                }
                double randdist  = (new Random()).NextDouble() * sum;
                double distcount = 0.0;
                for (int j = 0; j < dists.Length; j++)
                {
                    if (exists(j, centers, i))
                    {
                        continue;
                    }
                    else
                    {
                        distcount += dists[j];
                        if (distcount >= randdist)
                        {
                            centers[i] = j;
                            break;
                        }
                    }
                }
            }
            List <Taxon> taxlist = new List <Taxon>();

            for (int i = 0; i < centers.Length; i++)
            {
                Taxon tax = new Taxon();
                tax.mass_center = points[centers[i]];
                taxlist.Add(tax);
            }
            return(taxlist);
        }
        private void AddMaterialRowsForTaxon(DataMatrix results, Taxon taxon)
        {
            var ids = XMLIOService.GetMaterialForTaxon(taxon.TaxaID.Value);

            foreach (XMLIOMaterialID id in ids)
            {
                var links = SupportService.GetMultimediaItems(TraitCategoryType.Material.ToString(), id.MaterialID);
                foreach (MultimediaLink link in links)
                {
                    AddTaxonRow(results, taxon, link, "Material", id.MaterialID);
                }
            }
        }
        public void ClassificationTaxonModel_Deserialization_ShouldWork()
        {
            XmlSerializer serializer = new XmlSerializer(typeof(Taxon));
            Taxon         response   = null;

            using (var reader = new StreamReader(@"DataFiles\classification-taxon.xml"))
            {
                response = (Taxon)serializer.Deserialize(reader);
            }

            Assert.IsNotNull(response, "Deserialized object should not be null.");
            Assert.AreEqual("Insecta", response.Name, "Name should match.");
        }
Ejemplo n.º 10
0
        public static Node CreateOrSetParents(string scientificName, Type type, SubjectManager subjectManager)
        {
            string[]        nameArray = scientificName.Split(' ');
            WikipediaReader wReader   = new WikipediaReader();

            /**
             * Lactuca                      -> Genus
             * Lactuca sativa               -> Species
             * Lactuca sativa var. capitata -> Variation - Subspecies
             * Lactuca sativa var. capitata Larissa -> SubSpecies
             * Lactuca sativa Larissa -> SubSpecies
             * */

            //Lactuca sativa - create genus return genus
            Taxon genus = GetOrCreateGenus(nameArray[0], subjectManager);

            if (nameArray.Count() == 2)
            {
                return(genus);
            }

            //Lactuca sativa Larissa -> SubSpecies
            if (nameArray.Count() == 3 && !nameArray.Contains("var."))
            {
                string name = nameArray[0] + " " + nameArray[1];
                return(GetOrCreateSpecies(name, type, subjectManager, genus));
            }

            //Lactuca sativa var. capitata -> Species

            if (nameArray.Count() == 4 && nameArray.Contains("var."))
            {
                string name = nameArray[0] + " " + nameArray[1];
                return(GetOrCreateSpecies(name, type, subjectManager, genus));
            }

            //Lactuca sativa var. capitata Larissa -> SubSpecies
            if (nameArray.Count() == 5 && nameArray.Contains("var."))
            {
                string name = nameArray[0] + " " + nameArray[1];
                return(GetOrCreateSpecies(name, type, subjectManager, genus));
            }

            if (nameArray.Count() > 5)
            {
                string name = nameArray[0] + " " + nameArray[1];
                return(GetOrCreateSpecies(name, type, subjectManager, genus));
            }

            return(null);
        }
Ejemplo n.º 11
0
        /**TODO: refactor below **/
        public void ImportClasses()
        {
            if (classCol != 0)
            {
                for (int i = 2; i <= worksheetGeneral.Dimension.Rows; i++)
                {
                    if (worksheetGeneral.Cells[i, classCol].Value != null)
                    {
                        try
                        {
                            Taxon newTaxon = new Taxon
                            {
                                TaxonName       = worksheetGeneral.Cells[i, classCol].Value?.ToString().Trim(),
                                TaxonomyStateId = Constants.stateId_class,
                                KingdomId       = _kingdomId,
                                SubphylumId     = _getSubPhylumIdFromExcel(i),
                                PhylumId        = _getPhylumIdFromExcel(i),
                                Group           = _getGroupInfo(i),
                            };
                            if (!_checkTaxonExists(newTaxon.TaxonName))
                            {
                                //hack because client cant keep his excels clean
                                if (newTaxon.PhylumId != null)
                                {
                                    newTaxon.PhylumId = _infContext.Taxon.Where(tax => tax.TaxonName == "Gliederfüßer (Arthropoda)").Select(tax => tax.TaxonId).FirstOrDefault();
                                }

                                var newTaxonId = _infContext.Taxon.Add(newTaxon);
                                SaveToContext();
                                Logger.Debug("--- Added Taxon " + newTaxon.TaxonName);
                                IncrementCounter();
                            }
                            else
                            {
                                var alreadyTax = _infContext.Taxon.Where(tax => tax.TaxonName == newTaxon.TaxonName).FirstOrDefault();
                                if (!alreadyTax.Group.Contains(newTaxon.Group))
                                {
                                    alreadyTax.Group += "," + newTaxon.Group;
                                    _infContext.Update(alreadyTax);
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            Logger.Error(e, "Error adding new Class Taxon " + worksheetGeneral.Cells[i, classCol].Value + " to Context");
                        }
                    }
                }
                Logger.Info("-- Finished Import of Classes");
            }
        }
Ejemplo n.º 12
0
        // 检查指定类群的违规项。
        public static IReadOnlyCollection <IValidator> Validate(this Taxon taxon)
        {
            List <IValidator> result = new List <IValidator>();

            foreach (var validator in _Validators)
            {
                if (!validator.IsValid(taxon))
                {
                    result.Add(validator);
                }
            }

            return(result);
        }
Ejemplo n.º 13
0
        public void Equals_IfIDsAreTheSame_True()
        {
            var t1 = new Taxon {
                Id = Guid.NewGuid()
            };
            var t2 = new Taxon {
                Id = Guid.NewGuid()
            };

            Assert.IsFalse(t1.Equals(t2));

            t2.Id = t1.Id;
            Assert.IsTrue(t1.Equals(t2));
        }
Ejemplo n.º 14
0
        public bool IsValid(Taxon taxon)
        {
            Dictionary <string, object> dict = new Dictionary <string, object>();

            foreach (string synonym in taxon.Synonyms)
            {
                if (!dict.TryAdd(synonym, null))
                {
                    return(false);
                }
            }

            return(true);
        }
        public async Task AddSpecies(string genus, string species, string zone = "", string description = "")
        {
            // Check if the species already exists before attempting to add it.

            if ((await BotUtils.GetSpeciesFromDb(genus, species)).Count() > 0)
            {
                await BotUtils.ReplyAsync_Warning(Context, string.Format("The species \"{0}\" already exists.", BotUtils.GenerateSpeciesName(genus, species)));

                return;
            }

            await BotUtils.AddGenusToDb(genus);

            Taxon genus_info = await BotUtils.GetGenusFromDb(genus);

            using (SQLiteCommand cmd = new SQLiteCommand("INSERT INTO Species(name, description, genus_id, owner, timestamp, user_id) VALUES($name, $description, $genus_id, $owner, $timestamp, $user_id);")) {
                cmd.Parameters.AddWithValue("$name", species.ToLower());
                cmd.Parameters.AddWithValue("$description", description);
                cmd.Parameters.AddWithValue("$genus_id", genus_info.id);
                cmd.Parameters.AddWithValue("$owner", Context.User.Username);
                cmd.Parameters.AddWithValue("$user_id", Context.User.Id);
                cmd.Parameters.AddWithValue("$timestamp", DateTimeOffset.UtcNow.ToUnixTimeSeconds());

                await Database.ExecuteNonQuery(cmd);
            }

            Species[] sp_list = await BotUtils.GetSpeciesFromDb(genus, species);

            Species sp         = sp_list.Count() > 0 ? sp_list[0] : null;
            long    species_id = sp == null ? -1 : sp.Id;

            if (species_id < 0)
            {
                await BotUtils.ReplyAsync_Error(Context, "Failed to add species (invalid Species ID).");

                return;
            }

            // Add to all given zones.
            await _plusZone(sp, zone, string.Empty, onlyShowErrors : true);

            // Add the user to the trophy scanner queue in case their species earned them any new trophies.

            if (OurFoodChainBot.Instance.Config.TrophiesEnabled)
            {
                await Global.TrophyScanner.AddToQueueAsync(Context, Context.User.Id);
            }

            await BotUtils.ReplyAsync_Success(Context, string.Format("Successfully created new species, **{0}**.", BotUtils.GenerateSpeciesName(genus, species)));
        }
Ejemplo n.º 16
0
        public bool IsValid(Taxon taxon)
        {
            Dictionary <string, object> dict = new Dictionary <string, object>();

            foreach (string tag in taxon.Tags)
            {
                if (!dict.TryAdd(tag, null))
                {
                    return(false);
                }
            }

            return(true);
        }
Ejemplo n.º 17
0
        public TaxonPage(Taxon taxon)
        {
            InitializeComponent();

            var vm = new TaxonViewModel(taxon);

            vm.Navigation  = Navigation;
            BindingContext = vm;
            //Browser.Source = new UrlWebViewSource() { Url = string.Format("http://www.lepidoptera.se/arter/{0}.aspx", taxon.Name.ToLower().Replace(" ", "_")) };
            Browser.Source = new UrlWebViewSource()
            {
                Url = string.Format("https://www.google.com/search?tbm=isch&q={0}", taxon.ScientificName.Replace(" ", "%20"))
            };
        }
Ejemplo n.º 18
0
        public async Task <ActionResult <Taxon> > PostTaxonItem(Taxon item)
        {
            try
            {
                _infContext.Taxon.Add(item);
                await _infContext.SaveChangesAsync();

                return(CreatedAtAction(nameof(GetTaxonItem), new { id = item.TaxonId }, item));
            }
            catch (System.Exception e)
            {
                var exp = e;
            }
            return(null);
        }
Ejemplo n.º 19
0
 public static Models.Taxon GetTaxon(this IEnumerable <Models.Taxon> source, Taxon taxon) =>
 source.FirstOrDefault(t => t.Kingdom == taxon.Kingdom &&
                       t.Subkingdom == taxon.Subkingdom &&
                       t.Infrakingdom == taxon.Infrakingdom &&
                       t.Phylum == taxon.Phylum &&
                       t.Subphylum == taxon.Subphylum &&
                       t.Class == taxon.Class &&
                       t.Subclass == taxon.Subclass &&
                       t.Order == taxon.Order &&
                       t.Family == taxon.Family &&
                       t.Genus == taxon.Genus &&
                       t.Species == taxon.Species &&
                       t.Subspecies == taxon.Variety &&
                       t.Subvariety == taxon.Subvariety &&
                       t.Form == taxon.Form);
Ejemplo n.º 20
0
        //

        private static void _RecursiveFillAtoms(Taxon taxon, List <EvoAtom> evoAtoms)
        {
            if (taxon is null || evoAtoms is null)
            {
                throw new ArgumentNullException();
            }

            //

            foreach (var child in taxon.Children)
            {
                evoAtoms.Add(EvoAtom.FromTaxon(child));

                _RecursiveFillAtoms(child, evoAtoms);
            }
        }
 private Taxon GetTaxon(Boolean refresh = false, TaxonId?taxonId = null)
 {
     if (_taxon.IsNull() || refresh)
     {
         // _taxon = (Taxon)(CoreData.TaxonManager.GetTaxonById(GetUserContext(), TaxonId.Bear));
         if (taxonId.HasValue)
         {
             _taxon = (Taxon)(CoreData.TaxonManager.GetTaxon(GetUserContext(), taxonId.Value));
         }
         else
         {
             _taxon = (Taxon)(CoreData.TaxonManager.GetTaxon(GetUserContext(), 246126));
         }
     }
     return(_taxon);
 }
Ejemplo n.º 22
0
        public void UpdateCurrentTaxonInfo()
        {
            ViewModel.LoadFromCurrentTaxon();

            Taxon currentTaxon = Common.CurrentTaxon;

            taxonTitle.Taxon = currentTaxon;

            tagGroup_Tags.UpdateContent(currentTaxon.Tags);
            tagGroup_Synonyms.UpdateContent(currentTaxon.Synonyms);
            tagGroup_Synonyms.ThemeColor = currentTaxon.GetThemeColor();

            _UpdateParents();
            _UpdateChildren();
            _UpdateExcludes();
            _UpdateVisibility();
        }
Ejemplo n.º 23
0
        public void CanSetGenera()
        {
            var GeneraId = Guid.NewGuid();
            var taxon    = new Taxon {
                Genus = new Genus()
                {
                    Id = GeneraId
                }
            };

            Assert.AreEqual(taxon.Genus.Id, GeneraId);
            var Genera = new Genus();

            Genera.Title           = "astro";
            (taxon as Taxon).Genus = Genera;
            Assert.AreEqual((taxon as Taxon).Genus.Title, "astro");
        }
        public DataValidationResult ValidateTaxonMove(Taxon source, Taxon dest)
        {
            var map = GetTaxonRankMap();

            // Can only really validate if the ranks of the source and target are 'known'
            if (map.ContainsKey(RankKey(dest)) && map.ContainsKey(RankKey(source)))
            {
                TaxonRank destrank = map[RankKey(dest)];
                TaxonRank srcrank  = map[RankKey(source)];
                if (!IsValidChild(srcrank, destrank))
                {
                    return(new DataValidationResult(false, String.Format("{0} is not a valid child of {1}", srcrank.LongName, destrank.LongName)));
                }
            }

            return(new DataValidationResult(true));
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Creates a taxon for test
        /// </summary>
        /// <returns></returns>
        public ITaxon GetReferenceParentTaxon(IUserContext userContext, int taxonId)
        {
            ITaxon refTaxon = new Taxon();

            string   conceptDefinitionPartString = "";
            DateTime createdDate   = new DateTime(2004, 01, 20);
            Int32    createdBy     = userContext.User.Id;
            string   personName    = @"Hölje Soderås";
            DateTime validFromDate = new DateTime(1763, 02, 08);
            DateTime validToDate   = new DateTime(2447, 08, 01);

            // refTaxon.ConceptDefinitionFullGeneratedString = conceptDefinitionFullGeneratedString;
            refTaxon.PartOfConceptDefinition = conceptDefinitionPartString;
            refTaxon.CreatedBy        = createdBy;
            refTaxon.CreatedDate      = createdDate;
            refTaxon.DataContext      = new DataContext(userContext);
            refTaxon.ModifiedByPerson = personName;
            refTaxon.ValidFromDate    = validFromDate;
            refTaxon.ValidToDate      = validToDate;
            refTaxon.Id = taxonId;
            int taxonNameId = DyntaxaTestSettings.Default.TestParentTaxonNameId;
            // ITaxonName refTaxonName = GetReferenceTaxonName(userContext, taxonId, taxonNameId);
            ITaxonCategory   taxonCategory   = GetReferenceTaxonCategory(userContext, 1);
            ITaxonProperties taxonProperties = new TaxonProperties()
            {
                IsValid = true, DataContext = new DataContext(userContext), TaxonCategory = taxonCategory, ValidToDate = new DateTime(2111, 12, 31)
            };

            refTaxon.SetTaxonProperties(new List <ITaxonProperties>()
            {
                taxonProperties
            });
            refTaxon.Category = taxonCategory;
            // ITaxonName recName = new TaxonName(userContext);
            refTaxon.Author         = "ReferenceParentAuthor";        //GetReferenceTaxonName(userContext, taxonId, taxonNameId).Author;
            refTaxon.ScientificName = "ReferenceParentScentificName"; //GetReferenceTaxonName(userContext, taxonId, taxonNameId).Name;
            refTaxon.CommonName     = "ReferenceParentCommonName";    //GetReferenceTaxonName(userContext, taxonId, taxonNameId + 1).Name;
            //ITaxon grandParentTaxon = GetReferenceGrandParentTaxon(userContext, DyntaxaTestSettings.Default.TestParentTaxonId +10);
            //refTaxon.GetParentTaxa(userContext).Add(new TaxonRelation() { RelatedTaxon = grandParentTaxon, ValidFromDate = DateTime.Now, ValidToDate = new DateTime(2022, 1, 30) });
            //List<ITaxonRelation> grandParentsList = new List<ITaxonRelation>();
            //grandParentsList.Add(new TaxonRelation() { RelatedTaxon = grandParentTaxon, ValidFromDate = DateTime.Now, ValidToDate = new DateTime(2022, 1, 30) });

            //refTaxon.ParentTaxa = grandParentsList;
            return(refTaxon);
        }
Ejemplo n.º 26
0
        // 按照指定方式获取父类群。
        public static IReadOnlyList <Taxon> GetParents(this Taxon taxon, GetParentsOption option)
        {
            if (taxon is null)
            {
                throw new ArgumentNullException();
            }

            //

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

            if (!taxon.IsRoot)
            {
                if (option == GetParentsOption.EditMode)
                {
                    // 上溯到任何具名分类阶元类群,保留任何类群
                    result.AddRange(taxon.GetParents(
                                        TaxonFilter.Any,
                                        TaxonFilter.Named | TaxonFilter.AnyRank,
                                        includeTermination: true,
                                        skipParaphyly: false));

                    // 如果没有上溯到任何主要分类阶元类群,直接上溯到顶级类群,保留任何类群
                    if (result.Count <= 0)
                    {
                        result.AddRange(taxon.GetParents(
                                            TaxonFilter.Any,
                                            TaxonFilter.None,
                                            includeTermination: true,
                                            skipParaphyly: false));
                    }
                }
                else if (option == GetParentsOption.Least)
                {
                    // 首先上溯到任何具名类群,保留任何具名类群,不跳过并系群
                    result.AddRange(taxon.GetParents(
                                        TaxonFilter.Named | TaxonFilter.AnyRank,
                                        TaxonFilter.Named | TaxonFilter.AnyRank,
                                        includeTermination: true,
                                        skipParaphyly: false));

                    // 如果上溯到任何未指定分级类群或演化支类群,继续上溯到任何主要或次要分类阶元类群,保留任何具名类群,跳过并系群
                    if (result.Count > 0)
                    {
                        Taxon parent = result[^ 1];
 public void UpdateTaxon(Taxon taxon)
 {
     StoredProcUpdate("spBiotaUpdate",
                      _P("intBiotaID", taxon.TaxaID),
                      _P("vchrEpithet", taxon.Epithet, ""),
                      _P("vchrAuthor", taxon.Author, ""),
                      _P("vchrYearOfPub", taxon.YearOfPub, ""),
                      _P("bitChgComb", taxon.ChgComb, 0),
                      _P("chrElemType", taxon.ElemType, ""),
                      _P("bitUnplaced", taxon.Unplaced, 0),
                      _P("bitUnverified", taxon.Unverified, 0),
                      _P("vchrRank", taxon.Rank, ""),
                      _P("intOrder", taxon.Order, 0),
                      _P("chrKingdomCode", taxon.KingdomCode, "A"),
                      _P("bitAvailableName", taxon.AvailableName, ""),
                      _P("bitLiteratureName", taxon.LiteratureName, ""),
                      _P("vchrAvailableNameStatus", taxon.NameStatus, ""));
 }
Ejemplo n.º 28
0
        private static Taxon _GetTaxonOfTree(PhylogeneticTree tree, IReadOnlyList <int> indexList)
        {
            if (tree is null || indexList is null)
            {
                throw new ArgumentNullException();
            }

            //

            Taxon taxon = tree.Root;

            foreach (var id in indexList)
            {
                taxon = taxon.Children[id];
            }

            return(taxon);
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Saves an attribute to a taxon.  Do not forget to call SaveChanges on your TaxonomyManager.
        /// ** Sitefinitysteve.com Extension **.
        /// </summary>
        /// <exception cref="ArgumentOutOfRangeException">Thrown when one or more arguments are outside the
        /// required range.</exception>
        /// <param name="currentTaxon">This taxon.</param>
        /// <param name="key">Dictionary Key to store the value as.</param>
        /// <param name="value">Data to store.</param>
        /// <param name="isJson">(Optional) If it's a complex object, convert to JSON.</param>
        public static void SetValue(this Taxon currentTaxon, string key, object value, bool isJson = false)
        {
            string data = (isJson) ? JsonConvert.SerializeObject(value) : value.ToString();

            if (data.Length >= 255)
            {
                throw new ArgumentOutOfRangeException("value", "Data length exceeded, Max 255");
            }

            if (!currentTaxon.Attributes.ContainsKey(key))
            {
                currentTaxon.Attributes.Add(key, data);
            }
            else
            {
                currentTaxon.Attributes[key] = data;
            }
        }
        private string MakeFeatureKey(FeatureDataRow data, Taxon taxon)
        {
            var b = new StringBuilder("rowkey");

            foreach (DataColumn col in data.Table.Columns)
            {
                b.Append("_").Append(data[col]);
            }

            if (taxon != null)
            {
                b.Append("_").Append(taxon.Epithet);
            }
            else
            {
                b.Append("_Unidentified");
            }
            return(b.ToString());
        }
Ejemplo n.º 31
0
        // 获取继承的分类阶元。
        public static Rank GetInheritedRank(this Taxon taxon)
        {
            if (taxon is null)
            {
                throw new ArgumentNullException();
            }

            //

            if (taxon.Rank.IsPrimaryOrSecondaryRank())
            {
                return(taxon.Rank);
            }
            else
            {
                Taxon nearestPrimaryOrSecondaryRankParent = null;
                Taxon parent = taxon.Parent;

                while (parent is not null)
                {
                    if (parent.Rank.IsPrimaryOrSecondaryRank())
                    {
                        nearestPrimaryOrSecondaryRankParent = parent;

                        break;
                    }
                    else
                    {
                        parent = parent.Parent;
                    }
                }

                if (nearestPrimaryOrSecondaryRankParent is null)
                {
                    return(taxon.Root.Rank);
                }
                else
                {
                    return(nearestPrimaryOrSecondaryRankParent.Rank);
                }
            }
        }
Ejemplo n.º 32
0
        public void TestAddTaxa()
        {
            // First find a root to start from...
            var parent = Service.GetTaxon(7009); // Insecta

            Assert.NotNull(parent);
            // Create a new family...
            var taxon = new Taxon {
                TaxaParentID = parent.TaxaID, Author = "Smith", YearOfPub = "1990", AvailableName = false, ChgComb = false, Epithet = "Test Taxa", ElemType = "F", KingdomCode = "A", Unplaced = false, Unverified = false, LiteratureName = false, Order = 0
            };

            // insert it...
            Service.InsertTaxon(taxon);
            Assert.IsTrue(taxon.TaxaID.HasValue);
            Trace("Inserted TaxaID: {0}", taxon.TaxaID);

            var other = Service.GetTaxon(taxon.TaxaID.Value);

            AssertObjectsEqual(other, taxon, "Rank", "NameStatus", "Parentage", "Shadowed", "RankLong", "KingdomLong", "RankCategory", "DateCreated", "WhoCreated", "DateModified", "WhoModified", "GUID", "ObjectID");
        }
Ejemplo n.º 33
0
        /// <summary>
        /// Deletes any tags in Sitefinity that are not used by anything.
        /// </summary>
        /// <param name="taxonomyManager">The manager to use to delete the unused tags.</param>
        public static void DeleteAllUnusedTags(this ITaxonomyManager taxonomyManager)
        {
            if (taxonomyManager == null)
            {
                return;
            }
            List <Taxon> existingTags   = taxonomyManager.GetTaxonomy <FlatTaxonomy>(TaxonomyManager.TagsTaxonomyId).Taxa.ToList();
            List <Guid>  existingTagIds = existingTags.Select(t => t.Id).ToList();
            var          tagIdsToDelete = taxonomyManager.GetUnusedTaxonGuids(existingTagIds);

            foreach (Guid tagIdToDelete in tagIdsToDelete)
            {
                Taxon existingTagToDelete = existingTags.SingleOrDefault(t => t.Id == tagIdToDelete);
                if (existingTagToDelete != null)
                {
                    taxonomyManager.Delete(existingTagToDelete);
                }
            }
            taxonomyManager.SaveChanges();
        }