Esempio n. 1
0
 // 接收消息线程
 static void recvProc(object arg)
 {
     while (true)
     {
         for (int i = 0; i < clients.Count; i++)
         {
             clients.ElementAt(i).recv();
         }
         Thread.Sleep(1);
     }
 }
 /// <summary>
 /// Get the last consistent detail region content.
 /// </summary>
 /// <returns>last consistent detail region content</returns>
 public string GetLastDetailRegionContent()
 {
     if (detailRegionHistory.Count > 1)
     {
         System.Diagnostics.Debug.WriteLine("[DETAIL REGION HISTORY] last entry: " + detailRegionHistory.ElementAt(1));
         return(detailRegionHistory.ElementAt(1));
     }
     else
     {
         return(String.Empty);
     }
 }
Esempio n. 3
0
        // execute configurations against Rhino engine
        private IActionResult ExecuteConfigurations(IEnumerable <RhinoConfiguration> configurations)
        {
            // process request
            var testRuns = new ConcurrentBag <RhinoTestRun>();

            foreach (var configuration in configurations)
            {
                var onConfiguration = configuration.ApplySettings(appSettings);

                var testRun = onConfiguration.Execute(types);
                testRuns.Add(testRun);
            }

            // process response body
            var content = testRuns.Count == 1
                ? JsonConvert.SerializeObject(testRuns.ElementAt(0), jsonSettings)
                : JsonConvert.SerializeObject(testRuns, jsonSettings);

            // compose response
            return(new ContentResult
            {
                Content = content,
                ContentType = MediaTypeNames.Application.Json,
                StatusCode = HttpStatusCode.OK.ToInt32()
            });
        }
Esempio n. 4
0
        /// <summary>
        /// Gets the IStringLocalizer for given type, looking also in custom ClassRessourceMappers
        /// </summary>
        /// <param name="factory"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        protected IStringLocalizer MapRessourceToType(IStringLocalizerFactory factory, Type type)
        {
            IStringLocalizer       result       = null;
            Tuple <string, string> knownMapping = null;

            Parallel.For(0, ConventionalResourceMappers.Count, (element, state) => {
                try {
                    var mapping = ConventionalResourceMappers.ElementAt(element).Invoke(type);
                    if (mapping != null)
                    {
                        knownMapping = mapping;
                        state.Break();
                    }
                }
                catch {
                    ;
                }
            });
            if (knownMapping != null)
            {
                result = CreateLocalizer(knownMapping.Item1, knownMapping.Item2, factory);
            }
            else
            {
                result = factory.Create(type);
            }
            return(result);
        }
Esempio n. 5
0
        public async Task <string> GetProduct()
        {
            //string[] serviceUrls = { "http://localhost:9040", "http://localhost:9041", "http://localhost:9042" };//产品服务的地址,可以放在配置文件或者数据库等等...

            //var consulClient = new ConsulClient(c =>
            //{
            //    c.Address = new Uri(_configuration["Consul:Address"]);
            //});

            //var services = consulClient.Health.Service("ProductService", null, true, null).Result.Response;

            //string[] serviceUrls = services.Select(p => $"http://{p.Service.Address}:{p.Service.Port}").ToArray();

            //if (!serviceUrls.Any())
            //{
            //    return await Task.FromResult("[ProductService] instance list is null");
            //}

            if (_productServiceUrls == null)
            {
                return(await Task.FromResult("[ProductService] is initializing instances..."));
            }

            // 每次随机访问一个服务实例
            var Client  = new RestClient(_productServiceUrls.ElementAt(new Random().Next(0, _productServiceUrls.Count)));
            var request = new RestRequest("/api/products", Method.GET);

            var response = await Client.ExecuteAsync(request, CancellationToken.None);

            return(response.Content);
        }
Esempio n. 6
0
        public Glass TakeGlassFromBarTop()
        {
            Glass glass = barTop.ElementAt(0);

            barTop = new ConcurrentBag <Glass>(barTop.Except(new[] { glass }));
            return(glass);
        }
Esempio n. 7
0
 public BaseLightningStrikeDay this[int index]
 {
     get
     {
         return(lightningStrikesDayList.ElementAt(index));
     }
 }
 /// <summary>
 /// 索引器
 /// </summary>
 public Shape this[int index]
 {
     get
     {
         return(shapesCore.ElementAt(index));
     }
 }
