public override List<TableObject> DetectRotation(List<TableObject> ObjectList)
        {
            DateTime start = DateTime.Now;

            //No bitmaps -> no rotation detection
            if (ObjectList.Where(o => o.ExtractedBitmap != null).Count() == 0)
                return ObjectList;

            List<TableObject> ObjectsWithBitmap = ObjectList.Where(o => o.ExtractedBitmap != null).ToList();
            int objects = ObjectsWithBitmap.Count();
            int index = 0;

            int _threadcount = 0;
            ManualResetEvent[] resetEvents;

            //Start 4 threads, only if >= 4 threads
            if (objects >= 4)
            {
                _threadcount = 4;
                resetEvents = new ManualResetEvent[4];

                for (int i=4; i > 0; i--)
                {
                    Thread t1 = new Thread(new ParameterizedThreadStart(Work));
                    t1.Name = "ObjectTable RotationDetection Thread #" + i.ToString();
                    //Copy 1/i*objectcount of the objects to the new thread
                    int amount = (int) Math.Round((1.0/i)*objects);
                    TableObject[] threadobjects = new TableObject[amount];
                    ObjectsWithBitmap.CopyTo(index, threadobjects, 0, amount);
                    objects -= amount;
                    index += amount;

                    resetEvents[i-1] = new ManualResetEvent(false);
                    t1.Start(new object[] {threadobjects,resetEvents[i-1]});
                }

                WaitHandle.WaitAll(resetEvents);
            }
            else
            {
                //Single thread
                _threadcount = 1;

                ManualResetEvent manualReset = new ManualResetEvent(false);

                Thread t = new Thread(new ParameterizedThreadStart(Work));
                t.Name = "ObjectTable RotationDetection Thread -";
                t.Start(new object[] {ObjectsWithBitmap.ToArray(),manualReset});

                manualReset.WaitOne();
            }

            //Performance
            this.RotationDetectionDuration = (int) Math.Round((DateTime.Now - start).TotalMilliseconds);
            return ObjectList;
        }
        public ChuZhuangControl(List<ChuZhuangTable> list,HeroInfoTable singHero)
        {
            InitializeComponent();
            this.tbl_Title.Text = "英雄出装路线";
            if (list != null||list.Count==0)
            {
                List<ChuZhuangTable> list1 = list.Where(c => c.Index == 1).ToList();
                List<ChuZhuangTable> list2 = list.Where(c => c.Index == 2).ToList();
                List<ChuZhuangTable> list3 = list.Where(c => c.Index == 3).ToList();
                foreach (ChuZhuangTable item in list1)
                {
                    Image image = new Image();
                    image.Width = 60;
                    image.Height = 60;
                    image.Margin = new Thickness(5, 5, 5, 5);
                    image.Source = new BitmapImage() { UriSource = new Uri(item.ItemUri, UriKind.Relative) };
                    wp_ChuMen.Children.Add(image);
                }
                tb1_ChuMenContent.Text = singHero.ChuMen;

                foreach (ChuZhuangTable item in list2)
                {
                    Image image = new Image();
                    image.Width = 60;
                    image.Height = 60;
                    image.Margin = new Thickness(5, 5, 5, 5);
                    image.Source = new BitmapImage() { UriSource = new Uri(item.ItemUri, UriKind.Relative) };
                    this.wp_ZhongQi.Children.Add(image);
                }
                tb1_ZhongQiContent.Text= singHero.ZhongQi;;

                foreach (ChuZhuangTable item in list3)
                {
                    Image image = new Image();
                    image.Width = 60;
                    image.Height = 60;
                    image.Margin = new Thickness(5, 5, 5, 5);
                    image.Source = new BitmapImage() { UriSource = new Uri(item.ItemUri, UriKind.Relative) };
                    wp_HouQi.Children.Add(image);
                }
               // tb1_ChuMenContent.Text = singHero.ChuMen;
                tb1_HouQiContent.Text = singHero.HuoQi;
            }
            else
            {
                this.tbl_Title.Text = "没有相关信息,请等待更新.....";

            }
        }
Example #3
0
        public UserSettings(FacebookUserSetting setting)
        {
            _setting = setting;
            //get user
            InitializeComponent();

            var fb = new FacebookClient(setting.AccessToken);

            var picSettings = new List<FacebookPictureSetting>();

            dynamic friends = fb.Get("/me/friends");

            foreach (var friend in friends.data)
            {
                picSettings.Add(new FacebookPictureSetting(new FacebookUser(friend.name, friend.id), false));
            }

            picSettings.Sort((x, y) => string.Compare(x.User.Name, y.User.Name));
            picSettings.Insert(0, new FacebookPictureSetting(new FacebookUser(setting.User.Name, setting.User.Id), false));

            var selectedPics = picSettings.Where(x => setting.PictureSettings.Any(y => y.User.Id == x.User.Id));

            foreach (var sp in selectedPics)
            {
                sp.Selected = true;
            }

            lsUsers.ItemsSource = picSettings;
        }
        private static List<LandCombatUnit> AttackWithLandCombatUnits(List<LandCombatUnit> landCombatUnits)
        {
            landCombatUnits = landCombatUnits.Where(lcu => lcu.CanAttack || lcu.CanMove).ToList();
            foreach (LandCombatUnit landCombatUnit in landCombatUnits)
            {
                Tile currentTile = Game.BoardFactory.Tiles.Where(t => t.GroundUnit == landCombatUnit).FirstOrDefault();
                Game.TileFactory.SetAttackableTiles(landCombatUnit, currentTile);
                if (landCombatUnit.AttackableTiles.Count > 0)
                {
                    Tile targetTile = null;
                    if (landCombatUnit.EquipmentClassEnum == EquipmentClassEnum.AntiAir)
                    {
                        targetTile = DetermineTarget(landCombatUnit.AttackableTiles,TargetTypeEnum.Air);

                    }
                    else
                    {
                        targetTile = DetermineTarget(landCombatUnit.AttackableTiles, TargetTypeEnum.SoftGround);
                    }

                    Game.BoardFactory.ActiveTile = currentTile;
                    Game.BoardFactory.ActiveUnit = landCombatUnit;
                    Game.BoardFactory.CalculateBattleForComputerPlayer(targetTile);

                }
            }
            return landCombatUnits;
        }
        public static List<Currency> GetCurrency()
        {
            List<Currency> wCurrency = new List<Currency>();

            XmlDocument xmlDoc = new XmlDocument();
            string path = System.AppDomain.CurrentDomain.BaseDirectory + "Currencies.xml";
            if(System.IO.File.Exists(path)) {
                xmlDoc.Load(path);
                XmlNodeList nodeList = xmlDoc.DocumentElement.SelectNodes("/ISO_4217/CcyTbl/CcyNtry");
                foreach (XmlNode node in nodeList) {
                    if (node.SelectSingleNode("Ccy") != null) {
                        bool isExist = wCurrency.Where(c => c.code == node.SelectSingleNode("Ccy").InnerText &&
                                                            c.description == node.SelectSingleNode("CcyNm").InnerText).Any();

                        if(!isExist) {
                            wCurrency.Add(new Currency {
                                code = node.SelectSingleNode("Ccy").InnerText,
                                description = node.SelectSingleNode("CcyNm").InnerText,
                                createdAt = DateTime.Now,
                                updateAt = DateTime.Now
                            });
                        }
                    } else {
                        var d = node;
                    }
                }
            } else {
                MessageBox.Show("Currency file could not be found.", "Missing file", MessageBoxButton.OK, MessageBoxImage.Warning);
            }

            wCurrency = wCurrency.OrderBy(x => x.description).ToList();
            return wCurrency;
        }
