コード例 #1
0
ファイル: DataModel.cs プロジェクト: pipseq/csFxModel
 public List<string> load(string file)
 {
     List<string> ldts = new List<string>();
     try
     {
         archive = fileUtil.load(file);
     }
     catch (Exception e)
     {
         handleException(e);
     }
     List<DateTime> ldt = new List<DateTime>(archive.Keys);
     if (ldt.Count > 0)
     {
         mapTime = new Dictionary<string, DateTime>();
         ldt.Sort();
         foreach (DateTime dt in ldt)
         {
             string dts = partDateTime(dt);
             if (!mapTime.ContainsKey(dts))
             {
                 mapTime.Add(dts, dt);
                 ldts.Add(dts);
             }
         }
     }
     return ldts;
 }
コード例 #2
0
ファイル: Program.cs プロジェクト: balazsmolnar/Euler
        static void Main(string[] args)
        {
            PrimeCalculator calc = new PrimeCalculator();
            calc.GetAllPrimes(10000);
            for (int n = 1000; n < 10000; n++)
            {
                int d1 = n % 10;
                int d2 = (n / 10) % 10;
                int d3 = (n / 100) % 10;
                int d4 = n / 1000;

                var permutations = Permutator.Permutate(new int[] {d1, d2, d3, d4}.ToList());
                var numbers = new List<int>();
                foreach (var perm in permutations)
                {
                    var num = perm[0] + perm[1] * 10 + perm[2] * 100 + perm[3] * 1000;
                    if (calc.IsPrime((ulong)num) && !numbers.Contains(num) && num>999 && num>=n)
                        numbers.Add(num);
                }
                numbers.Sort();

                for (int i = 1; i < numbers.Count-1; i++)
                {
                    for (int j = i+1; j < numbers.Count; j++)
                    {
                        if (numbers[j]-numbers[i]==numbers[i]-numbers[0])
                            Console.Write("{0}{1}{2}\n", numbers[0], numbers[i], numbers[j]);
                    }
                }
            }
        }
コード例 #3
0
ファイル: Program.cs プロジェクト: carethik2k/C_Sharp_Class
        static void Main(string[] args)
        {
            int totalCount = 3;
            List<Student> listStudent = new List<Student>();
            for (int i = 0; i < 3; i++)
            {
                Student objStudent = new Student();
                Console.Write("Please enter the Student ID: ");
                objStudent.StudentId = Int32.Parse(Console.ReadLine());
                Console.Write("Please enter the Student Name: ");
                objStudent.Name = Console.ReadLine();
                listStudent.Add(objStudent);
            }

            //Query to get by name - only first occurence
            //Student student = listStudent.First(x => x.Name == "Karthik");
            Student student = listStudent.FirstOrDefault(x => x.Name == "Karthik");

            if(student != null)
                Console.WriteLine(string.Format("ID: {0} Name: {1}", student.StudentId, student.Name));

            //Query to get by name - all occurences
            //IEnumerable<Student> stdList = listStudent.Where(x => x.Name == "Karthik");
            IEnumerable<Student> stdList = listStudent.Where(x => x.StudentId >= 20);
            foreach (var student1 in stdList)
            {
                Console.WriteLine(string.Format("ID: {0} Name: {1}", student1.StudentId, student1.Name));
            }

            listStudent.Sort((std1, std2) => std1.Name.CompareTo(std2.Name));
            listStudent.ForEach(x=>Console.WriteLine(x.Name));
        }
コード例 #4
0
ファイル: Entity2.cs プロジェクト: Amichai/ComplexSystems
        public void InvestMoney()
        {
            int numberOfInvestments = numberOfMembers;
            //The index doing the investing:
            for(int i=0 ;i < numberOfMembers; i++){
                var investor = this.Members[i];
                List<double> partitions = new List<double>();
                //Generate N random numbers
                for (int j = 0; j < numberOfInvestments -1 ; j++) {
                    partitions.Add(rand.NextDouble());
                }
                partitions.Add(1);
                //Sort the numbers
                partitions.Sort();

                //Each partition corresponds to the investment amount in order
                //The index getting the investment
                double totalPercentInvested = 0;
                double totalMoneyInvested = 0;
                for (int j = 0; j < numberOfInvestments; j++) {
                    double percentToInvest = (partitions[j] - totalPercentInvested);
                    var investee = this.Members[j];
                    investee.TakeInvestment(investor, percentToInvest * investor.GetAssets());
                    totalMoneyInvested += percentToInvest * investor.GetAssets() ;
                    totalPercentInvested += percentToInvest;
                }
                //Debug.Print("Total percent invested: " + totalPercentInvested.ToString());
                //Debug.Print("Total monies invested: " + totalMoneyInvested.ToString());
            }
        }
コード例 #5
0
 /// <summary>
 ///     从外部文件中获取Options列表
 /// </summary>
 public static CTreeNode LoadDefines()
 {
     List<ConfigurationFileOption.Define> Definelist = new List<ConfigurationFileOption.Define>();
     Definelist = Utility.LoadObjFromXml<List<ConfigurationFileOption.Define>>(DefineFilename);
     Definelist.Sort((x, y) => { return x.Path.CompareTo(y.Path); });
     //Root Node
     var Root = new CTreeNode(string.Empty);
     foreach (var item in Definelist)
     {
         System.Diagnostics.Debug.WriteLine(item.Path);
         CTreeNode.AddToRootNode(Root, item.Path);
         ConfigurationItemDictionary.Add(item.Path, item);
     }
     return Root;
 }