Esempio n. 9
0
        private async void button1_Click(object sender, EventArgs e)
        {
            ReadGlobal();
            var st = new ConcurrentBag <string>();

            double h1 = (x0max - x0min) / (count - 1), h2 = (x1max - x1min) / (count - 1);

            toolStripStatusLabel1.Text = "Вычисления запущены";

            IProgress <int> progress = new Progress <int>((p) => { save = p; });

            all          = ((amax - amin) / astep + 1) * count * count;
            bool[,,] mas = new bool[(amax - amin) / astep + 1, count, count];
            timer1.Start();

            await Task.Run(() => {
                int k = 0;
                for (int aa = amin; aa <= amax; aa += astep)
                {
                    Parallel.For(0, count, (int i) => {
                        // for(int i=0;i<count;i++)
                        //{
                        for (int j = 0; j < count; j++)
                        {
                            int r = GetPeriod(x0min + i *h1, x1min + j *h2, aa);
                            if (r != 0)
                            {
                                st.Add($"{aa} \t{x0min + i * h1} \t{x1min + j * h2} \t{r}");
                            }
                            mas[k, i, j] = true;
                            progress.Report(Sum(mas));
                        }
                        //  }
                    });
                    k++;
                }
            });

            timer1.Stop();

            using (StreamWriter fs = new StreamWriter("Результаты.txt"))
            {
                st.OrderBy((s) => {
                    double[] d = s.ToDoubleMas();
                    Vectors v  = new Vectors(d);
                    return(v.GetHashCode());
                });
                fs.WriteLine("a \tx0 \tx1 \tperiod");
                for (int i = 0; i < st.Count; i++)
                {
                    fs.WriteLine(st.ElementAt(i));
                }
            }

            toolStripStatusLabel1.Text  = "Вычисления окончены";
            toolStripProgressBar1.Value = 0;
            Process.Start("Результаты.txt");
        }
Esempio n. 10
0
        private Task <SensorStatus> _createRandomSensorStatus()
        {
            SensorStatus sensorStatus = new SensorStatus();

            sensorStatus.StatusType    = (StatusType)_random.Next(Enum.GetNames(typeof(StatusType)).Length);
            sensorStatus.IsAlarmStatus = _isAlarmStatus(sensorStatus.StatusType);
            sensorStatus.SensorId      = _sensors.ElementAt(_random.Next(_sensorCount)).Id;
            return(Task.FromResult(sensorStatus));
        }
Esempio n. 11
0
        public async Task <string[]> SuggestDataType()
        {
            Init(Context.PathToSourceFile);
            StreamReader reader = new StreamReader(Context.PathToSourceFile);

            if (Context.FirstRowContainsHeaders)
            {
                reader.ReadLine();
            }                                                           //toss the first line
            StringSplit = new TransformBlock <string, string[]>(row =>
            {
                return(row.Split(Context.FieldDelimiter));
            });

            ColumnAssigner = new ActionBlock <string[]>(row =>
            {
                for (int i = 0; i < row.Count(); i++)
                {
                    ColumnCollection.ElementAt(i).Push(row[i]);
                }
            });

            StringSplit.LinkTo(ColumnAssigner, new DataflowLinkOptions {
                PropagateCompletion = true
            });

            string s;

            Parallel.For(0, Context.LinesToScan, new ParallelOptions {
                MaxDegreeOfParallelism = 1
            }, x =>
            {
                x++;
                if ((s = reader.ReadLine()) != null)
                {
                    StringSplit.Post(s);
                }
            });
            StringSplit.Complete();

            await ColumnAssigner.Completion;

            DoSuggestType(Context.StringPadding);
            List <string> types = new List <string>();

            foreach (ConcurrentStack <string> type in ColumnCollection)
            {
                string HURR;
                if (type.TryPop(out HURR))
                {
                    types.Add(HURR);
                }
            }
            return(types.ToArray());
        }
Esempio n. 12
0
        public void Dispensing(bool isDispensing,
                               Hopper hopperFilling, Hopper hopperFlavor, Hopper hopperTopping,
                               ConcurrentBag <Crust> crusts, AutoResetEvent stopLucy, AutoResetEvent waitLucy)
        {
            while (isWorking)
            {
                stopLucy.WaitOne();
                isDispensing = true;



                while (!this.EnoughForDispensing(hopperFilling, 250))
                {
                    Spin.Wait(1);
                }
                this.AddFilling(crusts.ElementAt(Crust.numberOfPies - 1), hopperFilling);
                Console.WriteLine("Filling was added successfully.");


                while (!this.EnoughForDispensing(hopperFlavor, 10))
                {
                    Spin.Wait(1);
                }
                this.AddFlavour(crusts.ElementAt(Crust.numberOfPies - 1), hopperFlavor);

                Console.WriteLine("Flavor was added successfully.");


                while (!this.EnoughForDispensing(hopperTopping, 100))
                {
                    Spin.Wait(1);
                }
                this.AddTopping(crusts.ElementAt(Crust.numberOfPies - 1), hopperTopping);

                Console.WriteLine("Topping was added successfully.");

                isDispensing = false;
                waitLucy.Set();
            }
        }
Esempio n. 13
0
        public async Task <string> GetProduct(string accessToken)
        {
            if (_productServiceUrls == null)
            {
                return(await Task.FromResult("【產品服務】正在初始化服務列表…"));
            }

            var Client  = new RestClient(_productServiceUrls.ElementAt(RandomNumberGenerator.GetInt32(0, _productServiceUrls.Count)));
            var request = new RestRequest("/products", Method.GET);

            var response = await Client.ExecuteAsync(request);

            return(response.Content);
        }
Esempio n. 14
0
        public async Task <string> GetOrder(string accessToken)
        {
            if (_orderServiceUrls == null)
            {
                return(await Task.FromResult("【訂單服務】正在初始化服務列表…"));
            }

            // 每次隨機訪問一個服務實例
            var Client  = new RestClient(_orderServiceUrls.ElementAt(RandomNumberGenerator.GetInt32(0, _orderServiceUrls.Count)));
            var request = new RestRequest("/orders", Method.GET);

            var response = await Client.ExecuteAsync(request);

            return(response.Content);
        }
