public static void Main()
        {
            n = int.Parse(Console.ReadLine());
            objects = new int[n];
            arr = new int[n];
            used = new bool[n];
            values = new Dictionary<int, int>();

            for (int i = 0; i < n; i++)
            {
                objects[i] = int.Parse(Console.ReadLine());
            }

            GenerateVariationsNoRepetitions(0);
            var minValues = values.Where(v => v.Value == values.Min(x => x.Value));

            if (minValues.Count() == 1)
            {
                Console.WriteLine(minValues.FirstOrDefault().Key);
            }
            else
            {
                Console.WriteLine(minValues.OrderBy(x => x.Key).FirstOrDefault().Key);
            }
        }
        public int Down(string tableName, string primaryColumn, Int64 primaryValue, string orderColumn, Int64 orderNumber)
        {
            var data = new Dictionary<string, Int64>();
            using (DataCommand cmd = DataCommandManager.GetDataCommand("CommonDown"))
            {
                cmd.CommandText = string.Format(cmd.CommandText, tableName, primaryColumn, primaryValue, orderColumn,orderNumber);
                using (IDataReader dr = cmd.ExecuteDataReader())
                {
                    while (dr.Read())
                    {
                        if (!Convert.IsDBNull(dr[primaryColumn]) && !Convert.IsDBNull(dr[orderColumn]))
                        {
                            data.Add(dr[primaryColumn].ToString(), Convert.ToInt64(dr[orderColumn]));
                        }
                    }
                }

                if (data.Count == 1)
                {
                    return 2;
                }
                else
                {
                    string sql = "update {0} set {1}={2} where {3}={4}";

                    StringBuilder sb = new StringBuilder();
                    foreach (KeyValuePair<string, long> keyValuePair in data)
                    {
                        if (keyValuePair.Key == primaryValue.ToString())
                        {
                            sb.Append(
                                string.Format(
                                    sql,
                                    tableName,
                                    orderColumn,
                                    data.Min(s => s.Value),
                                    primaryColumn,
                                    primaryValue) + ";");

                        }
                        else
                        {
                            sb.Append(
                                string.Format(
                                    sql,
                                    tableName,
                                    orderColumn,
                                    data.Max(s => s.Value),
                                    primaryColumn,
                                    keyValuePair.Key) + ";");
                        }
                    }
                    cmd.CommandText = sb.ToString();
                    return cmd.ExecuteNonQuery();
                }
            }
        }
        public static void SetChart(Dictionary<string, int> rawValues, Chart chart)
        {
            int fmin = 0;
            int fmax = 1;

            if (rawValues.Count > 0)
            {
                fmax = rawValues.Max(x => x.Value);
                fmin = rawValues.Min(x => x.Value);
            }

            //series init
            chart.Series.Clear();
            //   chart.Tag = values;
            var s = new Series();
            s.ChartType = SeriesChartType.Bar;

            foreach (var kvp in rawValues)
            {
                s.Points.AddXY(kvp.Key, kvp.Value);
                var dpc = s.Points[s.Points.Count - 1];
                dpc.Color = ColorExtras.GetRedGreenBlendedColour(kvp.Value, 0, fmax);
                dpc.ToolTip = kvp.Key + ":" + kvp.Value;
            }

            s.YAxisType = AxisType.Primary;
            s.XAxisType = AxisType.Secondary;
            s.IsVisibleInLegend = false;
            chart.Series.Add(s);
            //chartarea init
            chart.ChartAreas.Clear();
            var ca = new ChartArea();

              //  ca.CursorX.IsUserEnabled = true;
               // ca.CursorX.IsUserSelectionEnabled = true;

            ca.AxisX2.ScrollBar.IsPositionedInside = false;
            ca.AxisX2.ScaleView.Size = zoomMax;
            ca.AxisX2.ScaleView.Position=rawValues.Count-ca.AxisX2.ScaleView.Size;

            ca.AxisX2.Interval = 1;
            ca.AxisY.Interval = MathExtras.Ceiling((Math.Abs(fmax) - Math.Abs(fmin)) / 8);
            if (ca.AxisY.Interval<1)
                ca.AxisY.Interval = 1;

            ca.AxisY.Minimum = fmin;
            ca.AxisY.Maximum = fmax;
            if (Math.Abs(ca.AxisY.Minimum - ca.AxisY.Maximum) < 1)
                ca.AxisY.Minimum--;

            s.Sort(PointSortOrder.Ascending);
            chart.ChartAreas.Add(ca);
        }
Example #4
0
        public void Save(Dictionary<string, List<News>> news)
        {
            decimal min = news.Min(n => n.Value.Min(m => m.RawScore));
            decimal max = news.Max(n => n.Value.Max(m => m.RawScore));

            using (var dbContext = new DistrictsInTownModelContainer())
            {
                foreach (var district in news)
                    AddArticlesToDB(dbContext, district, min, max);

                try
                {
                    dbContext.SaveChanges();
                }
                catch (Exception error)
                {
                    Console.WriteLine(error.StackTrace);
                }

                Console.WriteLine("Total results: {0}", news.Sum(n => n.Value.Count));
            }
        }
Example #5
0
 internal static Dictionary<DateTime, double> compute(Dictionary<DateTime, double> prices, int assetid)
 {
     bool accessbd = false;
     Dictionary<DateTime, double> returns = new Dictionary<DateTime, double>();
     DateTime first = prices.Min(t=>t.Key);
     DateTime before;
     double price = 1;
     foreach (KeyValuePair<DateTime, double> kvp in prices)
     {
         if(kvp.Key != first){
             before = kvp.Key.AddDays(-1);
             while (!prices.ContainsKey(before) && before >= first) before = before.AddDays(-1);
             if (!prices.ContainsKey(before) && before < first)
             {
                 while (1 == 1)
                 {
                     try
                     {
                         price = AccessBD.Access.get_Price_Eur(assetid, before);
                         accessbd = true;
                         break;
                     }
                     catch (ArgumentException)
                     {
                         before = before.AddDays(-1);
                     }
                 }
                 
             }
             if (accessbd == false)
             {
                 price = prices[before];
             }
             returns[kvp.Key] = Math.Log(prices[kvp.Key] / price);
         }
     }
     return returns;
 }
