Beispiel #1
0
        public void DCT_Back_Fort_Test()
        {
            var bmap = new Bitmap(inputImagePath);

            double[] pixelArray = getPixelArray(bmap);

            IDCT dct = DCT.CreateParallelDCT();

            var output = setPixelMatrix(bmap, dct.Backward(dct.Forward(pixelArray)));

            output.Save(outputImagePath);
        }
Beispiel #2
0
        public static void DoClick(By query)
        {
            DCT.Execute(d =>
            {
                var element = driver.FindElement(query);

                ((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].scrollIntoView(true);", element);
                element             = driver.FindElement(query);
                var internalActions = new Actions(driver);
                internalActions.Click(element).Build().Perform();
            });
        }
        ///-------------------------------------------------------------------------------------------------
        /// <summary>   Регистрация пользователя в системе </summary>
        ///
        /// <remarks>   SV Milovanov, 01.02.2018. </remarks>
        ///-------------------------------------------------------------------------------------------------

        static Entity.Data.Application RegistryApplication(string token, Guid userId)
        {
            Entity.Data.Application result = null;
            DCT.Execute(data =>
            {
                var app    = new Entity.Data.Application();
                app.Token  = token;
                app.UserId = userId;
                data.Db1.Applications.Add(app);
                data.Db1.SaveChanges();
            });
            return(result);
        }
Beispiel #4
0
        public static ExampleModel Add(string title, string description)
        {
            ExampleModel result = null;

            DCT.Execute(c =>
            {
                result             = new ExampleModel();
                result.Title       = title;
                result.Description = description;
                models.Add(result);
            });
            return(result);
        }
 static Entity.Data.User RegistryUser(string login, string hash)
 {
     Entity.Data.User result = null;
     DCT.Execute(data =>
     {
         var user   = new Entity.Data.User();
         user.Login = login;
         user.Hash  = hash;
         data.Db1.Users.Add(user);
         data.Db1.SaveChanges();
     });
     return(result);
 }
        public static void BulletinWorkResult(IEnumerable <BulletinPackage> bulletins)
        {
            DCT.ExecuteAsync(d2 =>
            {
                using (var client = new EngineService())
                {
                    var r = client.Ping();
                    Console.WriteLine($"Ping = {r}");

                    client.SendQueryCollection("AssignBulletinWork", objects: bulletins);
                }
            });
        }
Beispiel #7
0
        static void ObjectAndComponent()
        {
            var soe = new SystemObjectExample();
            var sce = new SystemComponentExample();

            DCT.Execute(c =>
            {
                sce._SetState(FessooFramework.Objects.SystemState.Initialized);
                sce._SetState(FessooFramework.Objects.SystemState.Configured);
                sce._SetState(FessooFramework.Objects.SystemState.Loaded);
                sce._SetState(FessooFramework.Objects.SystemState.Launched);
            });
        }
Beispiel #8
0
        /// <summary>
        /// Вызывать только внутри DownloadPage
        /// </summary>
        /// <param name="url"></param>
        public static void NavigatePage(string url)
        {
            if (string.IsNullOrWhiteSpace(url))
            {
                throw new NullReferenceException("DownloadPage url can't be null!");
            }

            DCT.ExecuteMainThread((d) =>
            {
                WebBrowser.Navigate(url);
                Wait();
            }, isAsync: false);
        }
 void SetImage(HtmlElement form, string value)
 {
     DCT.Execute(data =>
     {
         form.Focus();
         var sendKeyTask = Task.Delay(500).ContinueWith((_) =>
         {
             SendKeys.SendWait(@value);
             SendKeys.SendWait("{Enter}");
         });
         form.InvokeMember("click");
     });
 }
Beispiel #10
0
        public static bool Wait <TResult>(Func <IWebDriver, TResult> condition, int timeout = 20)
        {
            var result = false;

            DCT.Execute(d =>
            {
                var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeout));
                wait.IgnoreExceptionTypes(typeof(StaleElementReferenceException));
                wait.Until(condition);
                result = true;
            });
            return(result);
        }