Esempio n. 15
0
 static void UpdateScrappedEmailsOnConsole()
 {
     lock (locker)
     {
         Console.SetCursorPosition(0, 22);
         Console.WriteLine(new string('*', Console.WindowWidth));
         for (int i = 0; i < HarvestedEmails.Count && i < 10; i++)
         {
             var oldpos = Console.CursorTop;
             Console.Write(new string(' ', Console.BufferWidth));
             Console.SetCursorPosition(0, oldpos);
             Console.WriteLine(HarvestedEmails.ElementAt(i));
         }
     }
 }
Esempio n. 16
0
        public async Task <string> GetCYPlanningAsync()
        {
            if (cyplanningServiceUrls == null)
            {
                return(await Task.FromResult("服务列表为空"));
            }
            //健康的服务
            var services = consulClient.Health.Service("cyplanningservice", null, true, null).Result.Response;

            var client = new HttpClient();
            //每次随机访问一个服务实例
            var result = await client.GetAsync(cyplanningServiceUrls.ElementAt(new Random().Next(0, cyplanningServiceUrls.Count)) + "/cyplanning");

            return(await result.Content.ReadAsStringAsync());
        }
        public async Task <string> GetProduct()
        {
            if (_productServiceUrls == null)
            {
                return(await Task.FromResult("【产品服务】正在初始化服务列表..."));
            }

            //每次随机访问一个服务实例
            var Client  = new RestClient(_productServiceUrls.ElementAt(new Random().Next(0, _productServiceUrls.Count())));
            var request = new RestRequest("/product", Method.GET);

            var response = await Client.ExecuteAsync(request);

            return(response.Content);
        }
Esempio n. 18
0
        public async Task <string> GetOrder(string accessToken)
        {
            if (_orderServiceUrls == null)
            {
                return(await Task.FromResult("【订单服务】正在初始化服务列表..."));
            }

            //每次随机访问一个服务实例
            var client  = new RestClient(_orderServiceUrls.ElementAt(new Random().Next(0, _orderServiceUrls.Count())));
            var request = new RestRequest("/orders", Method.GET);

            var response = await client.ExecuteAsync(request);

            return(response.Content);
        }
Esempio n. 19
0
        internal void ExportStatistics()
        {
            string guidFilename    = Guid.NewGuid().ToString();
            string filenameSummary = "summary." + guidFilename + ".txt";
            string filenameDetails = "details." + guidFilename + ".txt";

            System.IO.File.AppendAllText(filenameSummary, string.Format("{0}\r\n", guidFilename));
            System.IO.File.AppendAllText(filenameSummary, "Rung\tFinshd\tTotal\tTimeout\tError\tExClient\r\n");
            System.IO.File.AppendAllText(filenameSummary, string.Format("{0:0000}\t{1:0000}\t{2:0000}\t{3:0000}\t{4:0000}\t{5:0000}\r\n", running, finished, total, timeout, error, ExClient));

            TimeSpan totalduration   = new TimeSpan(0);
            TimeSpan minimumduration = new TimeSpan(24000000);
            TimeSpan maximumduration = NegativeTimeSpan.Duration;

            for (int i = 0; i < Durations.Count; i++)
            {
                var actualDuration = Durations.ElementAt(i);

                if (actualDuration.Duration > NegativeTimeSpan.Duration)
                {
                    totalduration += actualDuration.Duration;
                    if (actualDuration.Duration < minimumduration)
                    {
                        minimumduration = actualDuration.Duration;
                    }
                    if (actualDuration.Duration > maximumduration)
                    {
                        maximumduration = actualDuration.Duration;
                    }
                }

                System.IO.File.AppendAllText(filenameDetails, string.Format("{0}\t{1}\t{2}\t{3}\r\n",
                                                                            guidFilename,
                                                                            listrunning.ElementAt(i),
                                                                            actualDuration.Duration.Ticks,
                                                                            actualDuration.When.ToString("HH:mm:sss")));
            }

            var average = new TimeSpan(totalduration.Ticks / Durations.Count);

            System.IO.File.AppendAllText(filenameSummary, string.Format("Minimum Duration:{0}\r\n", minimumduration));
            System.IO.File.AppendAllText(filenameSummary, string.Format("Maximum Duration:{0}\r\n", maximumduration));
            System.IO.File.AppendAllText(filenameSummary, string.Format("Average Duration:{0}\r\n", average));
            for (int i = 0; i < Errors.Count; i++)
            {
                System.IO.File.AppendAllText(filenameSummary, string.Format("{0}\r\n", Errors.ElementAt(i)));
            }
        }