コード例 #6
0
ファイル: Startup.cs プロジェクト: Producenta/TelerikAcademy
        private static void NumberThatOccurOddNumberOfTimes(List<int> numbers)
        {
            var num = new List<int>(numbers);
            num.Sort();
            int previousNumber = num[0];
            int currentNumber = 0;
            var numberOfOcc = 1;

            var oddNumbers = new List<int>();

            for (int i = 1; i < num.Count; i++)
            {
                currentNumber = num[i];
                if (currentNumber == previousNumber)
                {
                    numberOfOcc++;
                }
                else
                {
                    if (numberOfOcc % 2 == 0)
                    {
                        for (int x = 0; x < numberOfOcc; x++)
                        {
                            oddNumbers.Add(previousNumber);
                        }
                    }

                    numberOfOcc = 1;
                }

                previousNumber = currentNumber;
            }

            if (numberOfOcc % 2 == 0)
            {
                for (int x = 0; x < numberOfOcc; x++)
                {
                    oddNumbers.Add(previousNumber);
                }
            }

            Console.WriteLine("Numbers that occur odd times ");
            foreach (var oddNumber in oddNumbers)
            {
                Console.WriteLine("{0} ", oddNumber);
            }
        }
コード例 #7
0
ファイル: YAMLHelper.cs プロジェクト: universsky/MongoCola
 /// <summary>
 ///     生成YAML文件
 /// </summary>
 /// <param name="fileName"></param>
 /// <param name="Items"></param>
 public static void CreateFile(string fileName, List<string> Items)
 {
     //假定Items的格式为Path:Value
     //Value为字符串(可以带有双引号)
     StreamWriter YamlDoc = new StreamWriter(fileName, false, Encoding.UTF8);
     Items.Sort((x, y) => { return x.CompareTo(y); });
     for (int i = 0; i < Items.Count; i++)
     {
         if (i == 0)
         {
             //第一个项目
             PrintYaml(YamlDoc, 0, Items[i]);
             continue;
         }
         //从后一个字符串
         var Last = Items[i].Split(".".ToCharArray());
         var Pre = Items[i - 1].Split(".".ToCharArray());
         //表示相同段数
         int SameSegment = 0;
         for (int j = 0; j < Math.Min(Last.Length, Pre.Length); j++)
         {
             if (Last[j] != Pre[j])
             {
                 SameSegment = j;
                 break;
             }
         }
         //Items[i]去掉相同的字符首
         string RemovedItems = string.Empty;
         for (int k = SameSegment; k < Last.Length; k++)
         {
             if (k!= Last.Length - 1)
             {
                 RemovedItems += Last[k] + ".";
             }
             else
             {
                 RemovedItems += Last[k];
             }
         }
         PrintYaml(YamlDoc, SameSegment, RemovedItems);
     }
     YamlDoc.Close();
 }
コード例 #8
0
ファイル: YAMLHelper.cs プロジェクト: magicdict/MongoCola
 /// <summary>
 ///     生成YAML文件
 /// </summary>
 /// <param name="fileName"></param>
 /// <param name="items"></param>
 public static void CreateFile(string fileName, List<string> items)
 {
     //假定Items的格式为Path:Value
     //Value为字符串(可以带有双引号)
     var yamlDoc = new StreamWriter(fileName, false, Encoding.UTF8);
     items.Sort((x, y) => string.Compare(x, y, StringComparison.Ordinal));
     for (var i = 0; i < items.Count; i++)
     {
         if (i == 0)
         {
             //第一个项目
             PrintYaml(yamlDoc, 0, items[i]);
             continue;
         }
         //从后一个字符串
         var last = items[i].Split(".".ToCharArray());
         var pre = items[i - 1].Split(".".ToCharArray());
         //表示相同段数
         var sameSegment = 0;
         for (var j = 0; j < Math.Min(last.Length, pre.Length); j++)
         {
             if (last[j] != pre[j])
             {
                 sameSegment = j;
                 break;
             }
         }
         //Items[i]去掉相同的字符首
         var removedItems = string.Empty;
         for (var k = sameSegment; k < last.Length; k++)
         {
             if (k != last.Length - 1)
             {
                 removedItems += last[k] + ".";
             }
             else
             {
                 removedItems += last[k];
             }
         }
         PrintYaml(yamlDoc, sameSegment, removedItems);
     }
     yamlDoc.Close();
 }
コード例 #9
0
        public List<RouteInstance> Load(int delivery_id)
        {
            // check values
            if (delivery_id == 0)
                throw new ArgumentException("Delivery_id cannot be zero", "delivery_id");

            var list = new List<RouteInstance>();

            object[] rows;
            lock (Database.Instance)
            {
                var sql = SQLQueryBuilder.SelectFieldsWhereFieldEquals(TABLE_NAME, "delivery_id", delivery_id.ToString(), new[] { "route_id", "departure_time" });
                rows = Database.Instance.FetchRows(sql);
            }

            foreach (object[] row in rows)
            {
                int route_id = row[0].ToInt();
                DateTime departureTime = (DateTime)row[1];
                Route route = routeDataHelper.Load(route_id, true);

                list.Add(new RouteInstance(route, departureTime));
            }

            list.Sort();
            return list;
        }