Beispiel #11
0
 private static void Ping()
 {
     DCT.Execute(c =>
     {
         var ping = c.ServiceClient.Ping();
         Console.WriteLine($"Ping data - {ping}");
         using (var main = new MainClient())
         {
             var ping2 = main.Ping();
             Console.WriteLine($"Ping main - {ping2}");
         }
     });
 }
Beispiel #12
0
        /// <summary>
        /// Вызывать только внутри DownloadPage
        /// </summary>
        /// <param name="url"></param>
        public static void NavigatePage(string url)
        {
            if (string.IsNullOrWhiteSpace(url))
            {
                throw new NullReferenceException("DownloadPage url can't be null!");
            }

            DCT.ExecuteCurrentDispatcher(d =>
            {
                WebBrowser.Navigate(url);
                Wait();
            });
        }
Beispiel #13
0
        public static void ExecuteOne(Action <FirefoxDriver> executeAction, ProxyCardCheckCache proxyCache = null, int Timeout = 10)
        {
            DCT.Execute(c =>
            {
                FirefoxOptions options = new FirefoxOptions();
                if (proxyCache != null)
                {
                    var proxy       = new Proxy();
                    proxy.HttpProxy = $"{proxyCache.Address}:{proxyCache.Port}";
                    proxy.FtpProxy  = $"{proxyCache.Address}:{proxyCache.Port}";
                    proxy.SslProxy  = $"{proxyCache.Address}:{proxyCache.Port}";
                    options.Proxy   = proxy;
                }
                options.AddArguments("--headless");
                options.Profile = new FirefoxProfile();
                options.Profile.SetPreference("dom.disable_beforeunload", true);
                options.Profile.SetPreference("dom.popup_maximum", 0);
                options.Profile.SetPreference("privacy.popups.showBrowserMessage", false);
                options.Profile.SetPreference("pdfjs.disabled", true);

                options.Profile.SetPreference("permissions.default.image", 2);
                options.Profile.SetPreference("dom.ipc.plugins.enabled.libflashplayer.so", "false");
                FirefoxDriverService service = FirefoxDriverService.CreateDefaultService();
                service.SuppressInitialDiagnosticInformation = false;
                service.HideCommandPromptWindow = true;

                using (var currentDriver = new FirefoxDriver(service, options, TimeSpan.FromSeconds(Timeout)))
                {
                    try
                    {
                        var manager = currentDriver.Manage();
                        manager.Timeouts().ImplicitWait = TimeSpan.FromSeconds(Timeout);
                        manager.Timeouts().PageLoad     = TimeSpan.FromSeconds(Timeout);
                        executeAction?.Invoke(currentDriver);
                    }
                    catch (Exception ex)
                    {
                        ConsoleHelper.SendMessage($"FIREFOXDRIVER CRASHED {Environment.NewLine} {ex.ToString()}");
                    }
                    try
                    {
                        currentDriver.Close();
                        currentDriver.Quit();
                    }
                    catch (Exception ex)
                    {
                        ConsoleHelper.SendMessage($"FIREFOXDRIVER CLOSE AND QUIT CRASHED {Environment.NewLine} {ex.ToString()}");
                    }
                }
            });
        }