Esempio n. 20
0
        public string[] SuggestDataType()
        {
            Init(Context.SourceFilePath); //initialize variables

            //put the first x lines into variables, order by column
            using (StreamReader reader = new StreamReader(Context.SourceFilePath))
            {
                var delimiterAsString = Context.Delimiter.ToString();
                if (Context.FirstLineContainsHeaders)
                {
                    reader.ReadLine();
                }                                                           //skip header line
                if (Context.SourceFileIsSourcedFromDial)
                {
                    reader.ReadLine();
                }                                                               //skip extra line for DIAL data
                string   line;
                string[] splitLine;
                for (int x = 0; x < ConfigVariables.Instance.Type_Suggestion_Sample_Lines_To_Scan; x++)
                {
                    if ((line = reader.ReadLine()) != null)
                    {
                        splitLine = StringAndText.SplitRow(line, delimiterAsString, "\"", false);
                        for (int i = 0; i < splitLine.Count(); i++)
                        {
                            ColumnCollection.ElementAt(i).Push(splitLine[i]);
                        }
                    }
                }
            }

            //suggest datatypes and push these on the stacks

            DoSuggestType(Context.StringPadding);
            List <string> types = new List <string>();

            foreach (ConcurrentStack <string> type in ColumnCollection)
            {
                string HURR;
                if (type.TryPop(out HURR))
                {
                    types.Add(HURR);
                }
            }
            return(types.ToArray());
        }
Esempio n. 21
0
        public async Task <string> GetOrderService()
        {
            if (_serviceBUrls == null)
            {
                return(await Task.FromResult("Order Service Initializing..."));
            }

            using var httpClient = _httpClient.CreateClient();

            //随机获取一个服务地址调用
            var serviceUrl = _serviceBUrls.ElementAt(new Random().Next(_serviceBUrls.Count()));

            Console.WriteLine("Order Service:" + serviceUrl);

            var result = await httpClient.GetStringAsync($"{serviceUrl}/order");

            return(result);
        }
        public void IdleVisitors_HasSomeIdleVisitors_ExpectSomeIdleVisitors()
        {
            ConcurrentBag <Visitor> visitors = new ConcurrentBag <Visitor>()
            {
                new Visitor(),
                new Visitor(),
                new Visitor(),
                new Visitor(),
                new Visitor()
            };

            for (int i = 0; i < visitors.Count; i++)
            {
                if (i is 0 or 2 or 3)
                {
                    Visitor visitor = visitors.ElementAt(i);
                    visitor.AvailableAt = DateTime.Now;
                }
            }

            VisitorRepository visitorRepository = new(random, loggerMock.Object, visitors);

            Assert.Equal(3, visitorRepository.IdleVisitors().Count);
        }
Esempio n. 23
0
 protected void DoWork()
 {
     _workerThread = new Thread(async() =>
     {
         while (true)
         {
             Thread.Sleep(Precision);
             for (var i = 0; i < Works.Count; i++)
             {
                 var work = Works.ElementAt(i);
                 if (work?.Status == TaskStatus.Created)
                 {
                     work.Start();
                 }
                 else if (work?.Status == TaskStatus.Faulted)
                 {
                     var ex      = work.Exception;
                     var faulted = work.IsFaulted;
                     if (faulted && ex != null)
                     {
                         await Debug.AddMessage_Async <object>(new Message <object>("[" + GetType().Name + "]  request faulted." + " |TaskID[" + work.Id + "]"
                                                                                    + " |TaskResult[" + work?.Exception?.Message + "]", MessageTypeEnum.Error)).ConfigureAwait(false);
                         await Debug.AddMessage_Async <object>(new Message <object>(ex.Data, MessageTypeEnum.Exception)).ConfigureAwait(false);
                         Works.TryTake(out work);
                     }
                     ;
                 }
                 if (i < Works.Count && work?.Status == TaskStatus.RanToCompletion)
                 {
                     Works.TryTake(out work);
                 }
             }
         }
     });
     _workerThread.Start();
 }
Esempio n. 24
0
        private void cancelTaskButton_Click(object sender, EventArgs e)
        {
            var test = processingStack.SelectedIndex;

            processingTasks.ElementAt(test).cTokenSource.Cancel();
        }