コード例 #10
0
        protected IList<GithubRepository> GetRepositories()
        {
            List<GithubRepository> repositories = null;
            InvokeInGithubOperationContext(() => { repositories = PSCmdlet.GithubChannel.GetRepositories(); });

            List<GithubOrganization> organizations = null;
            InvokeInGithubOperationContext(() => { organizations = PSCmdlet.GithubChannel.GetOrganizations(); });

            List<GithubRepository> orgRepositories = new List<GithubRepository>();
            foreach (var organization in organizations)
            {
                List<GithubRepository> currentOrgRepositories = null;
                InvokeInGithubOperationContext(() => { currentOrgRepositories = PSCmdlet.GithubChannel.GetRepositoriesFromOrg(organization.Login); });
                orgRepositories.AddRange(currentOrgRepositories);
            }

            repositories.Sort();
            orgRepositories.Sort();
            repositories.AddRange(orgRepositories);
            return repositories.Where(r => r.Private == false).ToList();
        }
コード例 #11
0
ファイル: DeviceContext.cs プロジェクト: HeabKing/QMKK
        public static string GetRouterTable()
        {
            // The number of bytes needed.
            int bytesNeeded = 0;

            // The result from the API call.
            int result = GetIpNetTable(IntPtr.Zero, ref bytesNeeded, false);

            // Call the function, expecting an insufficient buffer.
            if (result != ErrorInsufficientBuffer)
            {
                // Throw an exception.
                throw new Win32Exception(result);
            }

            // Allocate the memory, do it in a try/finally block, to ensure
            // that it is released.
            IntPtr buffer = IntPtr.Zero;

            // Try/finally.
            try
            {
                // Allocate the memory.
                buffer = Marshal.AllocCoTaskMem(bytesNeeded);

                // Make the call again. If it did not succeed, then
                // raise an error.
                result = GetIpNetTable(buffer, ref bytesNeeded, false);

                // If the result is not 0 (no error), then throw an exception.
                if (result != 0)
                {
                    // Throw an exception.
                    throw new Win32Exception(result);
                }

                // Now we have the buffer, we have to marshal it. We can read
                // the first 4 bytes to get the length of the buffer.
                int entries = Marshal.ReadInt32(buffer);

                // Increment the memory pointer by the size of the int.
                IntPtr currentBuffer = new IntPtr(buffer.ToInt64() +
                   Marshal.SizeOf(typeof(int)));

                // Allocate an array of entries.
                MibIpnetrow[] table = new MibIpnetrow[entries];

                // Cycle through the entries.
                for (int index = 0; index < entries; index++)
                {
                    // Call PtrToStructure, getting the structure information.
                    table[index] = (MibIpnetrow)Marshal.PtrToStructure(new
                       IntPtr(currentBuffer.ToInt64() + (index *
                       Marshal.SizeOf(typeof(MibIpnetrow)))), typeof(MibIpnetrow));
                }

                List<string> strtable = new List<string>();
                for (int index = 0; index < entries; index++)
                {
                    MibIpnetrow row = table[index];
                    IPAddress ip = new IPAddress(BitConverter.GetBytes(row.dwAddr));

                    StringBuilder sbMac = new StringBuilder();
                    sbMac.Append(row.mac0.ToString("X2") + '-');
                    sbMac.Append(row.mac1.ToString("X2") + '-');
                    sbMac.Append(row.mac2.ToString("X2") + '-');
                    sbMac.Append(row.mac3.ToString("X2") + '-');
                    sbMac.Append(row.mac4.ToString("X2") + '-');
                    sbMac.AppendLine(row.mac5.ToString("X2"));

                    strtable.Add(string.Format("IP: {0}\t\t\tMac: {1}", ip, sbMac));
                }
                string str = "";
                strtable.Sort();
                strtable.ForEach(m => str += m);
                return str;
            }
            finally
            {
                // Release the memory.
                FreeMibTable(buffer);
            }
        }