Example #6
0
        internal void Fold(Dictionary<Int32,FoldRegion> regions)
        {
            if (regions.Count == 0)
                return;

            var start = regions.Min(rv => rv.Key);
            var end = regions.Max(rv => rv.Value.EndLine);
            var lc =  @ref.Send(Sci.SCI_GETLINECOUNT);

            for (var i = start; i < end + 2; i++)
            {
                FoldRegion reg;

                if (regions.TryGetValue(i, out reg))
                {
                    //System.Diagnostics.Debug.WriteLine("sl=" + i + ";el=" + reg.EndLine + ";level=" + reg.Level);
                    ProcessRegion(ref i, 0, regions, reg);
                    i--;
                }
                else if (i < lc)
                    @ref.Send(Sci.SCI_SETFOLDLEVEL, i, 0 | Sci.SC_FOLDLEVELBASE);
            }
        }
        internal static Session GetUnassignedSessionWithFewestAvailableOptions(this IEnumerable<Assignment> assignments, IEnumerable<Session> sessions, SessionAvailabilityCollection sessionMatrix)
        {
            Session result = null;
            var assignedSessionIds = assignments.Where(a => a.SessionId != null).Select(a => a.SessionId);

            var sessionDictionary = new Dictionary<int, int>();
            foreach (var session in sessions.Where(s => !assignedSessionIds.Contains(s.Id)))
            {
                sessionDictionary.Add(session.Id, sessionMatrix.GetAvailableAssignmentCount(session.Id));
            }

            if (sessionDictionary.Count() > 0)
            {
                var min = sessionDictionary.Min(s => s.Value);
                var keys = sessionDictionary.Where(sd => sd.Value == min).Select(a => a.Key);
                result = sessions.Where(a => keys.Contains(a.Id))
                    .OrderByDescending(b => b.GetDependentDepth(sessions))
                    .ThenByDescending(c => c.GetDependentCount(sessions))
                    .FirstOrDefault();
            }

            return result;
        }
Example #8
0
        /// <summary>
        /// The actual scheduling procedure
        /// </summary>
        private void Runner()
        {
            var scheduled = new Dictionary<long, DateTime>();
            while (!m_terminate)
            {

                //TODO: As this is executed repeatedly we should cache it
                // to avoid frequent db lookups

                //Determine schedule list
                var lst = Program.DataConnection.Schedules;
                foreach(var sc in lst)
                {
                    if (!string.IsNullOrEmpty(sc.Repeat))
                    {
                        DateTime start;
                        DateTime last = new DateTime(0, DateTimeKind.Utc);
                        if (!scheduled.TryGetValue(sc.ID, out start))
                        {
                            start = new DateTime(sc.Time.Ticks, DateTimeKind.Utc);
                            last = sc.LastRun;
                        }

                        try
                        {
                            start = GetNextValidTime(start, last, sc.Repeat, sc.AllowedDays);
                        }
                        catch (Exception ex)
                        {
                            Program.DataConnection.LogError(sc.ID.ToString(), "Scheduler failed to find next date", ex);
                        }

                        //If time is exceeded, run it now
                        if (start <= DateTime.UtcNow)
                        {
                            var jobsToRun = new List<Server.Runner.IRunnerData>();
                            //TODO: Cache this to avoid frequent lookups
                            foreach(var id in Program.DataConnection.GetBackupIDsForTags(sc.Tags).Distinct().Select(x => x.ToString()))
                            {
                                //See if it is already queued
                                var tmplst = from n in m_worker.CurrentTasks
                                        where n.Operation == Duplicati.Server.Serialization.DuplicatiOperation.Backup
                                         select n.Backup;
                                var tastTemp = m_worker.CurrentTask;
                                if (tastTemp != null && tastTemp.Operation == Duplicati.Server.Serialization.DuplicatiOperation.Backup)
                                    tmplst.Union(new [] { tastTemp.Backup });

                                //If it is not already in queue, put it there
                                if (!tmplst.Any(x => x.ID == id))
                                {
                                    var entry = Program.DataConnection.GetBackup(id);
                                    if (entry != null)
                                        jobsToRun.Add(Server.Runner.CreateTask(Duplicati.Server.Serialization.DuplicatiOperation.Backup, entry));
                                }
                            }

                            //Caluclate next time, by adding the interval to the start until we have
                            // passed the current date and time
                            //TODO: Make this more efficient
                            int i = 50000;
                            while (start <= DateTime.UtcNow && i-- > 0)
                                try
                                {
                                    start = GetNextValidTime(start, start.AddSeconds(1), sc.Repeat, sc.AllowedDays);
                                }
                                catch(Exception ex)
                                {
                                    Program.DataConnection.LogError(sc.ID.ToString(), "Scheduler failed to find next date", ex);
                                    continue;
                                }

                            Server.Runner.IRunnerData lastJob = jobsToRun.LastOrDefault();
                            if (lastJob != null && lastJob != null)
                                lock(m_lock)
                                    m_updateTasks[lastJob] = new Tuple<ISchedule, DateTime, DateTime>(sc, start, DateTime.UtcNow);

                            foreach(var job in jobsToRun)
                                m_worker.AddTask(job);

                            if (start < DateTime.UtcNow)
                            {
                                //TODO: Report this somehow
                                continue;
                            }
                        }

                        scheduled[sc.ID] = start;
                    }
                }

                var existing = lst.ToDictionary(x => x.ID);
                Server.Serialization.Interface.ISchedule sc_tmp = null;
                //Sort them, lock as we assign the m_schedule variable
                lock(m_lock)
                    m_schedule = (from n in scheduled
                        where existing.TryGetValue(n.Key, out sc_tmp)
                        orderby n.Value
                        select existing[n.Key]).ToArray();

                // Remove unused entries
                foreach(var c in (from n in scheduled where !existing.ContainsKey(n.Key) select n.Key).ToArray())
                    scheduled.Remove(c);

                //Raise event if needed
                if (NewSchedule != null)
                    NewSchedule(this, null);

                int waittime = 0;

                //Figure out a sensible amount of time to sleep the thread
                if (scheduled.Count > 0)
                {
                    //When is the next run scheduled?
                    TimeSpan nextrun = scheduled.Min((x) => x.Value) - DateTime.UtcNow;
                    if (nextrun.TotalMilliseconds < 0)
                        continue;

                    //Don't sleep for more than 5 minutes
                    waittime = (int)Math.Min(nextrun.TotalMilliseconds, 60 * 1000 * 5);
                }
                else
                {
                    //No tasks, check back later
                    waittime = 60 * 1000;
                }

                //Waiting on the event, enables a wakeup call from termination
                // never use waittime = 0
                m_event.WaitOne(Math.Max(100, waittime), false);
            }
        }