Esempio n. 25
0
        static void Main(string[] args)
        {
            DateTime       start = DateTime.Now;
            ConsoleSpinner spin  = new ConsoleSpinner();

            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Debug()
                         .WriteTo.Console()
                         .WriteTo.File("log.txt")
                         .CreateLogger();
            //string dir = @"c:\Users\AL\Documents\Visual Studio 2017\Projects\DupFinder\test";
            string dir = @"B:\DiskE\BACKUP";

            Log.Information("Analyzing {0}...", dir);
            DirectoryInfo dirInfo = new DirectoryInfo(dir);

            var files = dirInfo.EnumerateDirectories()
                        .AsParallel()
                        .SelectMany(di => di.EnumerateFiles("*.*", SearchOption.AllDirectories))
                        .Where(x => Array.IndexOf(Ext, x.Extension.ToLowerInvariant()) >= 0)
                        .ToArray();

            TimeSpan duration = DateTime.Now - start;

            Log.Information("Found {0} file(s), duration {1} sec", files.Count(), duration.TotalSeconds);

            Log.Information("Calculating images' hashes...");
            CvErrorCallback cvErr = CVError;
            IntPtr          zero  = IntPtr.Zero;

            NativeMethods.redirectError(cvErr, zero, ref zero);
            Console.SetError(TextWriter.Null);

            int c = 0;

            Parallel.ForEach(files, f => {
                try {
                    RadialVarianceHash h1 = RadialVarianceHash.Create();
                    BlockMeanHash h2      = BlockMeanHash.Create();
                    byte[] data           = System.IO.File.ReadAllBytes(f.FullName);
                    using (Mat mat = Mat.FromImageData(data, ImreadModes.Color)) {
                        InputOutputArray h1o = new Mat();
                        InputOutputArray h2o = new Mat();

                        h1.Compute(mat, h1o);
                        h2.Compute(mat, h2o);

                        Files.Add(new File {
                            FileInfo           = f,
                            RadialVarianceHash = h1o,
                            BlockMeanHash      = h2o,
                        });
                        spin.Turn((double)(c++) / (double)files.Count());
                    }
                } catch (Exception ex) {
                    if (ex.Source != "OpenCvSharp")
                    {
                        Log.Error("Error with {0}:\n\t{1}", f.FullName, ex.Message);
                    }
                }
            });

            Log.Information("Finding duplicates...");
            RadialVarianceHash hh1 = RadialVarianceHash.Create();
            BlockMeanHash      hh2 = BlockMeanHash.Create();
            ulong saveSize         = 0;
            bool  dupMsg           = true;
            int   total            = Files.Count;
            int   counter          = 0;

            for (int x = 0; x < Files.Count; x++)
            {
                if (Files.ElementAt(x).Duplicate != true)
                {
                    counter++;
                    dupMsg = true;
                    for (int y = x + 1; y < Files.Count; y++)
                    {
                        if (Files.ElementAt(y).Duplicate == true)
                        {
                            continue;
                        }
                        double compare1 = hh1.Compare(InputArray.Create(Files.ElementAt(x).RadialVarianceHash.GetMat()), InputArray.Create(Files.ElementAt(y).RadialVarianceHash.GetMat()));
                        double compare2 = hh2.Compare(InputArray.Create(Files.ElementAt(x).BlockMeanHash.GetMat()), InputArray.Create(Files.ElementAt(y).BlockMeanHash.GetMat()));
                        if (compare1 > 0.98 && compare2 < 3)
                        {
                            saveSize += (ulong)Files.ElementAt(x).FileInfo.Length;
                            Files.ElementAt(y).Duplicate = true;
                            total--;
                            if (dupMsg)
                            {
                                Log.Information("Dups for {0}:", Files.ElementAt(x).FileInfo.FullName);
                                dupMsg = false;
                            }
                            Log.Information("\t{0}", Files.ElementAt(y).FileInfo.FullName);
                        }
                        spin.Turn((double)counter / (double)total);
                    }
                }
                spin.Turn((double)counter / (double)total);
            }
            Log.Information("Done, possible size save is {0} Mb", saveSize / 1024 / 1024);
            Console.ReadKey();
        }
Esempio n. 26
0
        private static double Mean(ConcurrentBag <double> xs)
        {
            var ys = xs.OrderBy(x => x).ToList();

            return((xs.ElementAt(ys.Count / 2) + ys.ElementAt((ys.Count - 1) / 2)) / 2);
        }
Esempio n. 27
0
        /// <summary>
        /// Сшивка снимков правого глаза
        /// </summary>
        private void rightDRAWING()
        {
            List<Int32> x = new List<Int32>(7);
            List<Int32> y = new List<Int32>(7);
            Int32 iPoint_number;

            //Double x1 = 850, y1 = 750;

            //Расставляем снимки по схеме
            x.Add(1050); y.Add(1150); //1
            x.Add(1050); y.Add(600);  //2
            x.Add(550);  y.Add(700);  //3
            x.Add(450);  y.Add(1150); //4
            x.Add(550);  y.Add(1600); //5
            x.Add(1050); y.Add(1700); //6
            x.Add(1550); y.Add(1600); //7
            x.Add(1650); y.Add(1150); //8
            x.Add(1550); y.Add(700);  //9

            Int32 check = 0;

            //Сомещаем, если есть общие ключевые точки
            //-Для первых трех снимков
            for (Int32 i = 0; i < 3; i++)
            {
                iPointPairs = CreatePairs(iPoints_right[i], iPoints_right[i + 1]);
                iPoint_number = bestIPoint_idSearch();

                if (iPoint_number != -1)
                {
                    Double x1 = iPointPairs.ElementAt(iPoint_number).p1.x - iPointPairs.ElementAt(iPoint_number).p2.x;
                    Double y1 = iPointPairs.ElementAt(iPoint_number).p1.y - iPointPairs.ElementAt(iPoint_number).p2.y;

                    x[i + 1] = Convert.ToInt32(x[i] + x1);
                    y[i + 1] = Convert.ToInt32(y[i] + y1);
                    check++;
                }
            }
            //-Для 4го и 5го снимков
            for (Int32 i = 3; i < 5; i++)
            {
                iPointPairs = CreatePairs(iPoints_right[1], iPoints_right[i]);
                iPoint_number = bestIPoint_idSearch();

                if (iPoint_number != -1)
                {
                    Double x1 = iPointPairs.ElementAt(iPoint_number).p1.x - iPointPairs.ElementAt(iPoint_number).p2.x;
                    Double y1 = iPointPairs.ElementAt(iPoint_number).p1.y - iPointPairs.ElementAt(iPoint_number).p2.y;

                    x[i] = Convert.ToInt32(x[1] + x1);
                    y[i] = Convert.ToInt32(y[1] + y1);
                    check++;
                }
            }
            //-Для 6го и 7го снимков
            for (Int32 i = 5; i < 7; i++)
            {
                iPointPairs = CreatePairs(iPoints_right[0], iPoints_right[i]);
                iPoint_number = bestIPoint_idSearch();

                if (iPoint_number != -1)
                {
                    Double x1 = iPointPairs.ElementAt(iPoint_number).p1.x - iPointPairs.ElementAt(iPoint_number).p2.x;
                    Double y1 = iPointPairs.ElementAt(iPoint_number).p1.y - iPointPairs.ElementAt(iPoint_number).p2.y;

                    x[i] = Convert.ToInt32(x[0] + x1);
                    y[i] = Convert.ToInt32(y[0] + y1);
                    check++;
                }
            }

            MessageBox.Show((9-check).ToString() + " снимков из 9 будут расположены по предустановленным координатам", "Информация", MessageBoxButtons.OK, MessageBoxIcon.Information);

            Bitmap img = new Bitmap(5000, 4500);

            Graphics g = Graphics.FromImage(img);
            Rectangle rect = new Rectangle(0, 0, img.Width, img.Height);

            SolidBrush blck = new SolidBrush(Color.Black);

            Region fill = new Region(rect);
            g.FillRegion(blck, fill);

            /*
            for (Int32 i = x.Count - 1; i >= 0; i--)
                g.DrawImage(eyeImages_right[i], new Point(x[i], y[i]));
            */

            for (Int32 i = x.Count - 1; i >= 0; i--)
                if (i == 8 || i == 6 || i == 4 || i == 2) g.DrawImage(eyeImages_right[i], new Point(x[i], y[i]));

            for (Int32 i = x.Count - 1; i >= 0; i--)
                if (i == 7 || i == 5 || i == 3 || i == 1 || i == 0) g.DrawImage(eyeImages_right[i], new Point(x[i], y[i]));

            pictureImage.Image = img;

            eyeImages_right.Add(img);
            rightListBox.Items.Add("Результат сшивки");
        }