コード例 #12
0
ファイル: GoalSelector.cs プロジェクト: fgeraci/CS195-Core
        public static IEnumerable<Candidate> GetCandidates(
            ExplorationSpace space,
            ExplorationNode start,
            ExplorationNode lastGoal,
            HashSet<uint> busyObjects,
            Scorer scorer,
            int numRecommendations,
            bool descending)
        {
            if (busyObjects == null)
                busyObjects = new HashSet<uint>();

            List<Candidate> candidates = new List<Candidate>();
            foreach (ExplorationNode node in space.Nodes)
            {
                if (start == node)
                    continue;

                // Make sure it's reachable
                ExplorationEdge[] path = start.GetPathOut(node.Id);
                if (path != null)
                {
                    // Add it as a candidate if the score is high enough
                    double score = scorer(start, node);
                    ExplorationEdge edge = path[0];
                    ExplorationNode goal = path.Last().Target;
                    double sentimentScore = SentimentScore(score, path);
                    candidates.Add(new Candidate(path, goal, sentimentScore));
                }
            }

            // Sort the candidates by score
            candidates.Sort((c1, c2) => c1.Score.CompareTo(c2.Score));
            if (descending == true)
                candidates.Reverse();

            // Add the previous goal to the front if we still have a path to it
            if (lastGoal != null)
            {
                ExplorationEdge[] oldPath = start.GetPathOut(lastGoal.Id);
                if (oldPath != null)
                    candidates.Insert(0, new Candidate(oldPath, lastGoal, 0.0));
            }

            HashSet<ExplorationNode> seenGoals = new HashSet<ExplorationNode>();
            HashSet<ExplorationEdge> seenEdges = new HashSet<ExplorationEdge>();

            // Pick the top N
            int count = 0;
            foreach (Candidate candidate in candidates)
            {
                ExplorationNode goal = candidate.Goal;
                if (candidate.Path.Length == 0)
                    continue;
                ExplorationEdge edge = candidate.Path[0];

                // Nix this event if it uses an object that's currently in use
                // TODO: Assumes only one event per edge
                TransitionEvent evt = edge.Events[0];
                foreach (uint id in evt.Participants)
                    if (busyObjects.Contains(id) == true)
                        goto skipCandidate;

                // If this is a novel direction to go, add it
                bool seenGoal = seenGoals.Contains(goal);
                bool seenEdge = seenEdges.Contains(edge);

                if (seenGoal == false && seenEdge == false)
                {
                    seenGoals.Add(goal);
                    seenEdges.Add(edge);
                    count++;
                    yield return candidate;
                }

                if (count >= numRecommendations)
                    break;

                skipCandidate : continue;
            }
        }
コード例 #13
0
        public List<WeeklyTime> Load(int route_id)
        {
            // check values
            if (route_id == 0)
                throw new ArgumentException("Route_id cannot be zero", "route_id");

            var list = new List<WeeklyTime>();
            lock (Database.Instance)
            {
                var sql = SQLQueryBuilder.SelectFieldsWhereFieldEquals(TABLE_NAME, "route_id", route_id.ToString(), new[]{ID_COL_NAME, "weekly_time"});
                var rows = Database.Instance.FetchRows(sql);

                foreach (object[] row in rows)
                {
                    int id = row[0].ToInt();
                    long ticks = (long)row[1];
                    list.Add(new WeeklyTime(ticks) { ID = id});
                }
            }

            list.Sort();
            return list;
        }