Example #6
0
        private bool vueMode = false; // false = ortho, true = orbite

        #endregion Fields

        #region Constructors

        internal Editor(EditorController _controller)
        {
            InitializeComponent();
            controller = _controller;

            // Ne pas enlever Forms : c'est pour éviter l'ambiguïté.
            KeyDown += controller.KeyPressed;
            KeyUp += controller.KeyUnPressed;
            GamePanel.MouseDown += new Forms.MouseEventHandler(controller.MouseButtonDown);
            GamePanel.MouseUp += new Forms.MouseEventHandler(controller.MouseButtonUp);
            GamePanel.MouseEnter += new EventHandler(GamePanel_MouseEnter);
            GamePanel.MouseLeave -= new EventHandler(GamePanel_MouseExit);
            GamePanel.MouseWheel += new Forms.MouseEventHandler(controller.RouletteSouris);
            GamePanel.MouseMove += new Forms.MouseEventHandler(controller.MouseMove);
            /// Resize on resize only
            Application.Current.MainWindow.SizeChanged += new SizeChangedEventHandler(ResizeGamePanel);

            settings = (new ConfigPanelData()).LoadSettings();
            profiles = (new ConfigPanelData()).LoadProfiles();

            var defaultProfile = profiles.Where(x => settings != null && x.CompareTo(settings.DefaultProfile) == 0);

            if (defaultProfile.Count() > 0)
            {
                selectedProfile = defaultProfile.First();
                controller.ChangeProfile(selectedProfile);
            }
            else
            {
                selectedProfile = profiles[0];
                controller.ChangeProfile(selectedProfile);
            }
        }
        /// <summary>
        /// 当出现控件类型变化时,刷新整个Tab
        /// </summary>
        /// <param name="prompts"></param>
        private void viewModel_ControlTypeChanged(List<PromptItem> prompts)
        {
            TabItem tab = tabAll.SelectedItem as TabItem;

            if (tab == null)
            {
                return;
            }

            //如果有prompt的ControlType发生了变化,那么就刷新页面
            int index = (int)tab.Tag;
            var numbers = prompts.Where(it => it.TabIndex == index);
            if (prompts.Where(it => it.TabIndex == index).Count() > 0)
            {
                RefreshTabContent(tab);
            }
        }
        public void BindLists(List<CodeITBL.FileFromDB> files, bool SearchByUploadDate = false)
        {
			lvItemsContainer.ItemsSource = null;
			lvItemsContainer3Days.ItemsSource = null;
			lvItemsContainer7Days.ItemsSource = null;

            lvItemsContainer.Items.Clear();
            lvItemsContainer3Days.Items.Clear();
            lvItemsContainer7Days.Items.Clear();

			if (!SearchByUploadDate)
			{
				lvItemsContainer.ItemsSource = files.Where(x => x.OriginalFileDate.Date == DateTime.Now.Date).ToList();
				lvItemsContainer3Days.ItemsSource = files.Where(x => x.OriginalFileDate.Date >= DateTime.Now.Date.AddDays(-2) && x.OriginalFileDate.Date <= DateTime.Now.Date.AddHours(23).AddMinutes(59)).ToList();
				lvItemsContainer7Days.ItemsSource = files.Where(x => x.OriginalFileDate.Date >= DateTime.Now.Date.AddDays(-6) && x.OriginalFileDate.Date <= DateTime.Now.Date.AddHours(23).AddMinutes(59)).ToList();
			}
			else
			{				
				lvItemsContainer.ItemsSource = files.Where(x => x.CreatedOn.Date == DateTime.Now.Date).ToList();
				lvItemsContainer3Days.ItemsSource = files.Where(x => x.CreatedOn.Date >= DateTime.Now.Date.AddDays(-2) && x.CreatedOn.Date <= DateTime.Now.Date.AddHours(23).AddMinutes(59)).ToList();
				lvItemsContainer7Days.ItemsSource = files.Where(x => x.CreatedOn.Date >= DateTime.Now.Date.AddDays(-6) && x.CreatedOn.Date <= DateTime.Now.Date.AddHours(23).AddMinutes(59)).ToList();
			}

            txtTodayNoItems.Visibility = lvItemsContainer.Items.Count == 0 ? Visibility.Visible : Visibility.Hidden;
            txt3DaysNoItems.Visibility = lvItemsContainer3Days.Items.Count == 0 ? Visibility.Visible : Visibility.Hidden;
            txt7DaysNoItems.Visibility = lvItemsContainer7Days.Items.Count == 0 ? Visibility.Visible : Visibility.Hidden;
        }
        public SelectionRoute(List<string> original, string route)
        {
            original.Where(it => !String.IsNullOrEmpty(it)).ToList().ForEach(it => this.original.Add(new RouteEntity(it)));
            if (!String.IsNullOrEmpty(route))
            {
                route.Split(' ').ToList().ForEach(it => this.route.Add(new RouteEntity(it)));
            }

            InitializeComponent();

            OriginalList.ItemsSource = this.original;
            RouteList.ItemsSource = this.route;
        }
Example #10
0
        private void HorarioProximo(List<string> saidasDiretas, TextBlock tb)
        {
            string proxSaida;
            try
            {
                proxSaida = saidasDiretas.Where(x => String.Compare(x, DateTime.Now.ToShortTimeString()) > 0).First();
            }
            catch (Exception)
            {
                proxSaida = saidasDiretas.First();
            }

            tb.Text = proxSaida;
        }
Example #11
0
        private void btn_simulate_Click(object sender, RoutedEventArgs e)
        {
            int nbrSim = Convert.ToInt32(txt_nbrsim.Text);
            double initWealth = Properties.Settings.Default.InitWealth;

            List<double> finalEarnings = new List<double>();
            List<int> counts = new List<int>();

            for (int i = 0; i < nbrSim; i++)
            {
                MartStrategy MStrat = new MartStrategy(5, 250, initWealth);
                double bid = MStrat.Bet();
                Number res;
                double payoff;
                int count = 0;
                while (bid <= MStrat.Wealth)
                {
                    MStrat.PlaceBet(bid);
                    res = _RGame.Play();
                    payoff = _RGame.GetPayoffColor(NumberColor.Red, bid, res);
                    MStrat.Setup(payoff);
                    bid = MStrat.Bet();
                    count++;
                }
                finalEarnings.Add(MStrat.Earnings-initWealth);
                counts.Add(count);
            }

            txt_earnings.Text = finalEarnings.Average().ToString();
            txt_plays.Text = counts.Average().ToString();
            txt_maxEarnings.Text = finalEarnings.Max().ToString();
            txt_maxLosses.Text = finalEarnings.Min().ToString();
            txt_totEarnings.Text = finalEarnings.Where(x => x > 0).Sum().ToString();
            txt_totLosses.Text = finalEarnings.Where(x => x < 0).Sum().ToString();
            txt_balance.Text = finalEarnings.Sum().ToString();
        }
Example #12
0
        public AnalysisResultsPage(List<AlgorithmResult> algorithmResults)
        {
            InitializeComponent();

            foreach (var algRes in algorithmResults.Where(result => result.Results != null))
            {
                algRes.Results = algRes.Results.Select(_preprocessAlgResults).ToList();
            }

            foreach (
                var finalRes in algorithmResults.SelectMany(result => result.FinalResults))
            {
                finalRes.WritableHelperData = _preprocessAlgResults(finalRes.HelperData);
            }

            _presenter = new ResultsPresenter(algorithmResults);
            DataContext = _presenter;
        }
        public PlayerSelectionDialog( string selector, List<Player> playerList )
        {
            InitializeComponent();

            List<Player> modifiedPlayerList = new List<Player>(playerList.Where(player => player.Name != selector));

            // Load the listbox with the players and select the first player on the list.
            if ( modifiedPlayerList.Count > 0 )
            {
                PlayerListBox.ItemsSource = modifiedPlayerList;
                PlayerListBox.SelectedIndex = 0;
            }
            else
            {
                MessageBox.Show("No other players!");
                this.enoughPlayers = false;
            }
        }
        private void btn_MentionUsers_UseScrapedData_Save_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if(!string.IsNullOrEmpty(cmbBox_MentionUser_UseScrapedUrl_LstOfUrls.Text))
                {
                    List<CheckBox> temp = new List<CheckBox>();
                    foreach (CheckBox item in cmbBox_MentionUser_UseScrapedUrl_LstOfUrls.Items)
                    {
                        temp.Add(item);
                    }

                    if (temp.Where(x => x.IsChecked == true).ToList().Count == 0)
                    {
                        GlobusLogHelper.log.Info("Please Select Atleast One Account ");
                        return;
                    }
                    if (temp.Count > 0)
                    {
                        foreach (CheckBox item in temp)
                        {
                            if (item.IsChecked == true)
                            {
                                GlobalDeclration.objMentionUser.listOfUrlToMentionUser.Add(item.Content.ToString());
                            }
                        }

                    }      
                    //GlobalDeclration.objMentionUser.listOfUrlToMentionUser.Add(cmbBox_MentionUser_UseScrapedUrl_LstOfUrls.Text);
                    ModernDialog.ShowMessage("Your Data Has Been Saved Succefully", "Select Url", MessageBoxButton.OK);
                }
                else
                {
                    GlobusLogHelper.log.Info("Please Select Url From Dropdown List");
                    ModernDialog.ShowMessage("Please Select Url From Dropdown List", "Select Url", MessageBoxButton.OK);
                    cmbBox_MentionUser_UseScrapedUrl_LstOfUrls.Focus();
                    return;
                }
            }
            catch(Exception ex)
            {
                GlobusLogHelper.log.Error("Error ==> " + ex.Message);
            }
        }