Esempio n. 28
0
            private void ExportAll(List <SwiftContainerModel> containers, string path, Dictionary <string, string> queryParams = null)
            {
                foreach (var container in containers)
                {
                    listQueue.Enqueue(new ContainerRequest
                    {
                        Container = container.Container,
                        Query     = queryParams
                    });
                }

                while (!listQueue.IsEmpty)
                {
                    ContainerRequest request = null;

                    if (listQueue.TryDequeue(out request))
                    {
                        var containerData = client.GetContainer(request.Container, null, request.Query).Result;
                        if (containerData.IsSuccess)
                        {
                            if (containerData.Objects.Count > 0)
                            {
                                if (containerData.Objects.Count < containerData.ObjectsCount)
                                {
                                    var marker = containerData.Objects.OrderByDescending(x => x.Object).Select(x => x.Object).FirstOrDefault();

                                    var newRequest = new ContainerRequest()
                                    {
                                        Container = request.Container,
                                        Query     = request.Query
                                    };

                                    if (newRequest.Query == null)
                                    {
                                        newRequest.Query = new Dictionary <string, string>();
                                    }

                                    newRequest.Query["marker"] = marker;

                                    listQueue.Enqueue(newRequest);
                                }

                                var target = Path.Combine(path, request.Container);

                                if (!Directory.Exists(target))
                                {
                                    Directory.CreateDirectory(target);
                                }

                                EnqueueObjects(request.Container, containerData.Objects, target);
                            }
                        }
                    }
                }

                if (downloadBag.Any())
                {
                    Console.Write("Exporting... ");

                    var objCount = downloadBag.Count;

                    var progress = new ProgressBar();

                    Parallel.For(0, objCount - 1, new ParallelOptions {
                        MaxDegreeOfParallelism = 10
                    },
                                 i =>
                    {
                        var downloadObj = downloadBag.ElementAt(i);

                        try
                        {
                            var response = ExportObject(downloadObj).Result;

                            Interlocked.Increment(ref counter);

                            if (!response.IsSuccess)
                            {
                                ManageFailed(new FailedObject
                                {
                                    Container = downloadObj.Container,
                                    Message   = response.Message,
                                    Object    = downloadObj.Object
                                });
                            }
                        }
                        catch (Exception ex)
                        {
                            ManageFailed(new FailedObject
                            {
                                Container = downloadObj.Container,
                                Message   = ex.Message,
                                Object    = downloadObj.Object
                            });
                        }

                        progress.Report((double)counter / objCount);
                    });

                    progress.Report(1);
                    progress.Dispose();
                    Console.WriteLine(" Done.");
                }

                if (failedQueue.Any())
                {
                    Console.WriteLine($"Failed objects: ");

                    var table = failedQueue.ToStringTable(
                        u => u.Container,
                        u => u.Object.Object,
                        u => u.Message
                        );
                    Console.WriteLine(table);
                }
            }