Example #9
0
    public Dictionary<Difficulty, Song> readChart(string directory)
    {
        //read file

        var files = (string[]) Directory.GetFiles(directory);

        var stream = files.FirstOrDefault(c => (c.ToLower().Contains(".sm")) && !c.ToLower().Contains(".old")  && !c.ToLower().Contains(".dwi") && !c.Contains("._"));
        if(stream == null) stream = files.FirstOrDefault(c => (c.ToLower().Contains(".dwi"))   && !c.ToLower().Contains(".old") && !c.Contains("._"));
        if(stream == null) return null;
        StreamReader sr = new StreamReader(stream);
        songContent = sr.ReadToEnd();
        sr.Close();

        //split all line and put on a list
        var thesong = songContent.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
        List<string> listLine = new List<string>();
        listLine.AddRange(thesong);
        List<int> indexNotes = new List<int>();

        //traitement des commentaires.
        /* Non : Impossible de savoir si single ou double :(
        for(int i=0; i < listLine.Count;i++){
            if(listLine.ElementAt(i).Contains("//")){
                listLine[i] = listLine.ElementAt(i).Split("//".ToCharArray())[0];
            }
        }*/

        for(int i=0; i < listLine.Count;i++){
            if(listLine.ElementAt(i).Contains("NOTES")){
                indexNotes.Add(i);
            }
        }

        Dictionary<Difficulty, Song>  outputSongs = new Dictionary<Difficulty, Song> ();

        try{
            //get generic information
            var thetitle = listLine.FirstOrDefault(c => c.Contains("TITLE")).Split(':');
            var title = thetitle[1].Replace(";","");
            var thesubtitle = listLine.FirstOrDefault(c => c.Contains("SUBTITLE")).Split(':');
            var subtitle = thesubtitle[1].Replace(";","");
            var theartist = listLine.FirstOrDefault(c => c.Contains("ARTIST")).Split(':');
            var artist = theartist[1].Replace(";","");
            var theoffset = listLine.FirstOrDefault(c => c.Contains("OFFSET")).Split(':');
            if(theoffset[1].Contains("//")) theoffset[1] = theoffset[1].Split('/')[0]; //Special Destination fix
            var offset = System.Convert.ToDouble(theoffset[1].Replace(";",""));
            var thesamplestart = listLine.FirstOrDefault(c => c.Contains("SAMPLESTART")).Split(':');
            var samplestart = System.Convert.ToDouble(thesamplestart[1].Replace(";",""));
            var thesamplelenght = listLine.FirstOrDefault(c => c.Contains("SAMPLELENGTH")).Split(':');
            var samplelenght = System.Convert.ToDouble(thesamplelenght[1].Replace(";",""));
            //"file://" +
            var theBanner = listLine.FirstOrDefault(c => c.Contains("BANNER")).Split(':');
            var bannerTemp = "";
            if(!String.IsNullOrEmpty(theBanner[1].Replace(";","")))
            {
                bannerTemp = files.FirstOrDefault(c => c.Contains(theBanner[1].Replace(";","")));
            }else{
                bannerTemp = files.FirstOrDefault(c => (c.ToLower().Contains("bn") || c.ToLower().Contains("banner")) && (c.ToLower().Contains(".png") || c.ToLower().Contains(".jpg") || c.ToLower().Contains(".bmp") || c.ToLower().Contains(".jpeg")));
            }
            var banner = "noBanner";
            if(!String.IsNullOrEmpty(bannerTemp)){
                banner = "file://" +  bannerTemp.Replace('\\', '/');
            }
            var theBpmListMesured = new Dictionary<double, double>();
            var theStopListMesured = new Dictionary<double, double>();

            var theBpmList = new Dictionary<double, double>();
            var theStopList = new Dictionary<double, double>();

            var theBpmMesureList = new List<double>();
            var theStopMesureList = new List<double>();

            //getting bpms with mesure
            string[] thebpm = listLine.FirstOrDefault(c => c.Contains("BPMS")).Split(':');
            string thebpmline = thebpm[1];
            string[] splitbpm = thebpmline.Split(',');
            /*double previousbps = 0;
            double previoustime = 0;
            double previousmesure = 0;
            List<double> timeToMesureBPM = new List<double>();*/
            foreach(string s in splitbpm){
                string[] mysplit = s.Replace(";","").Split('=');
                if(!theBpmListMesured.ContainsKey(System.Convert.ToDouble(mysplit[0]))) theBpmListMesured.Add(System.Convert.ToDouble(mysplit[0]), System.Convert.ToDouble(mysplit[1]));
                //theBpmList.Add(previousbps == 0 ? 0 : previoustime + (System.Convert.ToDouble(mysplit[0]) - previousmesure)/previousbps, System.Convert.ToDouble(mysplit[1]));
                /*previousbps = System.Convert.ToDouble(mysplit[1])/(double)60.0;
                previoustime = theBpmList.Last().Key;
                previousmesure = System.Convert.ToDouble(mysplit[0]);
                timeToMesureBPM.Add(System.Convert.ToDouble(mysplit[0]));
                Debug.Log ("bpm : " + theBpmList.Last().Key);*/
            }

            //getting stops mesured

            int stopbegin = listLine.IndexOf(listLine.FirstOrDefault(c => c.Contains("STOPS")));
            string thestop = "";
            bool stopTheRool = false;
            if(!listLine.ElementAt(stopbegin).Contains("STOPS:;")){
                for(int i=stopbegin; !stopTheRool; i++){
                    if( listLine.ElementAt(i).Contains("//")){
                        thestop += listLine.ElementAt(i).Split('/')[0];
                    }else{
                        thestop += listLine.ElementAt(i);
                    }

                    if(listLine.ElementAt(i).Contains(";")) stopTheRool = true;
                }
                thestop = thestop.Replace("/n", "");
                thestop = thestop.Replace(";", "");
            }

            if(thestop != ""){
                string[] thestopsplit = thestop.Split(':');
                string thestopline = thestopsplit[1];
                string[] splitstop = thestopline.Split(',');
                /*previousbps = theBpmList.First().Value;
                previoustime = 0;
                previousmesure = 0;*/
                foreach(string s in splitstop){

                    var mysplit = s.Split('=');

                    theStopListMesured.Add(System.Convert.ToDouble(mysplit[0]), System.Convert.ToDouble(mysplit[1]));
                    /*
                    var theMesure = timeToMesureBPM.IndexOf(timeToMesureBPM.FirstOrDefault(d => d == timeToMesureBPM.Where(c => c <= System.Convert.ToDouble(mysplit[0])).Max()));
                    previousbps = System.Convert.ToDouble(theBpmList.ElementAt(theMesure).Value)/(double)60.0;
                    previoustime = theBpmList.ElementAt(theMesure).Key;
                    previousmesure = timeToMesureBPM.ElementAt(theMesure);

                    theStopList.Add(previoustime + ((System.Convert.ToDouble(mysplit[0])) - previousmesure)/previousbps, System.Convert.ToDouble(mysplit[1]));

                    Debug.Log("real mesure : " + (System.Convert.ToDouble(mysplit[0])) + " analyse : " + theStopList.Last().Key + " : " + theStopList.Last().Value + " : " +
                        theMesure + " previous time : " + previoustime + " previous mesure : " +
                        previousmesure + " previous bps " + previousbps + " (" + previousbps*60.0 + ") bpm");*/
                }
            }

            //change bpm and stops mesured by time
            //Bug encore.
            double previousbps = 0;
            double stoptime = 0;
            double previoustime = 0;
            double previousmesure = 0;

            while(theStopListMesured.Count != 0 && theBpmListMesured.Count != 0){
                if((theStopListMesured.First().Key < theBpmListMesured.First().Key)){

                    theStopList.Add(previoustime + stoptime + (theStopListMesured.First().Key - previousmesure)/previousbps, theStopListMesured.First().Value);
                    theStopMesureList.Add(theStopListMesured.First().Key);

                    previoustime += (theStopListMesured.First().Key - previousmesure)/previousbps;
                    previousmesure = theStopListMesured.First().Key;
                    stoptime += theStopListMesured.First().Value;

                    theStopListMesured.Remove(theStopListMesured.First().Key);

                }else if((theStopListMesured.First().Key > theBpmListMesured.First().Key)){

                    theBpmList.Add(previousbps == 0 ? 0 : previoustime + stoptime + (theBpmListMesured.First().Key - previousmesure)/previousbps, theBpmListMesured.First().Value);
                    theBpmMesureList.Add(theBpmListMesured.First().Key);

                    previoustime += (previousbps == 0 ? 0 : (theBpmListMesured.First().Key - previousmesure)/previousbps);
                    previousbps = theBpmList.Last().Value/(double)60.0;
                    previousmesure = theBpmListMesured.First().Key;

                    theBpmListMesured.Remove(theBpmListMesured.First().Key);

                }else if(theStopListMesured.First().Key == theBpmListMesured.First().Key){

                    theStopList.Add(previousbps == 0 ? 0 : previoustime + stoptime + (theStopListMesured.First().Key - previousmesure)/previousbps, theStopListMesured.First().Value);
                    theStopMesureList.Add(theStopListMesured.First().Key);

                    theBpmList.Add(previousbps == 0 ? 0 : previoustime + stoptime + (theBpmListMesured.First().Key - previousmesure)/previousbps, theBpmListMesured.First().Value);
                    theBpmMesureList.Add(theBpmListMesured.First().Key);

                    previoustime += (previousbps == 0 ? 0 : (theBpmListMesured.First().Key - previousmesure)/previousbps);
                    previousbps = theBpmList.Last().Value/(double)60.0;
                    previousmesure = theBpmListMesured.First().Key;
                    stoptime += theStopListMesured.First().Value;

                    theStopListMesured.Remove(theStopListMesured.First().Key);
                    theBpmListMesured.Remove(theBpmListMesured.First().Key);
                }

            }

            while(theStopListMesured.Count != 0){

                    theStopList.Add(previoustime + stoptime + (theStopListMesured.First().Key - previousmesure)/previousbps, theStopListMesured.First().Value);
                    theStopMesureList.Add(theStopListMesured.First().Key);

                    previoustime += (theStopListMesured.First().Key - previousmesure)/previousbps;
                    previousmesure = theStopListMesured.First().Key;
                    stoptime += theStopListMesured.First().Value;

                    theStopListMesured.Remove(theStopListMesured.First().Key);

            }

            while(theBpmListMesured.Count != 0){

                    theBpmList.Add(previousbps == 0 ? 0 : previoustime + stoptime + (theBpmListMesured.First().Key - previousmesure)/previousbps, theBpmListMesured.First().Value);
                    theBpmMesureList.Add(theBpmListMesured.First().Key);

                    previoustime += (previousbps == 0 ? 0 : (theBpmListMesured.First().Key - previousmesure)/previousbps);
                    previousbps = theBpmList.Last().Value/(double)60.0;
                    previousmesure = theBpmListMesured.First().Key;

                    theBpmListMesured.Remove(theBpmListMesured.First().Key);

            }

            var thedisplayBPM = "";
            if(listLine.FirstOrDefault(c => c.Contains("DISPLAYBPM")) != null){
                try{
                    string[] thes = listLine.FirstOrDefault(c => c.Contains("DISPLAYBPM")).Split(':');
                    if(thes.Count() > 2){
                        thedisplayBPM = System.Convert.ToDouble(thes[1].Replace(";", "")).ToString("0") + " -> " + System.Convert.ToDouble(thes[2].Replace(";", "")).ToString("0");
                    }else{
                        thedisplayBPM = System.Convert.ToDouble(thes[1].Replace(";", "")).ToString("0");
                    }
                }catch{ //Special Gravity Blast fix
                    string[] thes = listLine.FirstOrDefault(c => c.Contains("DISPLAYBPM")).Split(':');
                    var theindex = 0;
                    for(int o=0; o<thes.Count(); o++){
                        if(thes[o].Contains("DISPLAYBPM")){
                            theindex = o + 1;
                        }
                    }
                    if((thes.Count() - theindex - 1) > 2){
                        thedisplayBPM = System.Convert.ToDouble(thes[theindex].Replace(";", "")).ToString("0") + " -> " + System.Convert.ToDouble(thes[theindex+1].Replace(";", "")).ToString("0");
                    }else{
                        thedisplayBPM = System.Convert.ToDouble(thes[theindex].Replace(";", "")).ToString("0");
                    }
                }
            }else{
                var themin = theBpmList.Min(c => c.Value);
                var themax = theBpmList.Max(c => c.Value);
                if(themin == themax){
                    thedisplayBPM = themax.ToString("0");
                }else{
                    thedisplayBPM = themin.ToString("0") + " -> " + themax.ToString("0");
                }
            }

            //debug
            /*foreach(var el in theStopList){
                Debug.Log(el.Key);
            }*/

            //For all difficulties
            foreach(int index in indexNotes){

                var theNewsong = new Song();

                //easy variable getted
                theNewsong.title = title;
                theNewsong.subtitle = subtitle;
                theNewsong.artist = artist;
                theNewsong.banner = banner;
                theNewsong.offset = offset;
                theNewsong.samplestart = samplestart;
                theNewsong.samplelenght = samplelenght;
                theNewsong.bpms = theBpmList;
                theNewsong.stops = theStopList;
                theNewsong.mesureBPMS = theBpmMesureList;
                theNewsong.mesureSTOPS = theStopMesureList;
                theNewsong.bpmToDisplay = thedisplayBPM;
                /*if(files.FirstOrDefault(c => c.Contains(".ogg")) == null){
                    foreach(var fil in files){
                        Debug.Log(fil);
                    }
                }*/
                theNewsong.song = "file://" + files.FirstOrDefault(c => c.Contains(".ogg") || c.Contains(".OGG")).Replace('\\', '/');

                //getting song information
                int beginInformation = index;
                string dl = "";
                var theinfo = listLine.ElementAt(beginInformation + 1).Replace(":","").Trim();
                if(theinfo.Contains("double")){
                    dl = "D";
                }else
                if(!theinfo.Contains("single") || theinfo.Contains("pump") || theinfo.Contains("ez2") ||
                        theinfo.Contains("para") || theinfo.Contains("ds3ddx") || theinfo.Contains("pnm") ||
                        theinfo.Contains("bm") || theinfo.Contains("maniax") || theinfo.Contains("techno")){
                    dl = "STOP";
                }
                theNewsong.stepartist = listLine.ElementAt(beginInformation + 2).Replace(":","").Trim();
                theNewsong.setDifficulty(dl + listLine.ElementAt(beginInformation + 3).Replace(":","").Trim());
                theNewsong.level = System.Convert.ToInt32(listLine.ElementAt(beginInformation + 4).Replace(":","").Trim());

                //getting stepchart
                int beginstepchart = beginInformation+6;
                while(listLine.ElementAt(beginstepchart).Contains("//") ||
                    String.IsNullOrEmpty(listLine.ElementAt(beginstepchart).Trim()) ||
                    listLine.ElementAt(beginstepchart) == ""){

                        if(listLine.ElementAt(beginstepchart).Contains("NOTES")) dl = "STOP";
                        beginstepchart++;
                }

                if(listLine.ElementAt(beginstepchart).Contains("NOTES")) dl = "STOP";
                //if(theNewsong.title == "The Last Kiss") Debug.Log(listLine.ElementAt(beginstepchart));

                if(dl != "STOP"){
                    var numberOfSteps = 0;
                    var numberOfMines = 0;
                    var numberOfRoll = 0;
                    var numberOfFreezes = 0;
                    var numberOfJump = 0;
                    var numberOfStepsWJ = 0;
                    theNewsong.stepchart.Add(new List<string>());
                    for(int i = beginstepchart; !listLine.ElementAt(i).Contains(";"); i++){
                        if(listLine.ElementAt(i).Contains(",")){
                            theNewsong.stepchart.Add(new List<string>());
                        }else if(!String.IsNullOrEmpty(listLine.ElementAt(i))){
                            theNewsong.stepchart.Last().Add(listLine.ElementAt(i));
                            numberOfSteps += listLine.ElementAt(i).Count(c => c == '1');
                            numberOfSteps += listLine.ElementAt(i).Count(c => c == '2');
                            numberOfSteps += listLine.ElementAt(i).Count(c => c == '4');
                            numberOfFreezes += listLine.ElementAt(i).Count(c => c == '2');
                            numberOfRoll += listLine.ElementAt(i).Count(c => c == '4');
                            numberOfMines += listLine.ElementAt(i).Count(c => c == 'M');
                            numberOfStepsWJ += listLine.ElementAt(i).Count(c => c == '1');
                            numberOfStepsWJ += listLine.ElementAt(i).Count(c => c == '2');
                            numberOfStepsWJ += listLine.ElementAt(i).Count(c => c == '4');

                            var countmesure = listLine.ElementAt(i).Count(c => c == '1') + listLine.ElementAt(i).Count(c => c == '2') + listLine.ElementAt(i).Count(c => c == '4');
                            if(countmesure == 2){
                                numberOfStepsWJ -= countmesure;
                                numberOfJump++;
                            }
                            if(countmesure >= 3){
                                numberOfStepsWJ -= countmesure;
                            }
                        }
                    }

                    theNewsong.numberOfSteps = numberOfSteps;
                    theNewsong.numberOfFreezes = numberOfFreezes;
                    theNewsong.numberOfRolls = numberOfRoll;
                    theNewsong.numberOfMines = numberOfMines;
                    theNewsong.numberOfJumps = numberOfJump;
                    theNewsong.numberOfStepsWithoutJumps = numberOfStepsWJ;
                    //A faire le mode double !
                    if(dl == "") fakeCreation(theNewsong);
                        //A mettre
                    //if(outputSongs.ContainsKey(theNewsong.difficulty))
                    theNewsong.sip = new SongInfoProfil(theNewsong.title, theNewsong.subtitle,
                        theNewsong.numberOfSteps, theNewsong.difficulty, theNewsong.level);
                    outputSongs.Add(theNewsong.difficulty, theNewsong);
                }

            }
        }catch(Exception e){
            Debug.Log(directory + " // " + e.Message + " //st : " + e.StackTrace);
        }

        return outputSongs;
    }