Beispiel #14
0
        /// <summary>
        /// Writes a block of pixel data using the given quantization table,
        /// returning the post-quantized DC value of the DCT-transformed block.
        /// The block is in natural (not zig-zag) order.
        /// </summary>
        /// <param name="index">The quantization table index.</param>
        /// <param name="prevDC">The previous DC value.</param>
        /// <param name="src">Source block</param>
        /// <param name="tempDest1">Temporal block to be used as FDCT Destination</param>
        /// <param name="tempDest2">Temporal block 2</param>
        /// <param name="quant">Quantization table</param>
        /// <param name="unzigPtr">The 8x8 Unzig block pointer</param>
        /// <returns>
        /// The <see cref="int"/>
        /// </returns>
        private int WriteBlock(
            QuantIndex index,
            int prevDC,
            Block8x8F *src,
            Block8x8F *tempDest1,
            Block8x8F *tempDest2,
            Block8x8F *quant,
            int *unzigPtr)
        {
            DCT.TransformFDCT(ref *src, ref *tempDest1, ref *tempDest2);

            Block8x8F.UnzigDivRound(tempDest1, tempDest2, quant, unzigPtr);
            float *unziggedDestPtr = (float *)tempDest2;

            int dc = (int)unziggedDestPtr[0];

            // Emit the DC delta.
            this.EmitHuffRLE((HuffIndex)((2 * (int)index) + 0), 0, dc - prevDC);

            // Emit the AC components.
            HuffIndex h         = (HuffIndex)((2 * (int)index) + 1);
            int       runLength = 0;

            for (int zig = 1; zig < Block8x8F.ScalarCount; zig++)
            {
                int ac = (int)unziggedDestPtr[zig];

                if (ac == 0)
                {
                    runLength++;
                }
                else
                {
                    while (runLength > 15)
                    {
                        this.EmitHuff(h, 0xf0);
                        runLength -= 16;
                    }

                    this.EmitHuffRLE(h, runLength, ac);
                    runLength = 0;
                }
            }

            if (runLength > 0)
            {
                this.EmitHuff(h, 0x00);
            }

            return(dc);
        }
Beispiel #15
0
        public static async Task Parse(IProgress <ParseProgress> progress)
        {
            var outDir = ((App.Current.MainWindow as MainWindow).DataContext as MainVM).OutPath;
            var groups = DCT.DataCenter.Root.Children.GroupBy(x => x.Name);
            var count  = groups.Count();
            var g      = 0;
            var dc     = DCT.GetDataCenter();

            foreach (var group in groups)
            {
                await Task.Run(async() =>
                {
                    var pi          = new ParseProgress();
                    pi.CurrentGroup = group.Key;

                    string dir2, format;
                    if (group.Count() > 1)
                    {
                        dir2   = outDir + "/" + group.Key + "/";
                        format = "{0}-{1}.json";
                    }
                    else
                    {
                        dir2   = outDir + "/";
                        format = "{0}.json";
                    }

                    g++;
                    pi.OverallProgress = g / (float)count;

                    var i            = 0;
                    var objectsCount = group.Count();
                    foreach (var mainObject in group)
                    {
                        await Task.Run(async() =>
                        {
                            var values = dc.GetValues(mainObject, x => x.Value);
                            var json   = JsonConvert.SerializeObject(values, Formatting.Indented);
                            var fName  = string.Format(format, mainObject.Name, i);
                            var path   = Utils.GetOutput(dir2 + fName);
                            File.WriteAllText(path, json);
                            i++;

                            pi.CurrentFile   = fName;
                            pi.GroupProgress = i / (float)objectsCount;
                            progress.Report(pi);
                        });
                    }
                });
            }
        }
 void GetUrl(BulletinPackage bulletin)
 {
     DCT.Execute(d =>
     {
         if (!string.IsNullOrEmpty(bulletin.Url))
         {
             UiHelper.UpdateActionState("URL успешно считан");
         }
         else
         {
             UiHelper.UpdateActionState("URL is NULL");
         }
     });
 }
Beispiel #17
0
        static FirefoxDriver TryCreateWithoutProxy()
        {
            var result = default(FirefoxDriver);

            DCT.Execute(d =>
            {
                //var options = new FirefoxOptions();
                //options.SetPreference("permissions.default.image", 2);
                //options.SetPreference("dom.ipc.plugins.enabled.libflashplayer.so", false);

                result = new FirefoxDriver();
            });
            return(result);
        }
 void ChooseCategories(GroupSignature signature)
 {
     DCT.Execute(d =>
     {
         foreach (var category in signature.GetCategories())
         {
             if (!string.IsNullOrEmpty(category))
             {
                 WebDriver.JsClick(By.CssSelector($"input[title='{category}']"));
                 Thread.Sleep(1000);
             }
         }
     });
 }