Esempio n. 29
0
        public static Tuple <int, int, int> PupilCenter(int borderColor, ByteImage bitmap)
        {
            int threads = 8;

            ByteImage[]         pictures = new ByteImage[threads];
            ConcurrentBag <int> Xs       = new ConcurrentBag <int>();
            ConcurrentBag <int> Ys       = new ConcurrentBag <int>();
            ConcurrentBag <int> Rs       = new ConcurrentBag <int>();

            for (int i = 0; i < threads; i++)
            {
                pictures[i] = new ByteImage(bitmap);
            }
            int borderValue      = (int)((0.85 * (double)borderColor) / 3);
            int centerX          = (int)bitmap.Width / 2;
            int centerY          = (int)bitmap.Height / 2;
            int R                = 1;
            int verticalMargin   = (int)bitmap.Height / 4;
            int horizontalMargin = (int)bitmap.Width / 4;

            int w = (int)bitmap.Width / threads;

            Parallel.For(0, threads, i =>
                         //for (int i = 0; i < threads; i++)
            {
                int tempX = 0;
                int tempY = 0;
                int tempR = 0;
                for (int x = i * w; x < (i + 1) * w; x++)
                {
                    for (int y = 0; y < pictures[i].Height; y++)
                    {
                        if (x > horizontalMargin && x < pictures[i].Width - horizontalMargin && y > verticalMargin && y < pictures[i].Height - verticalMargin)
                        {
                            if (x == pictures[i].Width / 2 && y == pictures[i].Height / 2)
                            {
                                Console.WriteLine("test");
                            }
                            if (pictures[i].Pixels[pictures[i].getPixelIndex(x, y) + 1] == 0)
                            {
                                int currR       = 0;
                                int[] contrasts = FindContrasts((int)pictures[i].Width / 4, x, y, pictures[i]);
                                for (int c = 0; c < contrasts.Length; c++)
                                {
                                    if (contrasts[c] >= borderValue)
                                    {
                                        currR = c;
                                        break;
                                    }
                                }
                                if (currR > tempR)
                                {
                                    tempX = x;
                                    tempY = y;
                                    tempR = currR;
                                }
                            }
                        }
                    }
                }
                Xs.Add(tempX);
                Ys.Add(tempY);
                Rs.Add(tempR);
            });
            //}

            for (int i = 0; i < threads; i++)
            {
                if (Rs.ElementAt(i) > R)
                {
                    R       = Rs.ElementAt(i);
                    centerX = Xs.ElementAt(i);
                    centerY = Ys.ElementAt(i);
                }
            }

            return(new Tuple <int, int, int>(centerX, centerY, R));
        }
Esempio n. 30
0
        public static Tuple <int, int, int> Iris(int borderColor, ByteImage bitmap, int px, int py, int pr)
        {
            if (px == 0 || py == 0 || pr == 0)
            {
                return(new Tuple <int, int, int>(-1, -1, -1));
            }
            int threads = 8;

            ByteImage[]         pictures = new ByteImage[threads];
            ConcurrentBag <int> Xs       = new ConcurrentBag <int>();
            ConcurrentBag <int> Ys       = new ConcurrentBag <int>();
            ConcurrentBag <int> Rs       = new ConcurrentBag <int>();

            for (int i = 0; i < threads; i++)
            {
                pictures[i] = new ByteImage(bitmap);
            }
            int borderValue = (int)(((double)borderColor / 5) * 3);
            int centerX     = px;
            int centerY     = py;
            int R           = pr;

            int w = 12 / threads;

            Parallel.For(0, threads, i =>
                         //for (int i = 0; i < threads; i++)
            {
                int tempX = 0;
                int tempY = 0;
                int tempR = 0;
                //for (int x = px - (i * w); x < px + ((i + 1) * w); x++)
                //{
                // for (int y = py - 9; y < py + 9; y++)
                // {
                //if (pictures[i].Pixels[pictures[i].getPixelIndex(x, y) + 1] == 0)
                //{
                int currR       = 0;
                tempX           = px;
                tempY           = py;
                int[] contrasts = FindContrasts((int)pictures[i].Width / 4 + pr, px, py, pictures[i], (pr + 10));
                for (int c = 0; c < contrasts.Length; c++)
                {
                    if (contrasts[c] >= borderValue)
                    {
                        currR = c;
                        break;
                    }
                }
                if (currR > tempR)
                {
                    tempR = currR;
                }
                //}
                // }
                // }
                Xs.Add(tempX);
                Ys.Add(tempY);
                Rs.Add(tempR);
            });
            //}

            for (int i = 0; i < threads; i++)
            {
                if (Rs.ElementAt(i) > R)
                {
                    R       = Rs.ElementAt(i);
                    centerX = Xs.ElementAt(i);
                    centerY = Ys.ElementAt(i);
                }
            }
            R = R + pr;
            return(new Tuple <int, int, int>(centerX, centerY, R));
        }