Example #15
0
        private void buttonPrikazi_Click(object sender, RoutedEventArgs e)
        {
            if (datePickerDatumOd.SelectedDate != null || datePickerDatumDo.SelectedDate != null)
            {
                ObservableCollection<StampaBrojIzdatihPonuda> _lista = dBProksi.DajBrojIzdatihPonudaPoRadnicima((DateTime)datePickerDatumOd.SelectedDate, (DateTime)datePickerDatumDo.SelectedDate);

                List<StampaBrojIzdatihPonuda> _s = new List<StampaBrojIzdatihPonuda>();

                switch (((ComboBoxItem)comboBoxSortirajPo.SelectedItem).Content.ToString())
                {
                    case "Šifra":
                        _s = _lista.OrderBy(o => o.Sifra).ToList();
                        break;
                    case "Nadimak":
                        _s = _lista.OrderBy(o => o.Nadimak).ToList();
                        break;
                    case "Broj ponuda":
                        _s = _lista.OrderByDescending(o => o.BrojPonuda).ToList();
                        break;
                }


                reportViewerIzvestaj.LocalReport.ReportEmbeddedResource = "Servis.Izvestaji.BrojIzdatihPonudaStampa.rdlc";
                reportViewerIzvestaj.ProcessingMode = ProcessingMode.Local;

                ReportDataSource _reportDataSource = new ReportDataSource("DS_StampaBrojIzdatihPonuda", (bool)checkBoxVeceOdNule.IsChecked ? _s.Where(f => f.BrojPonuda > 0) : _s);

                reportViewerIzvestaj.LocalReport.DataSources.Clear();
                reportViewerIzvestaj.LocalReport.DataSources.Add(_reportDataSource);
                reportViewerIzvestaj.SetDisplayMode(DisplayMode.PrintLayout);
                reportViewerIzvestaj.ZoomMode = ZoomMode.PageWidth;
                reportViewerIzvestaj.RefreshReport();
            }
            else
            {
                Dijalog _dialog = new Dijalog("Obavezan podatak", "Odaberi vremenski opseg.");
                //_dialog.WindowStyle = WindowStyle.ToolWindow;
                _dialog.Owner = Window.GetWindow(this);
                _dialog.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                _dialog.ShowDialog();
                return;
            }
        }
Example #16
0
 public override System.Collections.Generic.IEnumerable<object> FindMatchingItems(string searchText, System.Collections.IList items, System.Collections.Generic.IEnumerable<object> escapedItems, string textSearchPath, TextSearchMode textSearchMode)
 {
     var dependencies = new List<Dependency>();
     var toRemove = escapedItems.OfType<Dependency>();
     for (int i = 0; i < items.Count; i++)
     {
         dependencies.Add(new Dependency() { FromTask = items[i] as GanttTask, Type = DependencyType.FinishFinish });
         dependencies.Add(new Dependency() { FromTask = items[i] as GanttTask, Type = DependencyType.FinishStart });
         dependencies.Add(new Dependency() { FromTask = items[i] as GanttTask, Type = DependencyType.StartFinish });
         dependencies.Add(new Dependency() { FromTask = items[i] as GanttTask, Type = DependencyType.StartStart });
     }
     var searchTexts = searchText.Split(new char[] { '-' });
     var titleToUpper = searchTexts.First().Trim().ToUpper();
     var typeToUpper = searchTexts.Length > 1 ? searchTexts[1].Trim().ToUpper() : string.Empty;
     
     var result = dependencies.Where(x => !toRemove.Any(y => y.FromTask == x.FromTask && y.Type == x.Type));
     result = result.Where(x => x.FromTask.Title.ToUpper().StartsWith(titleToUpper.ToUpper()) && x.Type.ToString().ToUpper().StartsWith(typeToUpper));
     return result;
 }
Example #17
0
File: WfUtils.cs Project: JuRogn/OA
        /// <summary>
        /// 通过公司ID筛选角色
        /// </summary>
        /// <param name="RoleList"></param>
        /// <param name="CompanyID"></param>
        /// <returns></returns>
        public static List<StateType> GetRoleListByCompanyID(List<StateType> RoleList, string CompanyID)
        {

            List<StateType> StateList = new List<StateType>();
            if (RoleList != null && RoleList.Count > 0)
            {
                List<StateType> dt = RoleList.Where(c => c.CompanyID == CompanyID || c.CompanyID == null).ToList();
                StateType tmp;
                for (int i = 0; i < dt.Count; i++)
                {
                    tmp = new StateType();
                    tmp.StateCode = dt[i].StateCode;
                    tmp.StateName = dt[i].StateName;
                    tmp.CompanyID = dt[i].CompanyID;
                    StateList.Add(tmp);

                }
            }
            return StateList;
        }
        public void InitDate()
        {
            Condition.Initparameter<Customer>();
            customers = new List<Customer>()
            {
                new Customer(){Name = "张三",Age =20,Sex = "男",Income =2000,Level =1},
                new Customer(){Name = "张四",Age =21,Sex = "男",Income =3000,Level =2},
                new Customer(){Name = "张五",Age =22,Sex = "女",Income =4000,Level =1},
                new Customer(){Name = "张六",Age =23,Sex = "女",Income =5000,Level =1},
                new Customer(){Name = "张七",Age =24,Sex = "男",Income =6000,Level =1},
            };
             conditionList = new List<Condition>
            {
                //new Condition (){Field = "Sex",Operator="like",Value = "男",Relation="AND"},
                //new Condition (){Field = "Age",Operator=">=",Value = "21",Relation="AND"},
                //new Condition (){Field = "Level",Operator="=",Value = "1",Relation="AND"},
                //new Condition (){Field = "Income",Operator=">=",Value = "5000",Relation="AND"},
            };

             customers.Where(e => 1 == 1);
        }
Example #19
0
        private void _clientMenu_TL_MENU_LstCompleted(object sender, TL_MENU_LstCompletedEventArgs e)
        {
            if (e.Result != null && e.Result.Count > 0)
            {
                var MenuRootTEMP = new List<MenuItemData>();
                CurrentSystemInfo.AvailableLinks = new Dictionary<int, string>();

                foreach (var item in e.Result)
                {
                    if (CurrentSystemInfo.Roles.ContainsKey(item.menuID.ToString()))
                    {
                        if (item.menuParentID == 0)
                        {
                            var menuItem = new MenuItemData();
                            menuItem.MenuID = item.menuID;
                            menuItem.MenuName = _isVN ? item.menuName : item.menuNameEL;
                            menuItem.MenuLink = item.menuLink;
                            menuItem.Childs = new List<MenuItemData>();

                            MenuRootTEMP.Add(menuItem);
                        }
                        else
                        {
                            var menuItem = new MenuItemData();
                            menuItem.MenuID = item.menuID;
                            menuItem.MenuName = _isVN ? item.menuName : item.menuNameEL;
                            menuItem.MenuLink = item.menuLink;

                            MenuRootTEMP.Where(p => p.MenuID == item.menuParentID).FirstOrDefault().Childs.Add(menuItem);
                        }
                        // Save all menu name for navigation page tool
                        CurrentSystemInfo.AvailableLinks.Add(item.menuID, _isVN ? item.menuName : item.menuNameEL);
                    }
                }
                MenuRoot = MenuRootTEMP;
                OnPropertyChanged("MenuRoot");
            }
        }