Beispiel #19
0
        public bool Execute()
        {
            var result = false;

            DCT.Execute(data =>
            {
                lock (LockExecute)
                {
                    if (task.Value != null && !task.Value.IsCompleted)
                    {
                        return;
                    }
                    task.Clear();
                    task.Value = System.Threading.Tasks.Task.Factory.StartNew(() =>
                    {
                        if (CheckAction == null)
                        {
                            ExecuteAction.Execute();
                        }
                        else
                        {
                            while (CheckAction())
                            {
                                ExecuteAction.Execute();
                                var timeout = 30000;
                                if (CheckTimeout != null)
                                {
                                    timeout = CheckTimeout();
                                }
                                Thread.Sleep(timeout >= 1000 ? timeout : 30000);
                            }
                        }
                    }).ContinueWith((a) =>
                    {
                        System.Threading.Tasks.Task.Factory.StartNew(() =>
                        {
                            Thread.Sleep(500);
                            if (a.IsCompleted)
                            {
                                AfterExecuteAction.Execute();
                            }
                        });
                    });

                    result = true;
                }
            });

            return(result);
        }
Beispiel #20
0
 void GetBulletinsCallback(IEnumerable <BulletinPackage> objs)
 {
     DCT.Execute(d =>
     {
         if (objs.Count() == 0)
         {
             return;
         }
         Bulletins = objs.Select(q => new BulletinView(q));
         RaisePropertyChanged(() => Bulletins);
         RaisePropertyChanged(() => Bulletin);
         RaisePropertyChanged(() => NotBulletin);
     });
 }
        static void JsClick(FirefoxDriver driver, IWebElement element, Action <IWebElement> after = null)
        {
            DCT.Execute(d =>
            {
                ((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].scrollIntoView(true);", element);

                var internalActions = new Actions(driver);
                internalActions.MoveToElement(element).Click().Build().Perform();
                if (after != null)
                {
                    after(element);
                }
            });
        }
Beispiel #22
0
        public static IEnumerable <GroupPackage> ToGroupCollection(this List <CategoryTree> tree)
        {
            var result = new List <GroupPackage>();

            DCT.Execute(data =>
            {
                foreach (var t in tree)
                {
                    var categories = new List <string>();
                    GetChildCategory(t, categories, result);
                }
            });
            return(result.ToList());
        }
Beispiel #23
0
 public override bool Ping(string p)
 {
     DCT.Execute(c =>
     {
         for (int i = 0; i < 10; i++)
         {
             var model       = new ExampleDataServiceDAL.DataModels.ExampleData();
             model.D         = i.ToString();
             model.StateEnum = ExampleDataServiceDAL.DataModels.ExampleDataState.Edit;
         }
         c.SaveChanges();
     });
     return(_Ping(p));
 }
        private static T SerializeJSON <T>(string data)
        {
            T result = default(T);

            DCT.Execute(c =>
            {
                using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(data)))
                {
                    DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
                    result = (T)serializer.ReadObject(ms);
                }
            });
            return(result);
        }
        public void AddImage(Action <Response_AddImage> callback, string name, byte[] image)
        {
            Response_AddImage response = null;

            DCT.ExecuteAsync(c =>
            {
                var request = new Request_AddImage()
                {
                    Image = image,
                    Name  = name,
                };
                Execute(request, callback);
            });
        }