Example #10
0
 // Method to return purchase order details
 public Dictionary<string, object> GetOrderDetails()
 {
     // Insert regular and purchase price into cart for each item
     foreach (Dictionary<string, object> orderItem in this.OrderItems)
     {
         // Get records related to the item
         IEnumerable<DataRow> items =
             DBHelper.GetTable("Items").Table.AsEnumerable().Where(
                 item => item["UPC"].ToString().Equals(orderItem["UPC"].ToString()));
         IEnumerable<DataRow> promotions =
             DBHelper.GetTable("Promotions").Table.AsEnumerable().Where(
                 promotion => promotion["UPC"].ToString().Equals(orderItem["UPC"].ToString()) &&
                     ((DateTime)promotion["PromotionFrom"]).CompareTo(DateTime.Now) <= 0 &&
                         ((DateTime)promotion["PromotionTo"]).CompareTo(DateTime.Now) >= 0);
         // Get name of the item
         orderItem["ItemName"] = items.First()["ItemName"].ToString();
         // Set regular price and purchase price
         double? regularPrice = null;
         double? memberPrice = null;
         double? promotionalPrice = null;
         // Regular price depends on if the customer is member
         if (this.OrderDetails["UserId"] != null)
         {
             regularPrice = double.Parse(items.First()["TenDaysPrice"].ToString());
         }
         else
         {
             regularPrice = double.Parse(items.First()["RegularPrice"].ToString());
         }
         // Get member price
         if (string.IsNullOrEmpty(items.First()["MemberPrice"].ToString()))
         {
             memberPrice = null;
         }
         else
         {
             memberPrice = double.Parse(items.First()["MemberPrice"].ToString());
         }
         // Get promotional price
         if (promotions.Count() != 0)
         {
             promotionalPrice = double.Parse(items.First()["PromotionalPrice"].ToString());
         }
         // Set regular price to item ordered
         orderItem["RegularPrice"] = regularPrice;
         Dictionary<string, double?> priceDictionary = new Dictionary<string, double?>();
         priceDictionary.Add("RegularPrice", regularPrice);
         if (this.OrderDetails["UserId"] != null)
         {
             priceDictionary.Add("MemberPrice", memberPrice);
         }
         priceDictionary.Add("PromotionalPrice", promotionalPrice);
         // Set purchase price
         if (this.OrderDetails["UserId"] != null)
         {
             double? purchasePrice = priceDictionary.Min(pair => pair.Value);
             orderItem["PurchasePrice"] = purchasePrice;
         }
         else
         {
             double? purchasePrice = priceDictionary.Min(pair => pair.Value);
             orderItem["PurchasePrice"] = purchasePrice;
         }
         // If the cart belongs to member, save the price to database
         if (this.OrderDetails["UserId"] != null)
         {
             Dictionary<string, object> updatedRecord = new Dictionary<string, object>();
             updatedRecord.Add("OrderId", orderItem["OrderId"]);
             updatedRecord.Add("UPC", orderItem["UPC"]);
             updatedRecord.Add("RegularPrice", orderItem["RegularPrice"]);
             updatedRecord.Add("PurchasePrice", orderItem["PurchasePrice"]);
             DBHelper.Update("OrderItems", updatedRecord);
         }
     }
     return this.OrderDetails;
 }
        public void DictionaryExtensions_Min_ThrowsExceptionIfDictionaryIsEmpty()
        {
            var dictionary = new Dictionary<Int32, String>();

            Assert.That(() => dictionary.Min(x => x.Key),
                Throws.TypeOf<InvalidOperationException>());
        }
        public void DictionaryExtensions_Min_ReturnsMinValue()
        {
            var dictionary = new Dictionary<Int32, String>()
            {
                {  4, "A" },
                {  5, "B" },
                {  6, "C" },
                { 99, "D" },
                { 10, "E" },
                {  1, "F" },
                { 12, "G" },
                { 45, "H" },
            };

            var result = dictionary.Min(x => x.Key);

            TheResultingValue(result).ShouldBe(1);
        }
        private Dictionary<string, double> computeNearestNeighbour(string targetUser)
        {
            Dictionary<string, double> nearestNeighbourDict = new Dictionary<string, double>();
            foreach (var user in userDictionary)
            {
                if(!user.Key.Equals(targetUser))
                {

                    double similarity = similarityStrategy.computeSimilarity(userDictionary[targetUser].userPreferenceDictionary,
                        userDictionary[user.Key].userPreferenceDictionary);
                    int targetPreferenceCount = userDictionary[targetUser].userPreferenceDictionary.Count;
                    int userPreferenceCount = userDictionary[user.Key].userPreferenceDictionary.Count;

                    if (similarity > predefinedSimilarity && userPreferenceCount > targetPreferenceCount)
                    {
                        if(nearestNeighbourDict.Count < k)
                        {
                            nearestNeighbourDict.Add(user.Key, similarity);
                        }
                        else
                        {
                            // if list is full check for the minimum similarity and remove it,
                            // to add the new user and update the predefinedSimilarity treshold.
                            // http://stackoverflow.com/questions/23734686/c-sharp-dictionary-get-the-key-of-the-min-value
                            var minUser = nearestNeighbourDict.Aggregate((x, y) => x.Value < y.Value ? x : y);
                            if (similarity > minUser.Value)
                            {
                                nearestNeighbourDict.Remove(minUser.Key);
                                nearestNeighbourDict.Add(user.Key, similarity);
                                predefinedSimilarity = nearestNeighbourDict.Min(x => x.Value);
                            }
                        }

                    }

                }
            }

            //create a new dictionary with the results sorted by descending.
            Dictionary<string, double> resultDictionary = new Dictionary<string, double>();
            foreach(var keypair in nearestNeighbourDict.OrderByDescending(x => x.Value))
            {
                resultDictionary.Add(keypair.Key, keypair.Value);
            }

            return resultDictionary;
        }
        private void PerformTeachingSerie(int wantedNoOfNodes, int changesPerPatch, int patchesPerTeachingSerie)
        {
            // patch --> its error change - lower = better
            Dictionary<NetworkPatch, double> patchesEfficiency = new Dictionary<NetworkPatch, double>();
            double serieStartError = network_.CalculateTrainingSqrError();
            int startNetworkHash = network_.GetHashCode();

            while (patchesEfficiency.Count < patchesPerTeachingSerie)
            {
            #if DEBUG
                string graphBeforePatch = network_.PrintNetworkStruct();
            #endif
                NetworkPatch patch = patchFactory_.CreateAndApplyPatch(changesPerPatch, wantedNoOfNodes);
                patchesEfficiency[patch] = network_.CalculateTrainingSqrError() - serieStartError;
            #if DEBUG
                string graphAfterPatch = network_.PrintNetworkStruct();
            #endif
                patch.Revert();
            #if DEBUG
                string graphAfterRevert = network_.PrintNetworkStruct();
                double errorAfterNotApplyingPatch = network_.CalculateTrainingSqrError();
                if (serieStartError != errorAfterNotApplyingPatch)
                {
                    Logger.Log(this, String.Format(
                        "REVERT WENT WRONG!\n" +
                        "<<<<<<<<<<<<GRAPH BEFORE PATCH >>>>>>>>>>\n{0}\n" +
                        "<<<<<<<<<<<<GRAPH AFTER PATCH >>>>>>>>>>\n{1}\n" +
                        "<<<<<<<<<<<<GRAPH AFTER REVERT >>>>>>>>>>\n{2}\n",
                        graphBeforePatch,
                        graphAfterPatch,
                        graphAfterRevert),
                        10);
                    throw new ApplicationException("revert went wrong");
                }
            #endif
            }

            //NOTE: what is interesting double.NaN is lowest possible number AND double.NaN != double.NaN //WTF??
            double bestChange = patchesEfficiency.Min(x => double.IsNaN(x.Value) ? double.PositiveInfinity : x.Value);
            Logger.Log(this, String.Format("best change {0}", bestChange));
            if (bestChange <= 0.0d && //IMPORTANT: for now only
                !double.IsInfinity(bestChange) &&
                !double.IsNaN(bestChange))
            {
                Logger.Log(this, "applying patch!");
                NetworkPatch bestPatch = patchesEfficiency.First(patch => patch.Value == bestChange).Key;
                bestPatch.Apply();
                double errorAfterApplyingPatch = network_.CalculateTrainingSqrError();
                Logger.Log(this, String.Format("error after appplying patch {0}", errorAfterApplyingPatch));
            //#if DEBUG
                if (bestChange < -1E-2)
                {
                    PrintGraphVisualization(network_);
                }
            //#endif

                double delta = 1E-4;
                if (serieStartError + bestChange - errorAfterApplyingPatch > delta)
                    throw new ApplicationException("something went rly bad");
            }
            else
            {
                Logger.Log(this, "NOT applying patch");
            }
        }
 public uint GetHeaderColumnPosition(WorksheetEntry worksheet, Dictionary<string, uint> sectionLines, string columnName)
 {
     var rowLine = sectionLines.Min(spp => spp.Value) - 1;
     var headerSectionLine = _spreadsheetFacade.GetCellsValues(worksheet, rowLine, rowLine, 1, uint.MaxValue).ToList();
     return headerSectionLine.Where(h => h.Value.Equals(columnName)).Select(h => h.Column).First();
 }