コード例 #14
0
ファイル: MailManager.cs プロジェクト: Zane0816/Mail-.Net
        private List<BsonDocument> SortMail(List<BsonDocument> MailList, BsonDocument Search)
        {
            List<BsonDocument> MailNikeName = nnm.GetAllData();
            List<BsonDocument> MailIp = im.GetAllData();
            List<BsonDocument> MailAddress = mam.GetAllData();
            List<BsonDocument> MailPhone = pm.GetAllData();
            List<BsonDocument> MailContainer = cm.GetAllData();
            foreach (BsonDocument Mail in MailList)
            {
                int Weights = 0;
                if (Mail.Contains("MailFrom"))
                {
                    foreach (BsonValue MailFrom in Mail.GetValue("MailFrom").AsBsonArray)
                    {
                        if (!MailFrom.AsBsonArray[0].IsBsonNull)
                        {
                            Weights += MailNikeName.Find((x) => x.GetValue("_id").AsObjectId == MailFrom.AsBsonArray[0].AsObjectId).GetValue("RepeatTimes").AsInt32;
                        }
                        if (!MailFrom.AsBsonArray[1].IsBsonNull)
                        {
                            Weights += MailAddress.Find((x) => x.GetValue("_id").AsObjectId == MailFrom.AsBsonArray[1].AsObjectId).GetValue("RepeatTimes").AsInt32;
                        }
                    }
                }
                if (Mail.Contains("MailTO"))
                {
                    foreach (BsonValue MailTO in Mail.GetValue("MailTO").AsBsonArray)
                    {
                        if (!MailTO.AsBsonArray[0].IsBsonNull)
                        {
                            Weights += MailNikeName.Find((x) => x.GetValue("_id").AsObjectId == MailTO.AsBsonArray[0].AsObjectId).GetValue("RepeatTimes").AsInt32;
                        }
                        if (!MailTO.AsBsonArray[1].IsBsonNull)
                        {
                            Weights += MailAddress.Find((x) => x.GetValue("_id").AsObjectId == MailTO.AsBsonArray[1].AsObjectId).GetValue("RepeatTimes").AsInt32;
                        }
                    }
                }
                if (Mail.Contains("MailCC"))
                {
                    foreach (BsonValue MailCC in Mail.GetValue("MailCC").AsBsonArray)
                    {
                        if (!MailCC.AsBsonArray[0].IsBsonNull)
                        {
                            Weights += MailNikeName.Find((x) => x.GetValue("_id").AsObjectId == MailCC.AsBsonArray[0].AsObjectId).GetValue("RepeatTimes").AsInt32;
                        }
                        if (!MailCC.AsBsonArray[1].IsBsonNull)
                        {
                            Weights += MailAddress.Find((x) => x.GetValue("_id").AsObjectId == MailCC.AsBsonArray[1].AsObjectId).GetValue("RepeatTimes").AsInt32;
                        }
                    }
                }
                if (Mail.Contains("MailBCC"))
                {
                    foreach (BsonValue MailBCC in Mail.GetValue("MailBCC").AsBsonArray)
                    {
                        if (!MailBCC.AsBsonArray[0].IsBsonNull)
                        {
                            Weights += MailAddress.Find((x) => x.GetValue("_id").AsObjectId == MailBCC.AsBsonArray[0].AsObjectId).GetValue("RepeatTimes").AsInt32;
                        }
                        if (!MailBCC.AsBsonArray[1].IsBsonNull)
                        {
                            Weights += MailAddress.Find((x) => x.GetValue("_id").AsObjectId == MailBCC.AsBsonArray[1].AsObjectId).GetValue("RepeatTimes").AsInt32;
                        }
                    }
                }
                for (int i = 0; i < Mail.GetValue("HTMLBodyIps").AsBsonArray.Count; i += 2)
                {
                    Weights += MailIp.Find((x) => x.GetValue("Ip") == Mail.GetValue("HTMLBodyIps").AsBsonArray[i].AsString).GetValue("RepeatTimes").AsInt32 * Mail.GetValue("HTMLBodyIps").AsBsonArray[i + 1].AsInt32;
                }
                for (int i = 0; i < Mail.GetValue("HTMLBodyMailAddress").AsBsonArray.Count; i += 2)
                {
                    Weights += MailAddress.Find((x) => x.GetValue("Address").AsString == Mail.GetValue("HTMLBodyMailAddress").AsBsonArray[i].AsString).GetValue("RepeatTimes").AsInt32 * Mail.GetValue("HTMLBodyMailAddress").AsBsonArray[i + 1].AsInt32;
                }
                for (int i = 0; i < Mail.GetValue("HTMLBodyPhone").AsBsonArray.Count; i += 2)
                {
                    Weights += MailPhone.Find((x) => x.GetValue("Phone") == Mail.GetValue("HTMLBodyPhone").AsBsonArray[i].AsString).GetValue("RepeatTimes").AsInt32 * Mail.GetValue("HTMLBodyPhone").AsBsonArray[i + 1].AsInt32;
                }
                for (int i = 0; i < Mail.GetValue("HTMLBodyContainer").AsBsonArray.Count; i += 2)
                {
                    Weights += MailContainer.Find((x) => x.GetValue("Container") == Mail.GetValue("HTMLBodyContainer").AsBsonArray[i].AsString).GetValue("RepeatTimes").AsInt32 * Mail.GetValue("HTMLBodyContainer").AsBsonArray[i + 1].AsInt32;
                }
                for (int i = 0; i < Mail.GetValue("TextBodyIps").AsBsonArray.Count; i += 2)
                {
                    Weights += MailIp.Find((x) => x.GetValue("Ip") == Mail.GetValue("TextBodyIps").AsBsonArray[i].AsString).GetValue("RepeatTimes").AsInt32 * Mail.GetValue("TextBodyIps").AsBsonArray[i + 1].AsInt32;
                }
                for (int i = 0; i < Mail.GetValue("TextBodyMailAddress").AsBsonArray.Count; i += 2)
                {
                    Weights += MailAddress.Find((x) => x.GetValue("Address").AsString == Mail.GetValue("TextBodyMailAddress").AsBsonArray[i].AsString).GetValue("RepeatTimes").AsInt32 * Mail.GetValue("TextBodyMailAddress").AsBsonArray[i + 1].AsInt32;
                }
                for (int i = 0; i < Mail.GetValue("TextBodyPhone").AsBsonArray.Count; i += 2)
                {
                    Weights += MailPhone.Find((x) => x.GetValue("Phone") == Mail.GetValue("TextBodyPhone").AsBsonArray[i].AsString).GetValue("RepeatTimes").AsInt32 * Mail.GetValue("TextBodyPhone").AsBsonArray[i + 1].AsInt32;
                }
                for (int i = 0; i < Mail.GetValue("TextBodyContainer").AsBsonArray.Count; i += 2)
                {
                    Weights += MailContainer.Find((x) => x.GetValue("Container") == Mail.GetValue("TextBodyContainer").AsBsonArray[i].AsString).GetValue("RepeatTimes").AsInt32 * Mail.GetValue("TextBodyContainer").AsBsonArray[i + 1].AsInt32;
                }
                Mail.Add("Weights", Weights);
            }
            MailList.Sort((X, Y) => -X.GetValue("Weights").AsInt32.CompareTo(Y.GetValue("Weights").AsInt32));
            if (MailList.Count > 1000)
            {
                return MailList.GetRange(0, 1000);
            }
            else
            {
                return MailList;
            }

        }