Beispiel #26
0
        public async static Task Parse(IProgress <ParseProgress> progress)
        {
            var dc     = DCT.GetDataCenter();
            var groups = DCT.DataCenter.Root.Children.GroupBy(x => x.Name);
            var count  = groups.Count();
            var g      = 0;
            var outDir = ((App.Current.MainWindow as MainWindow).DataContext as MainVM).OutPath;

            foreach (var group in groups)
            {
                await Task.Run(async() =>
                {
                    var pi          = new ParseProgress();
                    pi.CurrentGroup = group.Key;
                    string dir2, format;
                    if (group.Count() > 1)
                    {
                        dir2   = outDir + "/" + group.Key + "/";
                        format = "{0}-{1}.xml";
                    }
                    else
                    {
                        dir2   = outDir + "/";
                        format = "{0}.xml";
                    }

                    g++;
                    pi.OverallProgress = g / (float)count;
                    Directory.CreateDirectory(dir2);
                    int i            = 0;
                    var objectsCount = group.Count();
                    foreach (var mainObject in group)
                    {
                        await Task.Run(() =>
                        {
                            var element = ConvertToXElement(mainObject);
                            var fName   = string.Format(format, mainObject.Name, i);
                            var path    = dir2 + fName;
                            element.Save(path);
                            i++;
                            pi.CurrentFile   = fName;
                            pi.GroupProgress = i / (float)objectsCount;
                            progress.Report(pi);
                            //Console.WriteLine($"[{i / (float)group.Count():P2}]\tCurrent: {fName}");
                        });
                    }
                });
            }
        }