Example #16
0
        public void CalculateSegmentWidth(Bitmap bitmap, double sensitivity)
        {
            int Height = bitmap.Height;
            int Width = bitmap.Width;
            var results = new Dictionary<int, double>();

            for (int i = 0; i < Width - 1; i++)
            {
                var l = new List<Color>();
                var r = new List<Color>();
                for (int j = 0; j < Height; j++)
                {
                    l.Add(bitmap.GetPixel(i, j));
                    r.Add(bitmap.GetPixel(i + 1, j));
                }
                results.Add(i, EdgeCompareScore(l, r));

                if (SegmentWidthCalculated != null && i % 20 == 0)
                    SegmentWidthCalculated(null, new EventArgs());
            }

            double max = results.Max(x => x.Value);
            double min = results.Min(x => x.Value);
            double range = max - min;
            Dictionary<int, double> normalisedResults = results.ToDictionary(x => x.Key, x => (x.Value - min) / range);
            List<int> edgeIndexes = normalisedResults.Where(x => x.Value > sensitivity).Select(x => x.Key).ToList();
            IEnumerable<int> columnWidth =
                edgeIndexes.Where((x, idx) => idx < edgeIndexes.Count - 1 && idx >= 0).Select(
                    (x, idx) => Math.Abs(edgeIndexes[idx] - edgeIndexes[idx + 1]));
            var groupedColumnWidth = columnWidth.GroupBy(i => i).Select(g => new { g.Key, Count = g.Count() });
            SegmentWidth =
                groupedColumnWidth.Where(x => x.Count == groupedColumnWidth.Max(y => y.Count)).Select(x => x.Key).First();

            if (SegmentWidthCalculationCompleted != null)
                SegmentWidthCalculationCompleted(null, new EventArgs());
        }