コード例 #15
0
        /// <summary>
        /// Converts an intermediate format content pipeline AnimationContent
        /// object to our runtime AnimationClip format.
        /// </summary>
        static AnimationClip ProcessAnimation(AnimationContent animation,
                                              Dictionary<string, int> boneMap)
        {
            List<Keyframe> keyframes = new List<Keyframe>();

            // For each input animation channel.
            foreach (KeyValuePair<string, AnimationChannel> channel in
                animation.Channels)
            {
                // Look up what bone this channel is controlling.
                int boneIndex;

                if (!boneMap.TryGetValue(channel.Key, out boneIndex))
                {
                    throw new InvalidContentException(string.Format(
                        "Found animation for bone '{0}', " +
                        "which is not part of the skeleton.", channel.Key));
                }

                // Convert the keyframe data.
                foreach (AnimationKeyframe keyframe in channel.Value)
                {
                    keyframes.Add(new Keyframe(boneIndex, keyframe.Time,
                                               keyframe.Transform));
                }
            }

            // Sort the merged keyframes by time.
            keyframes.Sort(CompareKeyframeTimes);

            if (keyframes.Count == 0)
                throw new InvalidContentException("Animation has no keyframes.");

            if (animation.Duration <= TimeSpan.Zero)
                throw new InvalidContentException("Animation has a zero duration.");

            return new AnimationClip(animation.Duration, keyframes);
        }
コード例 #16
0
        public void ShowFinalResultsInDatagrid(DataGridView dg, int sentIndex)
        {
            int i = 1;
            // simple sentence FINAL
            dg.Rows.Clear();
            foreach (var algResult in Result.Items)
            {
                List<int> wordOrders = new List<int>();
                List<string> words = new List<string>();

                foreach (var wordId in algResult.ChainWordsIds.All.Values)
                {
                    IPPI.SentenceWord word = _sentence.WordList.Find(x => (x.Id == wordId));
                    if (word != null)
                        wordOrders.Add(word.Order);
                }
                wordOrders.Add(algResult.Order);
                wordOrders.Sort();

                foreach (var wordOrder in wordOrders)
                    words.Add(_sentence.WordList.Find(x => x.Order == wordOrder).Text);

                if (words.Count > 0)
                {
                    dg.Rows.Add(i, sentIndex + 1,
                        algResult.SimpleSentenceNr,
                        string.Concat(algResult.Id, GeneralConsts.cIdsOrdersInFinalViewSeparator, string.Join(GeneralConsts.cIdsOrdersInFinalViewSeparator, algResult.ChainWordsIds.Nodes.Select(x => x.Data).ToArray())),
                        string.Join(GeneralConsts.cIdsOrdersInFinalViewSeparator, wordOrders.ToArray()),
                        string.Join(GeneralConsts.cWordsInFinalViewSeparator, words.ToArray()),
                        false
                    );
                    i++;
                }
            }
        }
コード例 #17
0
        public async Task<ActionResult> FB_TaggableFriends()
        {
            var access_token = HttpContext.Items["access_token"].ToString();
            if (access_token != null)
            {
                var appsecret_proof = access_token.GenerateAppSecretProof();

                var fb = new FacebookClient(access_token);
                dynamic myInfo = await fb.GetTaskAsync("me/taggable_friends?limit=5000".GraphAPICall(appsecret_proof));
                var friendsList = new List<FacebookFriendViewModel>();
                foreach (dynamic friend in myInfo.data)
                {
                    FacebookFriendViewModel facebookFriendViewModel = DynamicExtension.ToStatic<FacebookFriendViewModel>(friend);
                    /*
                    dynamic friendInfo = await fb.GetTaskAsync((facebookFriendViewModel.TaggingId).GraphAPICall(appsecret_proof));
                    FacebookProfileViewModel facebookProfile = DynamicExtension.ToStatic<FacebookProfileViewModel>(friendInfo);
                    facebookFriendViewModel.facebookProfileViewModel = facebookProfile;
                    */
                    friendsList.Add(facebookFriendViewModel);
                }

                friendsList.Sort(delegate (FacebookFriendViewModel x, FacebookFriendViewModel y)
                {
                    if (x.Name == null && y.Name == null) return 0;
                    else if (x.Name == null) return -1;
                    else if (y.Name == null) return 1;
                    else return x.Name.CompareTo(y.Name);
                });

                return PartialView(friendsList);
            }
            else
                throw new HttpException(404, "Missing Access Token");
        }
コード例 #18
0
        public void ShowFinalResultsInDatagrid(DataGridView dg, int sentIndex)
        {
            int i = 1;
            // simple sentence FINAL
            dg.Rows.Clear();
            foreach (var algResult in Result.Items.FindAll(x => x.IsCorrect).OrderBy(y => y.SimpleSentenceNr))
            {
                List<int> wordOrders = new List<int>();
                List<string> words = new List<string>();
                // получаем все Orders, при этом выкидываем из выборки восстановленные слова
                foreach (var wordId in algResult.ChainWordsIds.All.Values)
                {
                    Compreno.SentenceElement word = _sentence.ElementList.Find(x => (x.Id == wordId) && !x.IsRestored);
                    if (word != null)
                        wordOrders.Add(word.Order);
                }
                // если вершина является восстановленной, то не выводим ее
                if (!algResult.IsRestored)
                    wordOrders.Add(algResult.Order);
                wordOrders.Sort();

                foreach (var wordOrder in wordOrders)
                    words.Add(_sentence.ElementList.Find(x => x.Order == wordOrder).Text);

                if (words.Count > 0)
                {
                    dg.Rows.Add(i, sentIndex + 1,
                        algResult.SimpleSentenceNr,
                        string.Concat(algResult.Id, GeneralConsts.cIdsOrdersInFinalViewSeparator, string.Join(GeneralConsts.cIdsOrdersInFinalViewSeparator, algResult.ChainWordsIds.Nodes.Select(x => x.Data).ToArray())),
                        string.Join(GeneralConsts.cIdsOrdersInFinalViewSeparator, wordOrders.ToArray()),
                        string.Join(GeneralConsts.cWordsInFinalViewSeparator, words.ToArray()),
                        false
                    );
                    i++;
                }
            }
        }