Esempio n. 31
0
        /// <summary>
        /// Get the remote server.
        /// </summary>
        /// <param name="algorithmType">The algorithm type.</param>
        /// <returns>The remote server.</returns>
        private RemoteServer GetRemoteServer(AlgorithmType algorithmType)
        {
            // Make sure remotes servers exist.
            if (_remoteServers != null && _remoteServers.Count > 0)
            {
                RemoteServer remoteServer = null;

                // Select the algorithm type.
                switch (algorithmType)
                {
                case AlgorithmType.LeastConnections:
                    // Get the remote server that has the least connections.
                    // Get the name of the server this client will connect to.
                    // Get the server that has the least amount of connections.
                    long minimum = _remoteServers.Min(u => u.Count);
                    remoteServer        = _remoteServers.First(u => u.Count <= minimum);
                    remoteServer.Count += 1;
                    break;

                case AlgorithmType.RoundRobin:
                    // Get the next remote server.
                    // If the server count is the same or greater
                    // than the current index then restore to zero
                    // the first remote server.
                    if (_remoteServers.Count <= _currentRemoteServerIndex)
                    {
                        _currentRemoteServerIndex = 0;
                        remoteServer        = _remoteServers.First();
                        remoteServer.Count += 1;
                    }
                    else
                    {
                        remoteServer               = _remoteServers.ElementAt(_currentRemoteServerIndex);
                        remoteServer.Count        += 1;
                        _currentRemoteServerIndex += 1;
                    }
                    break;

                case AlgorithmType.UserDefined:
                    // A user defined algorithm.
                    if (_userDefinedAlgorithm != null)
                    {
                        remoteServer = _userDefinedAlgorithm();
                    }
                    break;

                case AlgorithmType.None:
                default:
                    // Get the first remote server.
                    remoteServer        = _remoteServers.First();
                    remoteServer.Count += 1;
                    break;
                }

                // If exists.
                if (remoteServer != null)
                {
                    return(remoteServer);
                }
                else
                {
                    throw new Exception("No remote servers exist.");
                }
            }
            else
            {
                throw new Exception("No remote servers exist.");
            }
        }
Esempio n. 32
0
        static bool MultiThreadedCompile(int maxParallelism, string workingDirectory, List<string> toCompile, bool overwrite, bool warnAsErrors, bool minify, bool verbose, string spriteProg, string spriteArguments, bool autoCacheBreak, bool autoPrefix, out DependencyGraph dependencies)
        {
            var @lock = new Semaphore(0, toCompile.Count);
            var contexts = new ConcurrentBag<Context>();
            var outMsg = new ConcurrentBag<string>();

            toCompile.AsParallel()
                .WithDegreeOfParallelism(maxParallelism)
                .WithExecutionMode(ParallelExecutionMode.ForceParallelism)
                .ForAll(
                    delegate(string compile)
                    {
                        try
                        {
                            var threadContext = new Context(FileCache);
                            contexts.Add(threadContext);

                            var buffer = new StringBuilder();

                            var outputFile = OutputFileFor(compile, overwrite: overwrite);
                            buffer.AppendLine("\t" + compile);
                            buffer.Append("\tto " + outputFile);

                            var timer = new Stopwatch();
                            timer.Start();

                            var result = Compile(workingDirectory, compile, outputFile, threadContext, minify, warnAsErrors, autoCacheBreak, autoPrefix);

                            timer.Stop();

                            if (result)
                            {
                                buffer.AppendLine(" in " + timer.ElapsedMilliseconds + "ms");
                            }
                            else
                            {
                                buffer.AppendLine(" failed after " + timer.ElapsedMilliseconds + "ms");
                            }

                            outMsg.Add(buffer.ToString());
                        }
                        finally
                        {
                            @lock.Release();
                        }
                    }
                );

            for (int i = 0; i < toCompile.Count; i++)
                @lock.WaitOne();

            var mergedContext = contexts.ElementAt(0);
            for (int i = 1; i < contexts.Count; i++)
            {
                mergedContext = mergedContext.Merge(contexts.ElementAt(i));
            }

            dependencies = mergedContext.Dependecies;

            var infoMessages = mergedContext.GetInfoMessages().ToList();
            var errors = mergedContext.GetErrors();

            if (spriteProg.HasValue())
            {
                foreach (var sprite in mergedContext.GetSpriteFiles())
                {
                    var commandErrors = RunSpriteCommand(spriteProg, workingDirectory, sprite, spriteArguments, infoMessages);

                    errors = errors.SelectMany(s => s.ToList()).Union(commandErrors).ToLookup(k => k.Type);
                }
            }

            if (verbose)
            {
                foreach (var msg in outMsg)
                {
                    Console.Write(msg);
                }

                if (outMsg.Count > 0) Console.WriteLine();
            }

            if (errors.Count > 0)
            {
                var parseErrors = errors.Where(e => e.Key == ErrorType.Parser).SelectMany(s => s.ToList()).Distinct().ToList();
                var compileErrors = errors.Where(e => e.Key == ErrorType.Compiler).SelectMany(s => s.ToList()).Distinct().ToList();

                Print("Errors", parseErrors, compileErrors);
            }

            if (mergedContext.GetWarnings().Count > 0)
            {
                var parseWarnings = mergedContext.GetWarnings().Where(e => e.Key == ErrorType.Parser).SelectMany(s => s.ToList()).Distinct().ToList();
                var compileWarnings = mergedContext.GetWarnings().Where(e => e.Key == ErrorType.Compiler).SelectMany(s => s.ToList()).Distinct().ToList();

                Print("Warnings", parseWarnings, compileWarnings);
            }

            if (verbose && infoMessages.Count > 0)
            {
                Console.WriteLine("INFO");
                Console.WriteLine("====");
                foreach (var i in infoMessages)
                {
                    Console.WriteLine(i);
                }
            }

            return mergedContext.GetErrors().Count == 0;
        }