Example #17
0
            private void UpdatePixelMapping(Dictionary<int, Utility.PixelMap[]> input)
            {
                for (int i = 0; i < this.pixelMapping.Length; i++)
                    this.pixelMapping[i] = -1;

                if (!input.Any())
                    return;

                int minUniverse = input.Min(x => x.Key);
                int maxUniverse = input.Max(x => x.Key);

                for (int universe = minUniverse; universe <= maxUniverse; universe++)
                {
                    Utility.PixelMap[] mapping;
                    if (!input.TryGetValue(universe, out mapping))
                        continue;

                    for (int i = 0; i < mapping.Length; i++)
                    {
                        Utility.PixelMap map = mapping[i];

                        int rgbOffset = -1;
                        switch (map.ColorComponent)
                        {
                            case Utility.ColorComponent.R:
                                rgbOffset = 2;
                                break;

                            case Utility.ColorComponent.G:
                                rgbOffset = 1;
                                break;

                            case Utility.ColorComponent.B:
                                rgbOffset = 0;
                                break;
                        }
                        if (rgbOffset == -1)
                            continue;

                        int sourcePos = map.Y * this.stride + map.X * 3 + rgbOffset;
                        if (sourcePos >= 0 && sourcePos <= this.pixelMapping.Length)
                            this.pixelMapping[sourcePos] = i + (universe - minUniverse) * 510;
                    }
                }
            }
        private void btnUpdateEvironment_Click(object sender, EventArgs e)
        {
            DateTime minEnvironmentDT = dtEnvironmentBegin.MinDate;
            DateTime maxEnvironmentDT = dtEnvironmentBegin.MaxDate;
            if (dtEnvironmentBegin.Value >= dtEnvironmentEnd.Value)
            {
                MessageBoxEx.Show(this, "<font size='18'><b>Ngày bắt đầu phải trước ngày kết thúc !</b></font>",
                        "<font size='15'><b>Thông báo</b></font>", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                dtEnvironmentBegin.Value = minEnvironmentDT;
                dtEnvironmentEnd.Value = maxEnvironmentDT;
            }
            else
            {
                if (dtEnvironmentBegin.Value < minEnvironmentDT)
                {
                    dtEnvironmentBegin.Value = minEnvironmentDT;
                }
                if (dtEnvironmentEnd.Value > maxEnvironmentDT)
                {
                    dtEnvironmentEnd.Value = maxEnvironmentDT;
                }
            }
            DateTime beginTime = dtEnvironmentBegin.Value;
            DateTime endTime = dtEnvironmentEnd.Value;

            double sum = 0;
            int avgCount = 0;
            Dictionary<byte, List<double>> dictData_X = new Dictionary<byte, List<double>>();
            Dictionary<byte, List<double>> dictData_Y = new Dictionary<byte, List<double>>();
            foreach (LogRecord lrec in LogManager.LogEntryList)
            {
                ILogEnvironment rec = lrec as ILogEnvironment;
                if (rec != null)
                {
                    if (rec.Time < beginTime || rec.Time > endTime)
                    {
                        continue;
                    }
                    sum += rec.Temperature;
                    avgCount++;

                    List<double> list_X;
                    if (!dictData_X.TryGetValue(rec.ClientID, out list_X))
                    {
                        list_X = new List<double>();
                        dictData_X.Add(rec.ClientID, list_X);
                    }
                    List<double> list_Y;
                    if (!dictData_Y.TryGetValue(rec.ClientID, out list_Y))
                    {
                        list_Y = new List<double>();
                        list_Y.Add(0);
                        dictData_Y.Add(rec.ClientID, list_Y);
                    }
                    bool isSeparate = false;
                    if (list_X.Count > 0 &&
                        (rec.Time - DateTime.FromOADate(list_X.Last())).TotalHours > 1)
                    {
                        isSeparate = true;
                    }
                    if (list_X.Count == 1)
                    {
                        list_X.Add(list_X.Last());
                    }
                    if (isSeparate)
                    {
                        list_X.Add(list_X.Last());
                        list_X.Add(rec.Time.ToOADate());
                    }
                    list_X.Add(rec.Time.ToOADate());
                    if (isSeparate)
                    {
                        list_Y.Add(0);
                        list_Y.Add(-1);
                        list_Y.Add(0);
                    }
                    if (rec.Temperature == 85)
                    {
                        if (list_Y.Count > 0)
                        {
                            list_Y.Add(list_Y.Last());
                        }
                        else
                        {
                            list_Y.Add(30);
                        }
                    }
                    else
                    {
                        list_Y.Add(rec.Temperature);
                    }
                }
            }
            sum /= avgCount;
            txtAverageTemperature.Text = sum.ToString("n2") + "\u00B0C";

            GraphPane pane = graphEnvironment.GraphPane;
            pane.Title.Text = "Lịch sử môi trường";
            pane.YAxis.Title.Text = "Nhiệt độ (\u00B0C)";
            pane.Fill = new Fill(Color.White, Color.LightGray, 45.0f);

            pane.XAxis.Type = AxisType.Date;
            pane.XAxis.Title.Text = "Thời gian";
            pane.XAxis.Scale.Format = "HH:mm dd/MM/yy";
            pane.XAxis.Scale.FontSpec.Size = 8;

            pane.CurveList.Clear();
            foreach (KeyValuePair<byte, List<double>> data in dictData_X)
            {
                data.Value.Add(data.Value.Last());
                dictData_Y[data.Key].Add(0);
                dictData_Y[data.Key].Add(-1);
                LineItem curve = pane.AddCurve("Nhiệt độ mạch " + data.Key + " (\u00B0C)",
                    data.Value.ToArray(), filterSignal(dictData_Y[data.Key].ToArray(), 5, 0, 0),
                    clientTemperatureColor[data.Key], SymbolType.None);
            }

            Graphics g = this.CreateGraphics();
            pane.YAxis.ResetAutoScale(pane, g);
            pane.XAxis.ResetAutoScale(pane, g);
            g.Dispose();
            pane.ZoomStack.Clear();
            pane.XAxis.Scale.Format = "HH:mm dd/MM/yy";

            pane.YAxis.Scale.Min = dictData_Y.Min(pair => pair.Value.FindAll(l => l > 0).Min());
            pane.YAxis.Scale.Max = dictData_Y.Max(pair => pair.Value.FindAll(l => l > 0).Max());

            graphEnvironment.AxisChange();
            graphEnvironment.Refresh();
        }
Example #19
0
 public static void normalize_graph(Dictionary<EntityLink,double> graph)
 {
     // Scales the edge weights so that the lightest is about 0.0 and the
     // heaviest is about 1.0, to within floating point errors.
     List<EntityLink> graph_keys = new List<EntityLink> (graph.Keys);
     // remove a constant offset from each edge
     double lightest_link = graph.Min(g => g.Value);
     for (int i = 0; i < graph_keys.Count; i++) {
         graph [graph_keys [i]] -= lightest_link;
     }
     // now scale everyone
     double heaviest_link = graph.Max(g => g.Value);
     for (int i = 0; i < graph_keys.Count; i++) {
         graph [graph_keys [i]] /= heaviest_link;
     }
 }
        public void DictionaryExtensions_Min_ThrowsExceptionIfDictionaryIsEmpty()
        {
            var dictionary = new Dictionary<Int32, String>();

            dictionary.Min(x => x.Key);
        }
Example #21
0
    ArrayList DetectTileMove()
    {
        #region Detect Best Moves
        List<Transform> moves = new List<Transform>();
        TakeMoves(ref moves, true);
        if (moves.Count == 0)
        {
            TakeMoves(ref moves);
            if (moves.Count == 0)
            {
                return null;
            }
        }
        moves = moves.Distinct().ToList();
        float maxAsim =  moves.Max(a => GetAsimilationCount(a.position));
        moves = moves.Where(a => GetAsimilationCount(a.position) == maxAsim).ToList();
        #endregion
        #region Create Dictionary Move/Unit
        Dictionary<Transform, Transform> targetTiles = new Dictionary<Transform, Transform>();
        float nearUnitCost;
        foreach (var move in moves)
        {
            nearUnitCost = myUnits.Min(a =>Vector3.Distance(move.position, a.transform.parent.position));
            Transform bestUnit=myUnits.First(a=>Vector3.Distance(a.transform.parent.position,move.position)==nearUnitCost).transform.parent;
            targetTiles.Add(move, bestUnit);
        }
        #endregion
        #region Best Unit/Best Move
        Transform resumeTarget=null;
        switch (level)//принятие решения соответственно уровню
        {
            case AiLevel.Easy:{
                resumeTarget = targetTiles.FirstOrDefault(a=>Vector3.Distance(a.Key.position, a.Value.position)<1.6f).Key;
                if (resumeTarget == null)
                {
                    resumeTarget = targetTiles.First().Key;
                }
                }break;

            case AiLevel.Middle: {
                nearUnitCost = targetTiles.Min(a => Vector3.Distance(a.Key.position, a.Value.position));
                resumeTarget = targetTiles.First(a => Vector3.Distance(a.Key.position, a.Value.position) == nearUnitCost).Key;
            } break;

            case AiLevel.Hard:{
                nearUnitCost = targetTiles.Min(a => Vector3.Distance(a.Key.position, a.Value.position));
                int minAroundUnit = targetTiles.Where(a => Vector3.Distance(a.Key.position, a.Value.position) == nearUnitCost)
                    .Min(a => AroundUnitCount(a.Value));
                resumeTarget = targetTiles.First(a => Vector3.Distance(a.Key.position, a.Value.position) == nearUnitCost
                    && AroundUnitCount(a.Value) == minAroundUnit).Key;
            } break;
        }
        return new ArrayList(){targetTiles[resumeTarget], resumeTarget};
        #endregion
    }
 public GCCollectionColumn(Dictionary<Benchmark, Stats> results, int generation)
 {
     ColumnName = $"Gen {generation}";
     this.results = results;
     this.generation = generation;
     opsPerGCCount = results.Min(r => r.Value?.TotalOperations ?? 0);
 }
        private string GetItem(string documentName, int nextPrevCount, string documentPath, int currentId = 0)
        {
            var localPath = ExtentionHelpers.ExchangSlash(documentPath + "/" + documentName);
            var filePaths = Directory.GetFiles(localPath);

            var dictionary = new Dictionary<int, string>();

            foreach (var item in filePaths)
            {
                if (Path.GetExtension(item).ToUpper() == ApplicationConfiguration.ImageExtension.ToUpper())
                {
                    var id = GetIds(item);
                    dictionary.Add(id, GetPath(item));
                }
            }

            var max = dictionary.Max(x => x.Key);
            var min = dictionary.Min(x => x.Key);
            var incrementCount = (nextPrevCount >= 1) ? 1 : -1;

            currentId = (nextPrevCount >= 1 && max == currentId) ? 0 : currentId;
            currentId = (nextPrevCount < 1 && min == currentId) ? max + 1 : currentId;

            var data = dictionary.FirstOrDefault(x => x.Key == currentId + incrementCount);

            return data.Value;
        }