Beispiel #27
0
        public void IDCTPerformanceTest()
        {
            var source = new float[]
            {
                560, -196, -150, -80, 0, 0, 0, 0,
                -210, -60, -35, 0, 0, 0, 0, 0,
                -140, -32, -40, 0, 0, 0, 0, 0,
                -70, 0, 0, 0, 0, 0, 0, 0,
                0, 0, 0, 0, 0, 0, 0, 0,
                0, 0, 0, 0, 0, 0, 0, 0,
                0, 0, 0, 0, 0, 0, 0, 0,
                0, 0, 0, 0, 0, 0, 0, 0
            };

            const int iterations = 100000;
            const int runs       = 5;
            var       naivePerf  = new PerformanceMonitor("Naive", runs);
            var       nvidiaPerf = new PerformanceMonitor("NVidia", runs);
            var       dct        = new DCT(20);

            var naive  = new byte[8][];
            var nvidia = new byte[8][];

            for (int i = 0; i < 8; i++)
            {
                naive[i]  = new byte[8];
                nvidia[i] = new byte[8];
            }

            for (int run = 0; run < runs; run++)
            {
                naivePerf.Start();
                for (int i = 0; i < iterations; i++)
                {
                    dct.DoIDCT_Naive(source, naive);
                }
                naivePerf.Stop();

                nvidiaPerf.Start();
                for (int i = 0; i < iterations; i++)
                {
                    dct.DoIDCT_NVidia(source, nvidia);
                }
                nvidiaPerf.Stop();
            }

            Assert.IsTrue(nvidiaPerf.AverageCompletionTimeInMs < naivePerf.AverageCompletionTimeInMs,
                          "The NVidia IDCT took {0:0.00} ms, while the naive IDCT took {1:0.00}", nvidiaPerf.AverageCompletionTimeInMs, naivePerf.AverageCompletionTimeInMs);
        }
        ///-------------------------------------------------------------------------------------------------
        /// <summary>   Loads category trees. </summary>
        ///
        /// <remarks>   SV Milovanov, 30.01.2018. </remarks>
        ///
        /// <param name="parentNode">   The parent node. </param>
        /// <param name="parentValue">  The parent value. </param>
        /// <param name="prevValue">    (Optional) The previous value. </param>
        ///-------------------------------------------------------------------------------------------------

        void LoadCategoryTrees(CategoryTree parentNode, string parentValue, string prevValue = null)
        {
            DCT.Execute(data =>
            {
                var byDataId = false;

                if (string.IsNullOrEmpty(parentValue))
                {
                    var div = WebWorker.WebDocument.GetElementsByTagName("div").Cast <HtmlElement>()
                              .LastOrDefault(q => q.GetAttribute("className") == "form-category js-form-category_param");
                    if (div != null)
                    {
                        parentValue = div.GetAttribute("data-param-id");
                        byDataId    = true;
                    }
                }
                if (string.IsNullOrEmpty(parentValue) || parentValue == prevValue)
                {
                    return;
                }

                if (!checkedIds.Contains(parentValue))
                {
                    checkedIds.Add(parentValue);
                }
                else if (byDataId)
                {
                    return;
                }


                var level = byDataId
                    ? WebWorker.WebDocument.GetElementsByTagName("input").Cast <HtmlElement>()
                            .Where(q => q.GetAttribute("type") == "radio" && q.GetAttribute("name") == $"params[{parentValue}]")
                    : WebWorker.WebDocument.GetElementsByTagName("input").Cast <HtmlElement>()
                            .Where(q => q.GetAttribute("type") == "radio" && q.GetAttribute("data-parent-id") == parentValue);

                foreach (var element in level)
                {
                    //var elementValue = element.GetAttribute("value");
                    var node = new CategoryTree(element.GetAttribute("title"));
                    parentNode.AddChild(node);

                    element.InvokeMember("click");
                    Thread.Sleep(1000);
                    LoadCategoryTrees(node, null, parentValue);
                }
            });
        }
        ///-------------------------------------------------------------------------------------------------
        /// <summary>   Генерирует пустую xls для группы. </summary>
        ///
        /// <remarks>   SV Milovanov, 06.02.2018. </remarks>
        ///-------------------------------------------------------------------------------------------------

        public override void GetXlsGroup(GroupSignature signature)
        {
            DCT.Execute(d =>
            {
                var groupContainer = GroupContainerList.Get(Uid);
                var groupPackage   = groupContainer.GetGroupPackage(signature.GetHash());

                var xls = new FileInfo(Path.Combine(Directory.GetCurrentDirectory(), $"new_bulletins[{groupPackage}].xlsx"));
                if (xls.Exists)
                {
                    xls.Delete();
                }

                using (var package = new ExcelPackage(xls))
                {
                    var worksheet = package.Workbook.Worksheets.Add("Мои объявления");
                    var pairs     = groupPackage.Fields;


                    var count = 0;
                    foreach (var pair in pairs)
                    {
                        var cell = worksheet.Cells[1, count + 2];

                        cell.Style.Font.Size = 14;
                        cell.Value           = pair.Key;
                        cell.AutoFitColumns();

                        var options = pair.Value.Options;
                        if (options != null && options.Length > 0)
                        {
                            var optCells = worksheet.Cells[2, count + 2, 100, count + 2];
                            worksheet.DataValidations.Clear();
                            var validation = worksheet.DataValidations.AddListValidation(optCells.Address);
                            validation.ShowErrorMessage = true;
                            validation.ErrorStyle       = ExcelDataValidationWarningStyle.warning;
                            validation.ErrorTitle       = "An invalid value was entered";
                            validation.Error            = "Select a value from the list";
                            for (var i = 0; i < options.Length; i++)
                            {
                                validation.Formula.Values.Add(options[i].Text);
                            }
                        }
                        count++;
                    }
                    package.Save();
                }
            });
        }
Beispiel #30
0
 static void Main(string[] args)
 {
     DCT.Execute(c =>
     {
         //Ping();
         Registaration(email, phone, password, firstname, secondname, middlename);
         while (true)
         {
             Thread.Sleep(3000);
             GetDataCollection();
         }
     });
     Thread.Sleep(10000);
     Console.ReadLine();
 }
        /// <summary>
        /// Encodes a JPEG, preserving the colorspace and metadata of the input JPEG.
        /// </summary>
        /// <param name="decodedJpeg">Decoded Jpeg to start with.</param>
        /// <param name="quality">Quality of the image from 0 to 100.  (Compression from max to min.)</param>
        /// <param name="outStream">Stream where the result will be placed.</param>
        public JpegEncoder(DecodedJpeg decodedJpeg, int quality, Stream outStream)
        {
            _input = decodedJpeg;
            
            /* This encoder requires YCbCr */
            _input.Image.ChangeColorSpace(ColorSpace.YCbCr);

            _quality = quality;

            _height = _input.Image.Height;
            _width = _input.Image.Width;
            _outStream = outStream;
            _dct = new DCT(_quality);
            _huf = new HuffmanTable(null); 
        }