Example #20
0
        public void OnImportsSatisfied()
        {
            // TODO: get via WCF
            ListEquipments = new List<Equipment>();
            ListEquipments.Add(new Equipment()
            {
                WidgetNamespace = "FHVGame.Light.MH.X25.Client.Controls",
                WidgetAddresses = new AddressCollection()
                {
                    Addresses = new List<int>() { 1, 2, 3 , 4 , 5 }
                }
            });
            //ListEquipments.Add(new Equipment() { WidgetClientNamespace = "Bakk2.Widget.PAR.Stairville64.Client", WidgetAddresses = new List<AddressBase>() { new AddrDmx(4), new AddressBase(5), new AddressBase(6) } });

            //DirectoryCatalog dc = new DirectoryCatalog(@"..\..\..\Repo");
            //CompositionContainer cc = new CompositionContainer(dc);

            try
            {
                //cc.ComposeParts(this);

                var firstControl = WidgetControls.FirstOrDefault();

                Equipment[] vv = new Equipment[0];
                foreach (var control in WidgetControls)
                {
                    var eqs = ListEquipments.Where(x => control.GetType().Namespace.Equals(x.WidgetNamespace)).ToArray();

                    for (int i = 0; i < eqs.Length; i++)
                    {
                        IPult tmp = control.CreateInstance(eqs[i].WidgetAddresses);

                        // Set addresses for UI-Element
                        //tmp.SetAddresses(eqs[i].WidgetAddresses);

                        // Add to UI
                        Expander ex = new Expander();
                        ex.Content = tmp;
                        stackPanelWidgets.Children.Add(ex);

                    }

                }
                //stackPanelWidgets.Children.Add((UIElement)WidgetControls.FirstOrDefault());

                try
                {
                    //cc.ComposeParts(((UserControl)WidgetControls.FirstOrDefault()).DataContext);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }

                stackPanelWidgets.Children.Add(new Label() { Content = "Ein Test aus dem Code" });

            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
        private void FetchSubCategories()
        {
            const int pagesToCheckForSubCategories = 200;
            var categoriesContents = new List<CategoriesContent>();

            string urlToFetch = cmbCategories.SelectedValue.ToString();
            prgCategory.Maximum = pagesToCheckForSubCategories;
            prgCategory.Value = 1;
            string retrievedHTML = RetrieveData(urlToFetch);

            categoriesContents.AddRange(FetchSelectedCategoryContent(retrievedHTML));

            for (int i = 2; i < pagesToCheckForSubCategories; i++)//Checks the no of pages where from different individual star celebrity names can be found.
            {
                string url = urlToFetch + "?order=n&page=" + i;
                retrievedHTML = RetrieveData(url);
                prgCategory.Value = i;
                categoriesContents.AddRange(FetchSelectedCategoryContent(retrievedHTML));
            }

            var categoriesContentsToBind = new List<CategoriesContent>();

            foreach (var categoriesContent in categoriesContents)
            {
                var content = categoriesContent;
                if (categoriesContentsToBind.Where(i => i.Name == content.Name).ToList().Count == 0)
                {
                    var webSite = new WebSite();
                    webSite.AddSubCategoriesCategories(categoriesContent.Name, categoriesContent.URL);
                    categoriesContentsToBind.Add(categoriesContent);
                }
            }

            cmbSubCategories.ItemsSource = categoriesContentsToBind.OrderBy(val => val.Name).ToList();
        }
        // Within the connection points with least number of connectors, get the one closest to the midpoint.
        private static ConnectionPoint GetConnectionPointForAutoConnect(List<ConnectionPoint> availableConnectionPoints)
        {
            int minConnectorCount = availableConnectionPoints.Min<ConnectionPoint>((p) =>
                {
                    return p.AttachedConnectors.Count;
                });

            List<ConnectionPoint> connectionPoints = new List<ConnectionPoint>(availableConnectionPoints.Where<ConnectionPoint>((p) =>
                {
                    return p.AttachedConnectors.Count == minConnectorCount;
                }));

            ConnectionPoint midPoint = availableConnectionPoints[availableConnectionPoints.Count / 2];
            if (connectionPoints.Contains(midPoint))
            {
                return midPoint;
            }
            double dist;
            return ConnectionPoint.GetClosestConnectionPoint(connectionPoints, midPoint.Location, out dist);
        }
        private void loadCharacterInventory(Character character, bool offline)
        {
            bool success = false;

            if (!offline)
                statusController.DisplayMessage((string.Format("Loading {0}'s inventory...", character.Name)));

            List<Item> inventory = null;
            try
            {
                inventory = ApplicationState.Model.GetInventory(character.Name);
                success = true;
            }
            catch (WebException)
            {
                inventory = new List<Item>();
                success = false;
            }

            var inv = inventory.Where(i => i.inventoryId != "MainInventory");
            updateStatus(success, offline);

            ApplicationState.Model.GetImages(inventory);
        }
        private void ListarTaxas()
        {
            List<Contrato.Taxa> lstTaxas = new List<Contrato.Taxa>();

            Contrato.EntradaTaxa entTaxa = new Contrato.EntradaTaxa();
            entTaxa.UsuarioLogado = Comum.Util.UsuarioLogado.Login;
            entTaxa.EmpresaLogada = Comum.Parametros.EmpresaProduto;
            entTaxa.Chave = Comum.Util.Chave;
            entTaxa.Taxa = new Contrato.Taxa() { Ativo = true, Produto = true };

            Servico.BrasilDidaticosClient servBrasilDidaticos = new Servico.BrasilDidaticosClient(Comum.Util.RecuperarNomeEndPoint());
            Contrato.RetornoTaxa retTaxa = servBrasilDidaticos.TaxaListar(entTaxa);
            servBrasilDidaticos.Close();

            // Se encontrou taxas
            if (retTaxa.Taxas != null)
                // Adiciona as taxas do Produto
                lstTaxas.AddRange(retTaxa.Taxas);

            if (cmbFornecedor.ValorSelecionado != null)
            {
                // Recupera as taxas do fornecedor
                List<Contrato.Taxa> taxas = (from f in _lstFornecedores
                                            where f.Id == ((Contrato.Fornecedor)cmbFornecedor.ValorSelecionado).Id
                                            select f).First().Taxas;

                // Se encontrou as taxas do fornecedor
                if (taxas != null)
                {
                    // Para cada taxa dentro da listagem de taxa do fornecedor
                    foreach (Contrato.Taxa tx in taxas)
                    {
                        if (tx != null)
                        {
                            Contrato.Taxa objTaxa = lstTaxas.Where(t => t.Nome == tx.Nome).FirstOrDefault();

                            if (objTaxa != null)
                            {
                                if (lstTaxas.RemoveAll(t => t.Nome == tx.Nome && (objTaxa.Valor != t.Valor || t.Valor == 0)) > 0)
                                    lstTaxas.Add(tx);
                            }
                            else
                                lstTaxas.Add(tx);
                        }
                    }
                }
            }

            if (lstTaxas != null)
            {
                List<Objeto.Taxa> objTaxas = null;

                if (_produto != null && _produto.Taxas != null)
                {
                    objTaxas = new List<Objeto.Taxa>();

                    // Para cada taxa existente
                    foreach (Contrato.Taxa taxa in lstTaxas)
                    {
                        // Verifica se a taxa não está vazia
                        if (taxa != null)
                        {
                            // Adiciona a taxa no objeto que popula o grid
                            objTaxas.Add(new Objeto.Taxa { Selecionado = false, Id = taxa.Id, Nome = taxa.Nome, Prioridade = taxa.Prioridade, Ativo = taxa.Ativo });
                            // Recupera a mesma taxa na lista de taxas do produto
                            Contrato.Taxa objTaxa = (from ft in _produto.Taxas where ft.Nome == taxa.Nome select ft).FirstOrDefault();
                            // Se a taxa existe para o produto
                            if (objTaxa != null)
                            {
                                // Atualiza a taxa com os valores do produto
                                objTaxas.Last().Selecionado = true;
                                objTaxas.Last().Valor = objTaxa.Valor;
                                objTaxas.Last().Prioridade = objTaxa.Prioridade;
                            }
                        }
                    }
                }
                else
                    objTaxas = (from t in lstTaxas
                                select new Objeto.Taxa { Selecionado = false, Id = t.Id, Nome = t.Nome, Valor = t.Valor, Prioridade = t.Prioridade, Ativo = t.Ativo }).ToList();

                dgTaxas.ItemsSource = objTaxas;
            }
        }
        private void btnMessage_Scrapefollower_Start_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (IGGlobals.listAccounts.Count > 0)
                {
                    try
                    {
                        GlobalDeclration.objScrapeUser.isStopScrapeUser = false;
                        GlobalDeclration.objScrapeUser.lstofThreadScrapeUser.Clear();

                        Regex checkNo = new Regex("^[0-9]*$");

                        int processorCount = objUtils.GetProcessor();

                        int threads = 25;

                        if (chkBox_Scraper_ScrapeUserFollowing_SingleUsername.IsChecked == true)
                        {
                            GlobalDeclration.objScrapeUser.listOfUsernameForCommentuserScraper.Clear();
                            GlobalDeclration.objScrapeUser.usernmeToScrape = Txt_ScrapeFollowing.Text;
                            GlobalDeclration.objScrapeUser.listOfFollowing.Add(Txt_ScrapeFollowing.Text);

                        }

                        int maxThread = 25 * processorCount;
                        try
                        {
                            GlobalDeclration.objScrapeUser.minDelayScrapeUser = Convert.ToInt32(txt_ScrapeUsers_DelayMin.Text);
                            GlobalDeclration.objScrapeUser.maxDelayScrapeUser = Convert.ToInt32(txt_ScrapeUsers_DelayMax.Text);
                            GlobalDeclration.objScrapeUser.NoOfThreadsScarpeUser = Convert.ToInt32(txt_Tweet_ScrapeUsers_NoOfThreads.Text);

                            //GlobalDeclration.objScrapeUser.noOfPhotoToScrape = Convert.ToInt32(Txt_ScrapeUser_ScrapeUser_NoOfPhotoToScrape.Text);
                            GlobalDeclration.objScrapeUser.noOfUserToScrape = Convert.ToInt32(Txt_ScrapeUser_ScrapeFollowing_NoOfUserToScrape.Text);

                            try
                            {
                                List<CheckBox> tempListOfAccount = new List<CheckBox>();
                                foreach (CheckBox item in cmb_Select_To_Account.Items)
                                {
                                    tempListOfAccount.Add(item);
                                }
                                if (tempListOfAccount.Count > 0)
                                {
                                    tempListOfAccount = tempListOfAccount.Where(x => x.IsChecked == true).ToList();
                                    if (tempListOfAccount.Count == 0)
                                    {
                                        GlobusLogHelper.log.Info("Please Select Account From List");
                                        ModernDialog.ShowMessage("Please Select Account From List", "Select Account", MessageBoxButton.OK);
                                        cmb_Select_To_Account.Focus();
                                        return;
                                    }
                                    else
                                    {
                                        foreach (CheckBox checkedItem in tempListOfAccount)
                                        {
                                            if (checkedItem.IsChecked == true)
                                            {
                                                GlobalDeclration.objScrapeUser.selectedAccountToScrape.Add(checkedItem.Content.ToString());
                                            }
                                        }
                                        GlobusLogHelper.log.Info(GlobalDeclration.objScrapeUser.selectedAccountToScrape.Count + " Account Selected");
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                GlobusLogHelper.log.Error("Error ==> " + ex.Message);
                            }
                        }
                        catch (Exception ex)
                        {
                            GlobusLogHelper.log.Info("Enter in Correct Formate/Fill all Field");
                            ModernDialog.ShowMessage("Enter in Correct Formate/Fill all Field", "Error", MessageBoxButton.OK);
                            return;
                        }
                        if (threads > maxThread)
                        {
                            threads = 25;
                        }
                        GlobalDeclration.objScrapeUser.isScrapeFollowing = true;
                        Thread CommentPosterThread = new Thread(GlobalDeclration.objScrapeUser.StartScrapUser);
                        CommentPosterThread.Start();
                        GlobusLogHelper.log.Info("------ ScrapeFollower Proccess Started ------");
                    }

                    catch (Exception ex)
                    {
                        GlobusLogHelper.log.Error("Error : " + ex.StackTrace);
                    }
                }
                else
                {
                    GlobusLogHelper.log.Info("Please Load Accounts !");
                    GlobusLogHelper.log.Debug("Please Load Accounts !");

                }

            }
            catch (Exception ex)
            {
                GlobusLogHelper.log.Error("Error ==> " + ex.StackTrace);
            }
        }
Example #26
0
        private void OptimizePerTiltWeights()
        {
            if (!Options.Movies.Any(m => m.GetType() == typeof(TiltSeries)))
                return;

            Image Mask = StageDataLoad.LoadMap("F:\\stefanribo\\vlion\\mask_warped2_OST_post.mrc", new int2(1, 1), 0, typeof(float));
            List<Image> SubsetMasks = new List<Image> { Mask, Mask };

            int3 Dims = Mask.Dims;
            float AngleMin = float.MaxValue, AngleMax = float.MinValue;
            float DoseMax = float.MinValue;
            List<WeightOptContainer> Reconstructions = new List<WeightOptContainer>();
            Dictionary<TiltSeries, int> SeriesIndices = new Dictionary<TiltSeries, int>();

            int NTilts = 0;

            {
                TiltSeries Series = (TiltSeries)Options.Movies[0];
                string[] FileNames = Directory.EnumerateFiles(Series.WeightOptimizationDir, "subset*.mrc").Where(p => p.Contains("subset3") || p.Contains("subset4")).Select(v => new FileInfo(v).Name).ToArray();

                string[] MapNames = FileNames.Where(v => !v.Contains(".weight.mrc")).ToArray();
                string[] WeightNames = FileNames.Where(v => v.Contains(".weight.mrc")).ToArray();
                if (MapNames.Length != WeightNames.Length)
                    throw new Exception("Number of reconstructions and weights does not match!");

                string[] MapSuffixes = MapNames;
                int[] MapSubsets = MapSuffixes.Select(v =>
                {
                    string S = v.Substring(v.IndexOf("subset") + "subset".Length);
                    return int.Parse(S.Substring(0, S.IndexOf("_"))) - 3;
                }).ToArray();
                int[] MapTilts = MapSuffixes.Select(v =>
                {
                    string S = v.Substring(v.IndexOf("tilt") + "tilt".Length);
                    return int.Parse(S.Substring(0, S.IndexOf(".mrc")));
                }).ToArray();

                SeriesIndices.Add(Series, SeriesIndices.Count);

                float[] MapAngles = MapTilts.Select(t => Series.AnglesCorrect[t]).ToArray();
                float[] MapDoses = MapTilts.Select(t => Series.Dose[t]).ToArray();

                for (int i = 0; i < MapNames.Length; i++)
                {
                    Image Map = StageDataLoad.LoadMap(Series.WeightOptimizationDir + MapNames[i], new int2(1, 1), 0, typeof(float));
                    Image MapFT = Map.AsFFT(true);
                    float[] MapData = MapFT.GetHostContinuousCopy();
                    Map.Dispose();
                    MapFT.Dispose();

                    Image Weights = StageDataLoad.LoadMap(Series.WeightOptimizationDir + WeightNames[i], new int2(1, 1), 0, typeof(float));
                    float[] WeightsData = Weights.GetHostContinuousCopy();
                    Weights.Dispose();

                    Reconstructions.Add(new WeightOptContainer(SeriesIndices[Series], MapSubsets[i], MapData, WeightsData, MapAngles[i], MapDoses[i]));
                }

                AngleMin = Math.Min(MathHelper.Min(MapAngles), AngleMin);
                AngleMax = Math.Max(MathHelper.Max(MapAngles), AngleMax);
                DoseMax = Math.Max(MathHelper.Max(MapDoses), DoseMax);

                NTilts = Series.NTilts;

                //break;
            }

            float[][] PackedRecFT = new float[SeriesIndices.Count][];
            float[][] PackedRecWeights = new float[SeriesIndices.Count][];
            foreach (var s in SeriesIndices)
            {
                WeightOptContainer[] SeriesRecs = Reconstructions.Where(r => r.SeriesID == s.Value).ToArray();
                PackedRecFT[s.Value] = new float[SeriesRecs.Length * SeriesRecs[0].DataFT.Length];
                PackedRecWeights[s.Value] = new float[SeriesRecs.Length * SeriesRecs[0].DataWeights.Length];

                for (int n = 0; n < SeriesRecs.Length; n++)
                {
                    Array.Copy(SeriesRecs[n].DataFT, 0, PackedRecFT[s.Value], n * SeriesRecs[0].DataFT.Length, SeriesRecs[0].DataFT.Length);
                    Array.Copy(SeriesRecs[n].DataWeights, 0, PackedRecWeights[s.Value], n * SeriesRecs[0].DataWeights.Length, SeriesRecs[0].DataWeights.Length);
                }
            }

            float PixelSize = (float)Options.Movies[0].CTF.PixelSize;
            float FreqMin = 1f / (10f / PixelSize), FreqMin2 = FreqMin * FreqMin;
            float FreqMax = 1f / (8.5f / PixelSize), FreqMax2 = FreqMax * FreqMax;

            int ShellMin = (int)(Dims.X * FreqMin);
            int ShellMax = (int)(Dims.X * FreqMax);
            int NShells = ShellMax - ShellMin;

            float[] R2 = new float[(Dims.X / 2 + 1) * Dims.Y * Dims.Z];
            int[] ShellIndices = new int[R2.Length];

            for (int z = 0; z < Dims.Z; z++)
            {
                int zz = z < Dims.Z / 2 + 1 ? z : z - Dims.Z;
                zz *= zz;
                for (int y = 0; y < Dims.Y; y++)
                {
                    int yy = y < Dims.Y / 2 + 1 ? y : y - Dims.Y;
                    yy *= yy;
                    for (int x = 0; x < Dims.X / 2 + 1; x++)
                    {
                        int xx = x;
                        xx *= x;

                        float r = (float)Math.Sqrt(zz + yy + xx) / Dims.X / PixelSize;
                        R2[(z * Dims.Y + y) * (Dims.X / 2 + 1) + x] = r * r;
                        int ir = (int)Math.Round(Math.Sqrt(zz + yy + xx));
                        ShellIndices[(z * Dims.Y + y) * (Dims.X / 2 + 1) + x] = ir < Dims.X / 2 ? ir : -1;
                    }
                }
            }

            float[] SeriesWeights = new float[SeriesIndices.Count];
            float[] SeriesBfacs = new float[SeriesIndices.Count];
            float[] InitGridAngle = new float[NTilts], InitGridDose = new float[NTilts];
            for (int i = 0; i < InitGridAngle.Length; i++)
            {
                InitGridAngle[i] = (float)Math.Cos((i / (float)(InitGridAngle.Length - 1) * (AngleMax - AngleMin) + AngleMin) * Helper.ToRad) * 100f;
                InitGridDose[i] = -8 * i / (float)(InitGridAngle.Length - 1) * DoseMax / 10f;
            }
            CubicGrid GridAngle = new CubicGrid(new int3(NTilts, 1, 1), InitGridAngle);
            CubicGrid GridDose = new CubicGrid(new int3(NTilts, 1, 1), InitGridDose);

            Func<double[], float[]> WeightedFSC = input =>
            {
                // Set parameters from input vector
                {
                    int Skip = 0;
                    GridAngle = new CubicGrid(GridAngle.Dimensions, input.Skip(Skip).Take((int)GridAngle.Dimensions.Elements()).Select(v => (float)v / 100f).ToArray());
                    Skip += (int)GridAngle.Dimensions.Elements();
                    GridDose = new CubicGrid(GridDose.Dimensions, input.Skip(Skip).Take((int)GridDose.Dimensions.Elements()).Select(v => (float)v * 10f).ToArray());
                }

                // Initialize sum vectors
                float[] FSC = new float[Dims.X / 2];

                float[] MapSum1 = new float[Dims.ElementsFFT() * 2], MapSum2 = new float[Dims.ElementsFFT() * 2];
                float[] WeightSum1 = new float[Dims.ElementsFFT()], WeightSum2 = new float[Dims.ElementsFFT()];

                int ElementsFT = (int)Dims.ElementsFFT();

                foreach (var s in SeriesIndices)
                {
                    WeightOptContainer[] SeriesRecs = Reconstructions.Where(r => r.SeriesID == s.Value).ToArray();

                    float[] PrecalcWeights = new float[SeriesRecs.Length];
                    float[] PrecalcBfacs = new float[SeriesRecs.Length];
                    int[] PrecalcSubsets = new int[SeriesRecs.Length];

                    for (int n = 0; n < SeriesRecs.Length; n++)
                    {
                        WeightOptContainer reconstruction = SeriesRecs[n];
                        // Weight is Weight(Series) * Weight(Angle) * exp((Bfac(Series) + Bfac(Dose)) / 4 * r^2)

                        float AngleWeight = GridAngle.GetInterpolated(new float3((reconstruction.Angle - AngleMin) / (AngleMax - AngleMin), 0.5f, 0.5f));
                        float DoseBfac = GridDose.GetInterpolated(new float3(reconstruction.Dose / DoseMax, 0.5f, 0.5f));

                        PrecalcWeights[n] = AngleWeight;
                        PrecalcBfacs[n] = DoseBfac * 0.25f;
                        PrecalcSubsets[n] = reconstruction.Subset;
                    }

                    CPU.OptimizeWeights(SeriesRecs.Length,
                                        PackedRecFT[s.Value],
                                        PackedRecWeights[s.Value],
                                        R2,
                                        ElementsFT,
                                        PrecalcSubsets,
                                        PrecalcBfacs,
                                        PrecalcWeights,
                                        MapSum1,
                                        MapSum2,
                                        WeightSum1,
                                        WeightSum2);
                }

                for (int i = 0; i < ElementsFT; i++)
                {
                    float Weight = Math.Max(1e-3f, WeightSum1[i]);
                    MapSum1[i * 2] /= Weight;
                    MapSum1[i * 2 + 1] /= Weight;

                    Weight = Math.Max(1e-3f, WeightSum2[i]);
                    MapSum2[i * 2] /= Weight;
                    MapSum2[i * 2 + 1] /= Weight;
                }

                lock (GridAngle)
                {
                    Image Map1FT = new Image(MapSum1, Dims, true, true);
                    Image Map1 = Map1FT.AsIFFT(true);
                    Map1.Multiply(SubsetMasks[0]);
                    Image MaskedFT1 = Map1.AsFFT(true);
                    float[] MaskedFT1Data = MaskedFT1.GetHostContinuousCopy();

                    Map1FT.Dispose();
                    Map1.Dispose();
                    MaskedFT1.Dispose();

                    Image Map2FT = new Image(MapSum2, Dims, true, true);
                    Image Map2 = Map2FT.AsIFFT(true);
                    Map2.Multiply(SubsetMasks[1]);
                    Image MaskedFT2 = Map2.AsFFT(true);
                    float[] MaskedFT2Data = MaskedFT2.GetHostContinuousCopy();

                    Map2FT.Dispose();
                    Map2.Dispose();
                    MaskedFT2.Dispose();

                    float[] Nums = new float[Dims.X / 2];
                    float[] Denoms1 = new float[Dims.X / 2];
                    float[] Denoms2 = new float[Dims.X / 2];
                    for (int i = 0; i < ElementsFT; i++)
                    {
                        int Shell = ShellIndices[i];
                        if (Shell < 0)
                            continue;

                        Nums[Shell] += MaskedFT1Data[i * 2] * MaskedFT2Data[i * 2] + MaskedFT1Data[i * 2 + 1] * MaskedFT2Data[i * 2 + 1];
                        Denoms1[Shell] += MaskedFT1Data[i * 2] * MaskedFT1Data[i * 2] + MaskedFT1Data[i * 2 + 1] * MaskedFT1Data[i * 2 + 1];
                        Denoms2[Shell] += MaskedFT2Data[i * 2] * MaskedFT2Data[i * 2] + MaskedFT2Data[i * 2 + 1] * MaskedFT2Data[i * 2 + 1];
                    }

                    for (int i = 0; i < Dims.X / 2; i++)
                        FSC[i] = Nums[i] / (float)Math.Sqrt(Denoms1[i] * Denoms2[i]);
                }

                return FSC;
            };

            Func<double[], double> EvalForGrad = input =>
            {
                return WeightedFSC(input).Skip(ShellMin).Take(NShells).Sum() * Reconstructions.Count;
            };

            Func<double[], double> Eval = input =>
            {
                double Score = EvalForGrad(input);
                Debug.WriteLine(Score);

                return Score;
            };

            int Iterations = 0;

            Func<double[], double[]> Grad = input =>
            {
                double[] Result = new double[input.Length];
                double Step = 1;

                if (Iterations++ > 15)
                    return Result;

                //Parallel.For(0, input.Length, new ParallelOptions { MaxDegreeOfParallelism = 4 }, i =>
                for (int i = 0; i < input.Length; i++)
                {
                    double[] InputCopy = input.ToList().ToArray();
                    double Original = InputCopy[i];
                    InputCopy[i] = Original + Step;
                    double ResultPlus = EvalForGrad(InputCopy);
                    InputCopy[i] = Original - Step;
                    double ResultMinus = EvalForGrad(InputCopy);
                    InputCopy[i] = Original;

                    Result[i] = (ResultPlus - ResultMinus) / (Step * 2);
                }//);

                return Result;
            };

            List<double> StartParamsList = new List<double>();
            StartParamsList.AddRange(GridAngle.FlatValues.Select(v => (double)v));
            StartParamsList.AddRange(GridDose.FlatValues.Select(v => (double)v));

            double[] StartParams = StartParamsList.ToArray();

            BroydenFletcherGoldfarbShanno Optimizer = new BroydenFletcherGoldfarbShanno(StartParams.Length, Eval, Grad);
            Optimizer.Epsilon = 3e-7;
            Optimizer.Maximize(StartParams);

            EvalForGrad(StartParams);

            float MaxAngleWeight = MathHelper.Max(GridAngle.FlatValues);
            GridAngle = new CubicGrid(GridAngle.Dimensions, GridAngle.FlatValues.Select(v => v / MaxAngleWeight).ToArray());

            float MaxDoseBfac = MathHelper.Max(GridDose.FlatValues);
            GridDose = new CubicGrid(GridDose.Dimensions, GridDose.FlatValues.Select(v => v - MaxDoseBfac).ToArray());

            foreach (var s in Options.Movies)
            {
                TiltSeries Series = (TiltSeries)s;

                List<float> AngleWeights = new List<float>();
                List<float> DoseBfacs = new List<float>();
                for (int i = 0; i < Series.Angles.Length; i++)
                {
                    float AngleWeight = GridAngle.GetInterpolated(new float3(Math.Min(1, (Series.AnglesCorrect[i] - AngleMin) / (AngleMax - AngleMin)), 0.5f, 0.5f));
                    float DoseBfac = GridDose.GetInterpolated(new float3(Math.Min(1, Series.Dose[i] / DoseMax), 0.5f, 0.5f));

                    AngleWeights.Add(AngleWeight);
                    DoseBfacs.Add(DoseBfac);
                }

                Series.GridAngleWeights = new CubicGrid(new int3(1, 1, AngleWeights.Count), AngleWeights.ToArray());
                Series.GridDoseBfacs = new CubicGrid(new int3(1, 1, DoseBfacs.Count), DoseBfacs.ToArray());

                Series.SaveMeta();
            }
        }
Example #27
0
        private void OptimizePerTomoWeights()
        {
            if (!Options.Movies.Any(m => m.GetType() == typeof (TiltSeries)))
                return;

            Image Mask1 = StageDataLoad.LoadMap("F:\\chloroplastribo\\vlion\\mask_post.mrc", new int2(1, 1), 0, typeof (float));
            //Image Mask2 = StageDataLoad.LoadMap("F:\\badaben\\vlion\\mask_C3_post.mrc", new int2(1, 1), 0, typeof(float));
            //Image Mask3 = StageDataLoad.LoadMap("F:\\badaben\\vlion\\mask_C4_post.mrc", new int2(1, 1), 0, typeof(float));
            List<Image> SubsetMasks = new List<Image> { Mask1, Mask1 };

            int3 Dims = Mask1.Dims;
            List<WeightOptContainer> Reconstructions = new List<WeightOptContainer>();
            Dictionary<TiltSeries, int> SeriesIndices = new Dictionary<TiltSeries, int>();

            foreach (Movie movie in Options.Movies)
            {
                if (!movie.DoProcess)
                    continue;

                TiltSeries Series = (TiltSeries)movie;
                string[] FileNames = Directory.EnumerateFiles(Series.WeightOptimizationDir, Series.RootName + "_subset*.mrc").Where(v => v.Contains("subset1") || v.Contains("subset2")).Select(v => new FileInfo(v).Name).ToArray();
                if (FileNames.Length == 0)
                    continue;

                string[] MapNames = FileNames.Where(v => !v.Contains(".weight.mrc")).ToArray();
                string[] WeightNames = FileNames.Where(v => v.Contains(".weight.mrc")).ToArray();
                if (MapNames.Length != WeightNames.Length)
                    throw new Exception("Number of reconstructions and weights does not match!");

                string[] MapSuffixes = MapNames.Select(v => v.Substring(Series.RootName.Length)).ToArray();
                int[] MapSubsets = MapSuffixes.Select(v =>
                {
                    string S = v.Substring(v.IndexOf("subset") + "subset".Length);
                    return int.Parse(S.Substring(0, S.IndexOf(".mrc"))) - 1;
                }).ToArray();

                SeriesIndices.Add(Series, SeriesIndices.Count);

                for (int i = 0; i < MapNames.Length; i++)
                {
                    Image Map = StageDataLoad.LoadMap(Series.WeightOptimizationDir + MapNames[i], new int2(1, 1), 0, typeof (float));
                    Image MapFT = Map.AsFFT(true);
                    float[] MapData = MapFT.GetHostContinuousCopy();
                    Map.Dispose();
                    MapFT.Dispose();

                    Image Weights = StageDataLoad.LoadMap(Series.WeightOptimizationDir + WeightNames[i], new int2(1, 1), 0, typeof (float));
                    float[] WeightsData = Weights.GetHostContinuousCopy();
                    Weights.Dispose();

                    Reconstructions.Add(new WeightOptContainer(SeriesIndices[Series], MapSubsets[i], MapData, WeightsData, 0, 0));
                }

                //break;
            }

            float[][] PackedRecFT = new float[SeriesIndices.Count][];
            float[][] PackedRecWeights = new float[SeriesIndices.Count][];
            foreach (var s in SeriesIndices)
            {
                WeightOptContainer[] SeriesRecs = Reconstructions.Where(r => r.SeriesID == s.Value).ToArray();
                PackedRecFT[s.Value] = new float[SeriesRecs.Length * SeriesRecs[0].DataFT.Length];
                PackedRecWeights[s.Value] = new float[SeriesRecs.Length * SeriesRecs[0].DataWeights.Length];

                for (int n = 0; n < SeriesRecs.Length; n++)
                {
                    Array.Copy(SeriesRecs[n].DataFT, 0, PackedRecFT[s.Value], n * SeriesRecs[0].DataFT.Length, SeriesRecs[0].DataFT.Length);
                    Array.Copy(SeriesRecs[n].DataWeights, 0, PackedRecWeights[s.Value], n * SeriesRecs[0].DataWeights.Length, SeriesRecs[0].DataWeights.Length);
                }
            }

            float PixelSize = (float)Options.Movies[0].CTF.PixelSize;
            float FreqMin = 1f / (18.0f / PixelSize), FreqMin2 = FreqMin * FreqMin;
            float FreqMax = 1f / (14.5f / PixelSize), FreqMax2 = FreqMax * FreqMax;

            int ShellMin = (int)(Dims.X * FreqMin);
            int ShellMax = (int)(Dims.X * FreqMax);
            int NShells = ShellMax - ShellMin;

            float[] R2 = new float[(Dims.X / 2 + 1) * Dims.Y * Dims.Z];
            int[] ShellIndices = new int[R2.Length];

            for (int z = 0; z < Dims.Z; z++)
            {
                int zz = z < Dims.Z / 2 + 1 ? z : z - Dims.Z;
                zz *= zz;
                for (int y = 0; y < Dims.Y; y++)
                {
                    int yy = y < Dims.Y / 2 + 1 ? y : y - Dims.Y;
                    yy *= yy;
                    for (int x = 0; x < Dims.X / 2 + 1; x++)
                    {
                        int xx = x;
                        xx *= x;

                        float r = (float)Math.Sqrt(zz + yy + xx) / Dims.X / PixelSize;
                        R2[(z * Dims.Y + y) * (Dims.X / 2 + 1) + x] = r * r;
                        int ir = (int)Math.Round(Math.Sqrt(zz + yy + xx));
                        ShellIndices[(z * Dims.Y + y) * (Dims.X / 2 + 1) + x] = ir < Dims.X / 2 ? ir : -1;
                    }
                }
            }

            float[] SeriesWeights = new float[SeriesIndices.Count];
            float[] SeriesBfacs = new float[SeriesIndices.Count];

            Func<double[], float[]> WeightedFSC = input =>
            {
                // Set parameters from input vector
                //{
                    int Skip = 0;
                    SeriesWeights = input.Take(SeriesWeights.Length).Select(v => (float)v / 100f).ToArray();
                    Skip += SeriesWeights.Length;
                    SeriesBfacs = input.Skip(Skip).Take(SeriesBfacs.Length).Select(v => (float)v * 10f).ToArray();
                //}

                // Initialize sum vectors
                float[] FSC = new float[Dims.X / 2];

                float[] MapSum1 = new float[Dims.ElementsFFT() * 2], MapSum2 = new float[Dims.ElementsFFT() * 2];
                float[] WeightSum1 = new float[Dims.ElementsFFT()], WeightSum2 = new float[Dims.ElementsFFT()];

                int ElementsFT = (int)Dims.ElementsFFT();

                foreach (var s in SeriesIndices)
                {
                    WeightOptContainer[] SeriesRecs = Reconstructions.Where(r => r.SeriesID == s.Value).ToArray();

                    float[] PrecalcWeights = new float[SeriesRecs.Length];
                    float[] PrecalcBfacs = new float[SeriesRecs.Length];
                    int[] PrecalcSubsets = new int[SeriesRecs.Length];

                    for (int n = 0; n < SeriesRecs.Length; n++)
                    {
                        WeightOptContainer reconstruction = SeriesRecs[n];
                        // Weight is Weight(Series) * exp(Bfac(Series) / 4 * r^2)

                        float SeriesWeight = (float)Math.Exp(SeriesWeights[reconstruction.SeriesID]);
                        float SeriesBfac = SeriesBfacs[reconstruction.SeriesID];

                        PrecalcWeights[n] = SeriesWeight;
                        PrecalcBfacs[n] = SeriesBfac * 0.25f;
                        PrecalcSubsets[n] = reconstruction.Subset;
                    }

                    CPU.OptimizeWeights(SeriesRecs.Length,
                                        PackedRecFT[s.Value],
                                        PackedRecWeights[s.Value],
                                        R2,
                                        ElementsFT,
                                        PrecalcSubsets,
                                        PrecalcBfacs,
                                        PrecalcWeights,
                                        MapSum1,
                                        MapSum2,
                                        WeightSum1,
                                        WeightSum2);
                }

                for (int i = 0; i < ElementsFT; i++)
                {
                    float Weight = Math.Max(1e-3f, WeightSum1[i]);
                    MapSum1[i * 2] /= Weight;
                    MapSum1[i * 2 + 1] /= Weight;

                    Weight = Math.Max(1e-3f, WeightSum2[i]);
                    MapSum2[i * 2] /= Weight;
                    MapSum2[i * 2 + 1] /= Weight;
                }

                Image Map1FT = new Image(MapSum1, Dims, true, true);
                Image Map1 = Map1FT.AsIFFT(true);
                Map1.Multiply(SubsetMasks[0]);
                Image MaskedFT1 = Map1.AsFFT(true);
                float[] MaskedFT1Data = MaskedFT1.GetHostContinuousCopy();

                Map1FT.Dispose();
                Map1.Dispose();
                MaskedFT1.Dispose();

                Image Map2FT = new Image(MapSum2, Dims, true, true);
                Image Map2 = Map2FT.AsIFFT(true);
                Map2.Multiply(SubsetMasks[1]);
                Image MaskedFT2 = Map2.AsFFT(true);
                float[] MaskedFT2Data = MaskedFT2.GetHostContinuousCopy();

                Map2FT.Dispose();
                Map2.Dispose();
                MaskedFT2.Dispose();

                float[] Nums = new float[Dims.X / 2];
                float[] Denoms1 = new float[Dims.X / 2];
                float[] Denoms2 = new float[Dims.X / 2];
                for (int i = 0; i < ElementsFT; i++)
                {
                    int Shell = ShellIndices[i];
                    if (Shell < 0)
                        continue;

                    Nums[Shell] += MaskedFT1Data[i * 2] * MaskedFT2Data[i * 2] + MaskedFT1Data[i * 2 + 1] * MaskedFT2Data[i * 2 + 1];
                    Denoms1[Shell] += MaskedFT1Data[i * 2] * MaskedFT1Data[i * 2] + MaskedFT1Data[i * 2 + 1] * MaskedFT1Data[i * 2 + 1];
                    Denoms2[Shell] += MaskedFT2Data[i * 2] * MaskedFT2Data[i * 2] + MaskedFT2Data[i * 2 + 1] * MaskedFT2Data[i * 2 + 1];
                }

                for (int i = 0; i < Dims.X / 2; i++)
                    FSC[i] = Nums[i] / (float)Math.Sqrt(Denoms1[i] * Denoms2[i]);

                return FSC;
            };

            Func<double[], double> EvalForGrad = input =>
            {
                return WeightedFSC(input).Skip(ShellMin).Take(NShells).Sum() * Reconstructions.Count;
            };

            Func<double[], double> Eval = input =>
            {
                double Score = EvalForGrad(input);
                Debug.WriteLine(Score);

                return Score;
            };

            int Iterations = 0;

            Func<double[], double[]> Grad = input =>
            {
                double[] Result = new double[input.Length];
                double Step = 4;

                if (Iterations++ > 15)
                    return Result;

                //Parallel.For(0, input.Length, new ParallelOptions { MaxDegreeOfParallelism = 4 }, i =>
                for (int i = 0; i < input.Length; i++)
                {
                    double[] InputCopy = input.ToList().ToArray();
                    double Original = InputCopy[i];
                    InputCopy[i] = Original + Step;
                    double ResultPlus = EvalForGrad(InputCopy);
                    InputCopy[i] = Original - Step;
                    double ResultMinus = EvalForGrad(InputCopy);
                    InputCopy[i] = Original;

                    Result[i] = (ResultPlus - ResultMinus) / (Step * 2);
                }//);

                return Result;
            };

            List<double> StartParamsList = new List<double>();
            StartParamsList.AddRange(SeriesWeights.Select(v => (double)v));
            StartParamsList.AddRange(SeriesBfacs.Select(v => (double)v));

            double[] StartParams = StartParamsList.ToArray();

            BroydenFletcherGoldfarbShanno Optimizer = new BroydenFletcherGoldfarbShanno(StartParams.Length, Eval, Grad);
            Optimizer.Epsilon = 3e-7;
            Optimizer.Maximize(StartParams);

            EvalForGrad(StartParams);

            foreach (var s in SeriesIndices)
            {
                s.Key.GlobalWeight = (float)Math.Exp(SeriesWeights[s.Value] - MathHelper.Max(SeriesWeights));   // Minus, because exponential
                s.Key.GlobalBfactor = SeriesBfacs[s.Value] - MathHelper.Max(SeriesBfacs);

                s.Key.SaveMeta();
            }
        }
Example #28
0
        private void CreateColumnTasks(List<StoryTask> storyTasks, Column column)
        {
            foreach (var key in storyYPositions.Keys)
            {

                xPos = SetXStartPos(column);
                yPos = storyYPositions[key];
                var cardCount = 0;
                var stackCount = 0;

                var currentstoryTasks = storyTasks.Where(t => t.StoryNumber == key).ToList();

                var maxCard = 10;

                if (column == Column.Testing)
                {
                    maxCard = 5;
                }

                if (currentstoryTasks.Count >= maxCard)
                {
                    currentstoryTasks = currentstoryTasks.Take(maxCard).ToList();
                    if (column == Column.Testing)
                    {
                        testingFull = true;
                    }
                }


                currentstoryTasks = currentstoryTasks.OrderByDescending(st => st.Number).ToList();

                foreach (var storyTask in currentstoryTasks)
                {

                    var taskControl = new TaskControl();
                    var tcvm = new TaskCardViewModel
                    {
                        Users = sbvm.Users,
                        StoryTask = storyTask
                    };

                    if (testingFull)
                        taskControl.BackgroundColour = Brushes.OrangeRed;
                    else
                        taskControl.BackgroundColour = Brushes.White;

                    taskControl.DataContext = tcvm;
                    taskControl.SetValue(Canvas.LeftProperty, xPos);
                    taskControl.SetValue(Canvas.TopProperty, yPos);

                    taskControl.MouseDown += ControlMouseDown;
                    taskControl.MouseMove += ControlMouseMove;
                    taskControl.MouseUp += ControlMouseUp;

                    cardCount++;
                    if (cardCount < 5)
                    {
                        SetXYForColumn(column);
                    }
                    else
                    {
                        stackCount++;
                        xPos = SetXStartPos(column) + (CARD_WIDTH * stackCount) + 5;
                        yPos = storyYPositions[key];
                        cardCount = 0;
                    }
                    SprintBoard.Children.Add(taskControl);

                }


                testingFull = false;

            }
        }
        public static Model.Event OverlappedWithExistingEvent(Model.Event eventToAdd, List<WpfScheduler.Event> events)
        {
            events = events.Where(e => e.EventInfo.IsCanceled == false && e.EventInfo.PatientSkips == false)
                            .OrderBy(e => e.EventInfo.StartEvent)
                            .ToList();

            foreach (WpfScheduler.Event e in events)
            {
                if (Utils.IsOverlappedTime(eventToAdd.StartEvent, eventToAdd.EndEvent, e.EventInfo.StartEvent, e.EventInfo.EndEvent))
                {
                    return e.EventInfo;
                }
            }

            return null;
        }
 private void btnSave_ScrapeUsers_ScrapeFollowing_Click(object sender, RoutedEventArgs e)
 {
     try
     {
         if (!string.IsNullOrEmpty(Txt_ScrapeFolowing.Text))
         {
             GlobalDeclration.objScrapeUser.usernmeToScrape = Txt_ScrapeFolowing.Text;
         }
         else
         {
             GlobusLogHelper.log.Info("Please Enter Username of User To Scrape Following");
             ModernDialog.ShowMessage("Please Enter Username of User To Scrape Following", "Scrape Following", MessageBoxButton.OK);
             Txt_ScrapeFolowing.Focus();
             return;
         }
         //if (!string.IsNullOrEmpty(cmb_Select_To_Account.Text))
         //{
         //    GlobalDeclration.objScrapeUser.selectedAccountToScrape = cmb_Select_To_Account.Text;
         //}
         //else
         //{
         //    GlobusLogHelper.log.Info("Please Select Account To Scrape Following");
         //    ModernDialog.ShowMessage("Please Select Account To Scrape Following", "Scrape Following", MessageBoxButton.OK);
         //    cmb_Select_To_Account.Focus();
         //    return;
         //}
         try
         {
             List<CheckBox> tempListOfAccount = new List<CheckBox>();
             foreach (CheckBox item in cmb_Select_To_Account.Items)
             {
                 tempListOfAccount.Add(item);
             }
             if (tempListOfAccount.Count > 0)
             {
                 tempListOfAccount = tempListOfAccount.Where(x => x.IsChecked == true).ToList();
                 if (tempListOfAccount.Count == 0)
                 {
                     GlobusLogHelper.log.Info("Please Select Account From List");
                     ModernDialog.ShowMessage("Please Select Account From List", "Select Account", MessageBoxButton.OK);
                     cmb_Select_To_Account.Focus();
                     return;
                 }
                 else
                 {
                     foreach (CheckBox checkedItem in tempListOfAccount)
                     {
                         if (checkedItem.IsChecked == true)
                         {
                             GlobalDeclration.objScrapeUser.selectedAccountToScrape.Add(checkedItem.Content.ToString());
                         }
                     }
                     GlobusLogHelper.log.Info(GlobalDeclration.objScrapeUser.selectedAccountToScrape.Count + " Account Selected");
                 }
             }
         }
         catch (Exception ex)
         {
             GlobusLogHelper.log.Error("Error ==> " + ex.Message);
         }
         if (!string.IsNullOrEmpty(Txt_ScrapeUser_ScrapeFollowing_NoOfUserToScrape.Text))
         {
             GlobalDeclration.objScrapeUser.noOfUserToScrape = int.Parse(Txt_ScrapeUser_ScrapeFollowing_NoOfUserToScrape.Text);
         }
         else
         {
             GlobusLogHelper.log.Info("Please Enter No Of User To Scrape Following");
             ModernDialog.ShowMessage("Please Enter No Of User To Scrape Following", "Scrape Following", MessageBoxButton.OK);
             Txt_ScrapeUser_ScrapeFollowing_NoOfUserToScrape.Focus();
             return;
         }
         ModernDialog.ShowMessage("Your Data Has Been Saved Successfully", "Success Message", MessageBoxButton.OK);
     }
     catch (Exception ex)
     {
         GlobusLogHelper.log.Error("Error ==> " + ex.StackTrace);
     }
 }