コード例 #19
0
ファイル: Usr.cs プロジェクト: davelondon/dontstayin
		public void Init(Usr u)
		{
			AllMusicTypes = null;
			SelectedMusicTypes = null;
			GenericMusicTypes = null;
			SelectedPlaces = null;
			MusicQ = null;
			PlaceQ = null;
			#region Populate MusicQ and MusicTypes
			if (u.FavouriteMusicTypeK == 0 && u.MusicTypesFavouriteCount == 0)
			{
				MusicQ = new Q(true);
			}
			else
			{
				List<int> musicTypesK = new List<int>();

				#region Add MusicTypes
				if (u.MusicTypesFavouriteCount > 0)
				{
					foreach (MusicType mt in u.MusicTypesFavourite)
					{
						if (!musicTypesK.Contains(mt.K))
						{
							musicTypesK.Add(mt.K);
							AllMusicTypes.Add(mt.Order, mt);
							SelectedMusicTypes.Add(mt.Order, mt);
							AddMusicTypeChildren(mt, ref musicTypesK);
							#region Add the parent
							if (u.UpdateSendGenericMusic && mt.ParentK > 1 && !musicTypesK.Contains(mt.ParentK))
							{
								musicTypesK.Add(mt.ParentK);
								AllMusicTypes.Add(mt.Parent.Order, mt.Parent);
								GenericMusicTypes.Add(mt.Parent.Order, mt.Parent);
							}
							#endregion
						}
					}
				}
				else
				{
					if (u.FavouriteMusicTypeK != 0)
					{
						musicTypesK.Add(u.FavouriteMusicTypeK);
						AllMusicTypes.Add(u.FavouriteMusicType.Order, u.FavouriteMusicType);
						SelectedMusicTypes.Add(u.FavouriteMusicType.Order, u.FavouriteMusicType);
						AddMusicTypeChildren(u.FavouriteMusicType, ref musicTypesK);
					}
				}
				if (u.UpdateSendGenericMusic && !musicTypesK.Contains(1))
				{
					musicTypesK.Add(1);
					MusicType mtAllMusic = new MusicType(1);
					AllMusicTypes.Add(mtAllMusic.Order, mtAllMusic);
					GenericMusicTypes.Add(mtAllMusic.Order, mtAllMusic);
				}
				#endregion
				musicTypesK.Sort();
				MusicQ = new Or(musicTypesK.ConvertAll<Q>(mtk => new Q(EventMusicType.Columns.MusicTypeK, mtk)).ToArray());
			}
			#endregion
			#region Populate PlaceQ and SelectedPlaces
			List<int> placesK = new List<int>();
			if (u.HomePlaceK > 0)
			{
				placesK.Add(u.HomePlaceK);
				SelectedPlaces.Add(u.Home.Name, u.Home);
			}

			foreach (Place p in u.PlacesVisit(null, 0))
			{
				if (!placesK.Contains(p.K))
				{
					placesK.Add(p.K);
					SelectedPlaces.Add(p.Name, p);
				}
			}

			if (placesK.Count > 0)
			{
				placesK.Sort();
				PlaceQ = new Or(placesK.ConvertAll<Q>(pk => new Q(Venue.Columns.PlaceK, pk)).ToArray());
			}
			else
			{
				PlaceQ = new Q(false);
			}
			#endregion
		}
コード例 #20
0
        /// <summary>
        /// 获取Tag集合
        /// </summary>
        public List<TagInfo> GetTagList(int tid, int count)
        {
            List<TagInfo> tags = new List<TagInfo>();

            IQueryable<blog_varticle> articles=GetArticles(tid, 0,0);
            string tagstr = "";
            foreach (blog_varticle article in articles)
            {
                tagstr += article.tags.Trim() + ",";
            }

            string[] arrTag = tagstr.Split(',');
            arrTag = Utils.DistinctStringArray(arrTag);

            foreach (string a in arrTag)
            {
                if (a.Trim() != "")
                {
                    tags.Add(new TagInfo { Tag = a.Trim(), Count = Utils.RegexCount(a, tagstr) });
                }
            }
            tags.Sort(delegate(TagInfo x, TagInfo y) { return y.Count - x.Count; });

            if (count > 0)
                tags = tags.Take(count).ToList();

            return tags;
        }
コード例 #21
0
        private void SetupArrangedPaths(List<Path> paths)
        {
            arrangedByTime = new List<Path> ();
            arrangedByTime.AddRange (paths);
            arrangedByTime.Sort (new Analyzer.TimeComparer ());

            arrangedByLength = new List<Path> ();
            arrangedByLength.AddRange (paths);
            arrangedByLength.Sort (new Analyzer.Length2dComparer ());

            arrangedByDanger = new List<Path> ();
            arrangedByDanger.AddRange (paths);
            arrangedByDanger.Sort (new Analyzer.DangerComparer ());

            arrangedByDanger3 = new List<Path> ();
            arrangedByDanger3.AddRange (paths);
            arrangedByDanger3.Sort (new Analyzer.Danger3Comparer ());

            arrangedByDanger3Norm = new List<Path> ();
            arrangedByDanger3Norm.AddRange (paths);
            arrangedByDanger3Norm.Sort (new Analyzer.Danger3NormComparer ());

            arrangedByLoS = new List<Path> ();
            arrangedByLoS.AddRange (paths);
            arrangedByLoS.Sort (new Analyzer.LoSComparer ());

            arrangedByLoS3 = new List<Path> ();
            arrangedByLoS3.AddRange (paths);
            arrangedByLoS3.Sort (new Analyzer.LoS3Comparer ());

            arrangedByLoS3Norm = new List<Path> ();
            arrangedByLoS3Norm.AddRange (paths);
            arrangedByLoS3Norm.Sort (new Analyzer.LoS3NormComparer ());

            arrangedByCrazy = new List<Path> ();
            arrangedByCrazy.AddRange (paths);
            arrangedByCrazy.Sort (new Analyzer.CrazyComparer ());

            arrangedByVelocity = new List<Path> ();
            arrangedByVelocity.AddRange (paths);
            arrangedByVelocity.Sort (new Analyzer.VelocityComparer ());
        }
コード例 #22
0
		public void InsertPassJournalTestData()
		{
			IEnumerable<ShortEmployee> employees = null;
			employees = DbService.EmployeeTranslator.ShortTranslator.Get(new EmployeeFilter()).Result;
			var zoneUID = GKManager.Zones.FirstOrDefault().UID;

			Context.PassJournals.RemoveRange(Context.PassJournals);

			var random = new Random();
			foreach (var employee in employees)
			{
				for (int day = 0; day < 100; day++)
				{
					var dateTime = DateTime.Now.AddDays(-day);

					var seconds = new List<int>();
					var count = random.Next(0, 5);
					for (int i = 0; i < count * 2; i++)
					{
						var totalSeconds = random.Next(0, 24 * 60 * 60);
						seconds.Add(totalSeconds);
					}
					seconds.Sort();

					for (int i = 0; i < count * 2; i += 2)
					{
						var startTimeSpan = TimeSpan.FromSeconds(seconds[i]);
						var endTimeSpan = TimeSpan.FromSeconds(seconds[i + 1]);

						var passJournal = new PassJournal();
						passJournal.UID = Guid.NewGuid();
						passJournal.EmployeeUID = employee.UID;
						passJournal.ZoneUID = zoneUID;
						passJournal.EnterTime = new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, startTimeSpan.Hours, startTimeSpan.Minutes, startTimeSpan.Seconds);
						passJournal.ExitTime = new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, endTimeSpan.Hours, endTimeSpan.Minutes, endTimeSpan.Seconds);
						Context.PassJournals.Add(passJournal);
					}
				}
			}
			Context.SaveChanges();
		}
コード例 #23
0
 private void NickList_Updated(object sender, EventArgs e)
 {
     userList = new List<UserViewModel>();
     foreach (User user in _channel.Users)
     {
         userList.Add(new UserViewModel(user));
     }
     userList.Sort((user1, user2) => user1.CompareTo(user2));
     RaisePropertyChanged("UserList");
     RaisePropertyChanged("Name");
 }
コード例 #24
0
        /// <summary>
        ///   Review method for BitTyrant Choking/Unchoking Algorithm
        /// </summary>
        private void ExecuteTyrantReview()
        {
            // if we are seeding, don't deal with it - just send it to old method
            if (!_isDownloading)
                ExecuteReview();

            var sortedPeers = new List<PeerId>();

            foreach (var connectedPeer in _owningTorrent.Peers.ConnectedPeers)
            {
                if (connectedPeer.Connection != null)
                {
                    // update tyrant stats
                    connectedPeer.UpdateTyrantStats();
                    sortedPeers.Add(connectedPeer);
                }
            }

            // sort the list by BitTyrant ratio
            sortedPeers.Sort(delegate(PeerId p1, PeerId p2) { return p2.Ratio.CompareTo(p1.Ratio); });

            //TODO: Make sure that lan-local peers always get unchoked. Perhaps an implementation like AZInstanceManager
            //(in com.aelitis.azureus.core.instancemanager)

            // After this is complete, sort them and and unchoke until upload capcity is met
            // TODO: Should we consider some extra measures, like nascent peers, candidatePeers, optimisticUnchokeCandidates ETC.

            var uploadBandwidthUsed = 0;
            foreach (var pid in sortedPeers)
            {
                // unchoke the top interested peers till we reach the max bandwidth allotted.
                if (uploadBandwidthUsed < _owningTorrent.Settings.MaxUploadSpeed && pid.IsInterested)
                {
                    Unchoke(pid);

                    uploadBandwidthUsed += pid.UploadRateForRecip;
                }
                else
                {
                    Choke(pid);
                }
            }

            _timeOfLastReview = DateTime.Now;
            ReviewsExecuted++;
        }