private void InitializePlugins()
        {
            var assemblies = GetAssemblies("Plugins");

            List<MenuItem> menuItems = new List<MenuItem>();

            foreach (var assembly in assemblies)
            {
                var types = assembly.GetTypes();

                foreach (var type in types)
                {
                    if (type.IsClass && type.IsPublic && type.GetInterface(typeof(IPlugin).FullName) != null)
                    {
                        var item = Activator.CreateInstance(type) as IPlugin;
                        var menuItem = item.GetMenuItem();
                        menuItem.Tag = item;
                        menuItem.Click += pluginMenuItem_Click;
                        menuItems.Add(menuItem);
                    }
                }
            }

            if (menuItems.Any())
            {
                var tools = new MenuItem();
                tools.Header = "Tools";
                menuItems.ForEach((i) => { tools.Items.Add(i); });

                v_Menu.Items.Add(tools);
            }
        }
        private void GetWpAlbums(object state)
        {
           List<ServiceAgnosticAlbum> albums = new List<ServiceAgnosticAlbum>();

           IITPlaylist libraryPlaylist = GetLibraryPlaylist();
           if (libraryPlaylist != null)
           {
               IITTrackCollection tracks = libraryPlaylist.Tracks;
               int i = 1;
               foreach (IITFileOrCDTrack track in tracks)
               {
                   var artistName = track.Artist;
                   var albumName = track.Album;
                   if (!string.IsNullOrEmpty(artistName) &&
                       !string.IsNullOrEmpty(albumName) &&
                       !albums.Any(a => a.AlbumName == albumName && a.ArtistName == artistName))
                   {
                       albums.Add(new ServiceAgnosticAlbum(albumName, artistName));
                   }

                   i++;
               }
           }

            App.AlbumsToImport = albums;
            Dispatcher.BeginInvoke(DispatcherPriority.Normal, new ThreadStart(() => this.Navigate(new CollectionImporter())));
        }
        private void GetWpAlbums(object state)
        {
            var wmp = new WindowsMediaPlayer();
            var collection = wmp.mediaCollection;
            this.authorIndex = collection.getMediaAtom("Author");
            this.albumArtistIndex = collection.getMediaAtom("WM/AlbumArtist");
            this.albumIndex = collection.getMediaAtom("Album");

            IWMPPlaylist allMedia = collection.getAll();
            List<ServiceAgnosticAlbum> albums = new List<ServiceAgnosticAlbum>();
            for (int i = 0; i < allMedia.count; i++)
            {
                var currentMedia = allMedia.get_Item(i);
                var artistName = GetArtist(currentMedia);
                var albumName = GetAlbum(currentMedia);

                if (!string.IsNullOrEmpty(artistName) &&
                    !string.IsNullOrEmpty(albumName) &&
                    !albums.Any(a => a.AlbumName == albumName && a.ArtistName == artistName))
                {
                    albums.Add(new ServiceAgnosticAlbum(albumName, artistName));
                }
            }
            App.AlbumsToImport = albums;

            Dispatcher.BeginInvoke(DispatcherPriority.Normal, new ThreadStart(() => this.Navigate(new CollectionImporter())));
        }
Beispiel #4
0
        public LaunchWindow()
        {
            string gameConfigurationFolder = "GameConfiguration";
            string gameConfigurationsPath = Path.Combine(gameConfigurationFolder, "gameConfigs.json");

            InitializeComponent();

            if (!Directory.Exists(gameConfigurationFolder))
                Directory.CreateDirectory(gameConfigurationFolder);

            //Loading the last used configurations for hammer
            RegistryKey rk = Registry.CurrentUser.OpenSubKey(@"Software\Valve\Hammer\General");

            var configs = new List<GameConfiguration>();

            //try loading json
            if (File.Exists(gameConfigurationsPath))
            {
                string jsonLoadText = File.ReadAllText(gameConfigurationsPath);
                configs.AddRange(JsonConvert.DeserializeObject<List<GameConfiguration>>(jsonLoadText));
            }

            //try loading from registry
            if (rk != null)
            {
                string BinFolder = (string)rk.GetValue("Directory");

                string gameData = Path.Combine(BinFolder, "GameConfig.txt");

                configs.AddRange(GameConfigurationParser.Parse(gameData));
            }

            //finalise config loading
            if (configs.Any())
            {
                //remove duplicates
                configs = configs.GroupBy(g => g.Name).Select(grp => grp.First()).ToList();

                //save
                string jsonSaveText = JsonConvert.SerializeObject(configs, Formatting.Indented);
                File.WriteAllText(gameConfigurationsPath, jsonSaveText);

                if (configs.Count == 1)
                    Launch(configs.First());

                GameGrid.ItemsSource = configs;
            }
            else//oh noes
            {
                LaunchButton.IsEnabled = false;
                WarningLabel.Content = "No Hammer configurations found. Cannot launch.";
            }
        }
 public EditTestsWindow(List<TestCase> testCases)
 {
     TestCases = testCases;
     InitializeComponent();
     lstTestCases.Items.Clear();
     foreach (var t in testCases)
     {
         lstTestCases.Items.Add(t);
     }
     if (testCases.Any())
     {
         lstTestCases.SelectedIndex = 0;
     }
     UpdateUI();
 }
        public void RemoveEntry(PhoneApplicationPage page, List<string> uris)
        {
            var lastPage = page.NavigationService.BackStack.FirstOrDefault();

            if (lastPage != null)
            {

                for (int i = page.NavigationService.BackStack.Count() - 1; i >= 0; i--)
                {
                    bool remove = uris.Any(x => { return page.NavigationService.BackStack.ElementAt(i).Source.ToString().Contains(x); });

                    if (remove)
                        page.NavigationService.RemoveBackEntry();
                }

            }
        }
		public IEnumerable<Edge> GroupToEdges(List<Point> points)
		{
			List<Edge> edges = new List<Edge>();

			while (points.Any())
			{
				creatingTime.Start();
				var point = points.First();
				points.Remove(point);

				var edge = new Edge(point);
				creatingTime.Stop();

				edges.Add(GrowEdge(edge, points));
			}

			return edges;
		}
        private void TwitterSampleStream()
        {
            ListWordsByFrequency frequencyList = new ListWordsByFrequency();
            var logFile = System.IO.File.ReadAllLines(@"C:\Users\Daniel\Source\Repos\TwitterCrawl\positive-words.txt");
            List <string> StringList = new List<string>(logFile);
            Globals.Stream = Stream.CreateSampleStream();
            int incomming = 0;
            int success = 0;

            Globals.Stream.TweetReceived += (sender, args) =>
            {
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    incomming++;
                    label.Content = incomming;
                    label1.Content = success;

                    string tweet = args.Tweet.ToString();
                    bool test = StringList.Any(tweet.Contains);

                    if (test)
                    {
                        success++;
                        txtBxTwitterFeed.Clear();
                        txtBxTwitterFeed.Text = tweet;

                        var matchingvalues = StringList.FindAll(tweet.Contains);

                        StringBuilder builder = new StringBuilder();
                        foreach (string v in matchingvalues) // Loop through all strings
                        {
                            builder.Append(v).Append(" "); // Append string to StringBuilder
                        }

                        frequencyList.split(builder.ToString());
                        rTxtBxFrequency.Document.Blocks.Clear();
                        rTxtBxFrequency.Document.Blocks.Add(new Paragraph(new Run(frequencyList.output)));
                    }

                }));
            };
        }
        /// <summary>
        /// Populates the layout radio buttons from disk.
        /// </summary>
        private void PopulateLayoutRadioButtonsFromDisk()
        {
            List<RadioButton> radioButtonList = new List<RadioButton>();
            var rockConfig = RockConfig.Load();
            List<string> filenameList = Directory.GetFiles( ".", "*.dplx" ).ToList();
            foreach ( var fileName in filenameList )
            {
                DplxFile dplxFile = new DplxFile( fileName );
                DocumentLayout documentLayout = new DocumentLayout( dplxFile );
                RadioButton radLayout = new RadioButton();
                if ( !string.IsNullOrWhiteSpace( documentLayout.Title ) )
                {
                    radLayout.Content = documentLayout.Title.Trim();
                }
                else
                {
                    radLayout.Content = fileName;
                }

                radLayout.Tag = fileName;
                radLayout.IsChecked = rockConfig.LayoutFile == fileName;
                radioButtonList.Add( radLayout );
            }

            if ( !radioButtonList.Any( a => a.IsChecked ?? false ) )
            {
                if ( radioButtonList.FirstOrDefault() != null )
                {
                    radioButtonList.First().IsChecked = true;
                }
            }

            lstLayouts.Items.Clear();
            foreach ( var item in radioButtonList.OrderBy( a => a.Content ) )
            {
                lstLayouts.Items.Add( item );
            }
        }
 public FlowDocument ShowContainers(List<Container> containers, List<Vehicle> vehicles)
 {
     var doc = new FlowDocument();
     foreach (var vehicle in vehicles)
     {
         var tempList = UnpackVehicle(vehicle);
         AddMainHeader(doc,
             "Список контейнеров для автомобиля " + vehicle.Name + "(" + tempList.Count() +
             " контейнеров; общий вес груза " + vehicle.Mass + " кг.)");
         AddTable(doc, tempList);
     }
     if (containers.Any())
     {
         AddMainHeader(doc,
             "Список контейнеров не поместившихся в машины " + "(" + containers.Count() + " контейнеров)");
         AddTable(doc, containers);
     }
     else
     {
         AddMainHeader(doc, "Все контейнеры загружены.");
     }
     return doc;
 }
Beispiel #11
0
        private void FillGridWithInfo()//Fetching info for each cell of Info grid and placing it there
        {
            int rows = WeekGrid.Rows;//we will need row and column number to properly placing info into the grid;
            int columns = WeekGrid.Columns;
            List<Group> searchresult = new List<Group>();

            foreach (ListView listView in WeekGrid.Children)
            {

                int index = WeekGrid.Children.IndexOf(listView);
                int row = index / columns;
                int column = index % columns;

                searchresult = groups.FindAll(delegate(Group group)//Looking up if there are ny group for at this date;
                {
                    DateTime weekday = GetStartOfCurrentWeek().AddDays(column);
                    return group.Date == weekday;
                });

                if (!searchresult.Any())//If there are none - setting empty labels.
                {
                    for (int i = 0; i < listView.Items.Count; i++)
                    {
                        ((Label)listView.Items[i]).Content = " ";
                        ((Label)listView.Items[i]).Tag = null;
                        ((Label)listView.Items[i]).Background = Brushes.White;
                    }
                }
                else if (searchresult.Any())//If there are any - we narrow search further to timeperiod.
                {
                    searchresult = searchresult.FindAll(delegate(Group gp)
                    {
                        timeperiod time = (timeperiod)row;
                        return gp.Time == time;
                    });

                    if (!searchresult.Any())//If there are none, we again set all to empty;
                    {
                        for (int i = 0; i < listView.Items.Count; i++)
                        {
                            ((Label)listView.Items[i]).Content = " ";
                            ((Label)listView.Items[i]).Tag = null;
                            ((Label)listView.Items[i]).Background = Brushes.White;
                        }
                    }
                    else if (searchresult.Any())//And if there are any we set them to appropriate posistions in list;
                    {
                        for (int i = 0; i < listView.Items.Count; i++)//we go through all labels on Listview
                        {
                            Group target = searchresult.Find(delegate(Group gp)//And see if there is group for this label
                            {//to be displayed
                                return gp.Room.Id == i + 1;//We check it by room id, because each label corresponds to unique room;
                            });
                            if (target != null)//If we get some result 
                            {
                                ((Label)listView.Items[target.Room.Id - 1]).Tag = target;//We place this group there
                                ((Label)listView.Items[target.Room.Id - 1]).Content = target.Room.Type + ": " +target.Name;
                                ((Label)listView.Items[i]).Background = Brushes.LightSeaGreen;//And display with text and color;
                            }
                            else
                            {
                                ((Label)listView.Items[i]).Content = " ";//Again if there is nothing - setting all to empty;
                                ((Label)listView.Items[i]).Tag = null;
                                ((Label)listView.Items[i]).Background = Brushes.White;
                            }

                        }


                    }
                }
            }
        }
Beispiel #12
0
 List<UserModel> getUsersByCategoryFromDatabase()
 {
     List<UserModel> list_user=new List<UserModel>();
     for (int i = 0; i < categoryCount; i++)
     {
         if (category[i])
         {
             List<ItemTable> list = db.Items.Where(c => c.CategoryId == i + 1).ToList<ItemTable>();
             foreach (ItemTable item in list)
             {
                 UserTable user = db.Users.First(c => c.Id == item.UserId);
                 UserModel userModel = new UserModel()
                 {
                     AvatarUri = user.AvatarUri,
                     UserName = user.UserName,
                     Latitude=(double)user.Latitude,
                     Longitude = (double)user.Longitude,
                     Category = i,
                     Id=user.Id,
                     Address=user.Address
                 };
                // Geocode(userModel.Address,user.Id);
                 if (!list_user.Any(c => c.Id == user.Id))
                     list_user.Add(userModel);
             }
         }
     }
     return list_user;
 }
Beispiel #13
0
        public void Update(List<SimulationObject> SimObjList)
        {
            System.Diagnostics.Debug.WriteLine("MapManager: Update");
            if (!SimObjList.Any())
                return;

            //Stop the engine for synchronisation reasons
            _waveEngineRef.Stop();

            //Debug.WriteLine("MapManager: Update");
            //divide the objects in three categorys: changed wave sources, changed elong-object, changed mass, changed wall
            List<SimulationObject> sources =
                SimObjList.Where(o => o.GetType() == typeof (SimWaveSourceObject)).ToList();
            List<SimulationObject> elongation =
                SimObjList.Where(
                    o =>
                    o.ObjectType == SimulationObject.EObjectType.ConstElongation ||
                    o.ObjectType == SimulationObject.EObjectType.RelElongation).Where(o => o.GetType() != typeof(SimWaveSourceObject)).ToList();
            List<SimulationObject> mass =
                SimObjList.Where(o => o.ObjectType == SimulationObject.EObjectType.Mass).ToList();
            List<SimulationObject> wall =
                SimObjList.Where(o => o.ObjectType == SimulationObject.EObjectType.Wall).ToList();

            //Clear all maps where objects did change, and recreate data
            if (elongation.Where(o => o.PositionOrRotationChange == true).Any())
            {
                _additionalSettings.ElongationMap = new double[_simulationSize.Width,_simulationSize.Height];
                GenerateSimObjData(elongation.Where(o => o.PositionOrRotationChange == true).ToList());
            }

            if (mass.Where(o => o.PositionOrRotationChange == true).Any())
            {
                _additionalSettings.MassMap = new double[_simulationSize.Width,_simulationSize.Height];
                GenerateSimObjData(mass.Where(o => o.PositionOrRotationChange == true).ToList());
            }

            if (wall.Where(o => o.PositionOrRotationChange == true).Any())
            {
                _additionalSettings.WallMap = new bool[_simulationSize.Width,_simulationSize.Height];
                GenerateSimObjData(wall.Where(o => o.PositionOrRotationChange == true).ToList());
            }

            //Merge _additionalSettings with _loadedSettings
            //(SimObjects with mouse/stored values)
            WaveSettings exportSettings = GetMergedMaps();
            //Apply changes
            _waveEngineRef.Settings = exportSettings;

            if (sources.Where(o => o.PositionOrRotationChange == true).Any())
            {
                _additionalSettings.WaveSources.Clear();
                _waveEngineRef.ResetSources();
                GenerateSimObjData(sources);
                //Add Wave Sources
                //loadedSettings.sources refers directly to _waveEngine.Sources
                foreach (WaveSource src in _loadedSettings.WaveSources)
                {
                    _waveEngineRef.AddWaveSoucre(src);
                }
                foreach (WaveSource src in _additionalSettings.WaveSources)
                {
                    _waveEngineRef.AddWaveSoucre(src);
                }
            }

            //all changes done - restart the engine
            _waveEngineRef.Start();
        }
Beispiel #14
0
        private void falar_botao_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                reconhecedor = new Reconhecer();

                parar_botao.IsEnabled = true;

                falar_botao.IsEnabled = false;
                SpeechRecognitionEngine engine = reconhecedor.engine;

                engine.RecognizeCompleted += engine_RecognizeCompleted;

                engine.SpeechRecognized += engine_SpeechRecognized;

                try
                {
                    string linha ;
                    StreamReader falas = new StreamReader(Environment.CurrentDirectory + @"\Falas.txt");
                    List<string> ressu = new List<string>();
                    while((linha=falas.ReadLine())!=null){
                       //if(Regex.IsMatch(linha, @"^[a-zA-Z\s]+$")){
            ressu.Add(linha);
                       //}

                    }
                    /*if (!ressu.Any())
                    {
                        MessageBox.Show("Por favor, só é permitido no arquivo de falas letras, números e espaços", "Erro!", MessageBoxButton.OK, MessageBoxImage.Error);
                    }*/
                    falas.Close();
                    if (ressu.Any())
                    {
                        reconhecedor.escolhas = ressu.ToArray();
                        reconhecedor.gramatica = new GrammarBuilder();

                        reconhecedor.Recognize(RecognizeMode.Multiple);

                    }
                    else
                    {
                        MessageBox.Show("Não há nada neste arquivo.", "Erro!", MessageBoxButton.OK, MessageBoxImage.Error);

                    }

                    //Regex.IsMatch(input, @"^[a-zA-Z]+$");
                }
                catch (InvalidOperationException ee)
                {

                    MessageBox.Show("Um erro ocorreu: \n\n" + ee.Message, "Erro!", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                catch (FileNotFoundException ee)
                {
                    MessageBox.Show("Um erro ocorreu: \n\n" + ee.Message, "Erro!", MessageBoxButton.OK, MessageBoxImage.Error);
                }

                //reconhecedor.escolhas = new string[] {"fale sobre o sistema operacional","cite os planetas do sistema solar","feche o visual studio","gin defina a equivalência massa-energia","ajuda aqui", "desligar a máquina","gin feche o programa","fala teste","ajuda aqui","gin informe o clima" ,"positivo","sim","não","negativo","falas presentes"};

            }
            catch (InvalidOperationException ee)
            {
                switch (ee.Message)
                {

                    case "Cannot find the requested data item, such as a data key or value.":
                        MessageBox.Show("Um erro ocorreu, talvez você não tenha um dispositivo de gravação conectado. \n\n"+ee.Message,"Erro!",MessageBoxButton.OK,MessageBoxImage.Error);
                        parar_botao.IsEnabled = false;
                falar_botao.IsEnabled = true;
                        break;
                    default:
                        MessageBox.Show("Um erro ocorreu: \n\n" + ee.Message, "Erro!", MessageBoxButton.OK, MessageBoxImage.Error);
                        break;

                }

            }
            catch (Exception eee)
            {
                MessageBox.Show("Um erro ocorreu: \n\n" + eee.Message, "Erro...", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
		private bool CheckClipboardForNetDeckImport()
		{
			try
			{
				if(Clipboard.ContainsText())
				{
					var clipboardContent = Clipboard.GetText();
					if(clipboardContent.StartsWith("netdeckimport") || clipboardContent.StartsWith("trackerimport"))
					{
						var clipboardLines = clipboardContent.Split('\n').ToList();
						var deckName = clipboardLines.FirstOrDefault(line => line.StartsWith("name:"));
						if(!string.IsNullOrEmpty(deckName))
						{
							clipboardLines.Remove(deckName);
							deckName = deckName.Replace("name:", "").Trim();
						}
						var url = clipboardLines.FirstOrDefault(line => line.StartsWith("url:"));
						if(!string.IsNullOrEmpty(url))
						{
							clipboardLines.Remove(url);
							url = url.Replace("url:", "").Trim();
						}
						bool? isArenaDeck = null;
						var arena = clipboardLines.FirstOrDefault(line => line.StartsWith("arena:"));
						if(!string.IsNullOrEmpty(arena))
						{
							clipboardLines.Remove(arena);
							bool isArena;
							if(bool.TryParse(arena.Replace("arena:", "").Trim(), out isArena))
								isArenaDeck = isArena;
						}
						var localized = false;
						var nonEnglish = clipboardLines.FirstOrDefault(line => line.StartsWith("nonenglish:"));
						if(!string.IsNullOrEmpty(nonEnglish))
						{
							clipboardLines.Remove(nonEnglish);
							bool.TryParse(nonEnglish.Replace("nonenglish:", "").Trim(), out localized);
						}
						var tagsRaw = clipboardLines.FirstOrDefault(line => line.StartsWith("tags:"));
						var tags = new List<string>();
						if(!string.IsNullOrEmpty(tagsRaw))
						{
							clipboardLines.Remove(tagsRaw);
							tags = tagsRaw.Replace("tags:", "").Trim().Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries).ToList();
						}
						clipboardLines.RemoveAt(0); //"netdeckimport" / "trackerimport"

						var deck = ParseCardString(clipboardLines.Aggregate((c, n) => c + "\n" + n), localized);
						if(deck != null)
						{
							if(tags.Any())
							{
								var reloadTags = false;
								foreach(var tag in tags)
								{
									if(!DeckList.Instance.AllTags.Contains(tag))
									{
										DeckList.Instance.AllTags.Add(tag);
										reloadTags = true;
									}
									deck.Tags.Add(tag);
								}
								if(reloadTags)
								{
									DeckList.Save();
									Helper.MainWindow.ReloadTags();
								}
							}

							if(isArenaDeck.HasValue)
								deck.IsArenaDeck = isArenaDeck.Value;
							deck.Url = url;
							deck.Name = deckName;
							SetNewDeck(deck);
							if(Config.Instance.AutoSaveOnImport)
								SaveDeckWithOverwriteCheck();
							ActivateWindow();
						}
						Clipboard.Clear();
						return true;
					}
				}
			}
			catch(Exception e)
			{
				Logger.WriteLine(e.ToString(), "NetDeckClipbardCheck");
				return false;
			}
			return false;
		}
Beispiel #16
0
        private void v_Button_Search_Click(object sender, RoutedEventArgs e)
        {
            if (!_rawDocuments.Any() || !_rawKeywords.Any() || !_documents.Any())
            {
                return;
            }

            string originalQuery = v_TextBox_SearchInput.Text;

            #region TF/IDF/SIMILARITY
            string processedQuery = string.Concat(Regex.Replace(originalQuery.ToLower(), @"[^\w\s]", "").Split(null).Select(s => _ps.stemTerm(s) + " "));
            //Creating bag of words
            var queryBagOfWords = new Dictionary<string, int>();
            foreach (var keyword in _rawKeywords)
            {
                var temp = _ps.stemTerm(keyword);
                queryBagOfWords[keyword] = processedQuery.Split(null).Count(s => s.Equals(_ps.stemTerm(temp)));
            }

            //Calculating TF
            var queryTF = new Dictionary<string, double>();
            var queryTFMax = queryBagOfWords.Max(w => w.Value);
            foreach (var word in queryBagOfWords)
            {
                queryTF[word.Key] = queryTFMax <= 0 ? 0 : (double)queryBagOfWords[word.Key] / queryTFMax;
            }

            //Calculationg TF-IDF
            var queryTFIDFVectorValue = DistanceN(queryTF.Select(tf => IDF[tf.Key] * tf.Value));

            v_ListView_ResultList.ItemsSource = _documents.OrderByDescending(d => d.Similarity).ToList();

            //CALCULATING SIMILARITY
            foreach (var docRep in _documents)
            {
                var x = docRep.TFIDFVectorValue * queryTFIDFVectorValue;
                double val = 0;
                foreach (var keyword in _rawKeywords)
                {
                    val += docRep.TF[keyword] * IDF[keyword] * queryTF[keyword] * IDF[keyword];
                }
                docRep.Similarity = x > 0 ? val / x : 0;
            }
            #endregion

            //Checking Correlation
            #region Correlation
            List<CorrelatedWord> correlatedWords = new List<CorrelatedWord>();
            bool _first = true;
            foreach (var inputWord in GetWords(originalQuery))
            {
                if (_first)
                {
                    correlatedWords = GetCorrelateedWords(inputWord, allWords, wordsCorrelationMatrix).ToList();
                }
                else
                {
                    correlatedWords = GetCorrelateedWords(inputWord, allWords, wordsCorrelationMatrix).Where(c => correlatedWords.Any(w => w.Word.Equals(c.Word))).ToList();
                }

                _first = false;
            }
            var stemedWords = GetWords(originalQuery).Select(w => _ps.stemTerm(w));
            var filteredWords = correlatedWords
                .Where(w => !string.IsNullOrWhiteSpace(w.Word))
                .Where(w => !stemedWords.Contains(_ps.stemTerm(w.Word)))
                .Where(w => !originalQuery.Contains(w.Word))
                .Where(w => !_stopWords.Contains(w.Word))
                .Where(w => w.Correlation >= _minCorrelationValue);

            var orderedResult = filteredWords.GroupBy(c => c.Word)
                .Select(x => new CorrelatedWord()
                {
                    Word = x.Key,
                    Correlation = x.Select(z => z.Correlation).Aggregate((a, b) => a + b)
                })
                .OrderByDescending(w => w.Correlation)
                .Take(5);
            #endregion

            //next word
            #region Next Word

            var lastQueryWord = GetWords(originalQuery).LastOrDefault();
            List<CorrelatedWord> nextWordsOrdered = new List<CorrelatedWord>();
            if (!string.IsNullOrWhiteSpace(lastQueryWord))
            {
                if (_nextWordCounter.ContainsKey(lastQueryWord))
                {
                    var sum = _nextWordCounter[lastQueryWord].Sum(c => c.Value);
                    nextWordsOrdered = _nextWordCounter[lastQueryWord].OrderByDescending(c => c.Value)
                        .Select(w => new CorrelatedWord() { Word = w.Key, Correlation = sum > 0 ? (double)w.Value/sum : 0}).ToList();
                }
            }

            #endregion

            //LSI
            #region LSI
            //bag of words
            Vector<double> qT = Vector<double>.Build.DenseOfArray(queryBagOfWords.Select(w => (double)w.Value).ToArray());//new double[] { 0, 1, 0, 0, 1 });
            // TF/IDF
            //Vector<double> qT = Vector<double>.Build.DenseOfArray(queryTF.Select(w => w.Value * IDF[w.Key]).ToArray());//new double[] { 0, 1, 0, 0, 1 });

            var transformedQuery = qT * K_s * S_s.Inverse();

            var queryValue = DistanceN(transformedQuery);

            var docValues = new double[D_s.RowCount];
            for (int i = 0; i < docValues.Length; i++)
            {
                docValues[i] = DistanceN(D_s.Row(i));
            }

            var sumOfProducts = new double[D_s.RowCount];
            for (int i = 0; i < sumOfProducts.Length; i++)
            {
                sumOfProducts[i] = 0;
                for (int j = 0; j < D_s.Row(i).Count; j++)
                {
                    sumOfProducts[i] += D_s[i, j] * transformedQuery[j];
                }
            }

            var sim = new double[D_s.RowCount];
            for (int i = 0; i < sim.Length; i++)
            {
                sim[i] = queryValue > 0 ? sumOfProducts[i] / queryValue : 0;
                _documents[i].LsiSimilarity = sim[i];
            }

            v_ListView_LSIResultList.ItemsSource = _documents.OrderByDescending(d => d.LsiSimilarity).ToList();
            #endregion

            switch (_currentSuggestionsMethod)
            {
                case SuggestionsMethod.Correlation:
                    v_ListBox_Suggestions.ItemsSource = orderedResult;
                    break;
                case SuggestionsMethod.NextWord:
                    v_ListBox_Suggestions.ItemsSource = nextWordsOrdered;
                    break;
                default:
                    break;
            }
        }
        public void CheckDoneList(List<Score> scores, bool isFirst)
        {
            if(scores.Any(x => x.Action == ActionPoints.Action.LandStatusChanged.ToString()))
            {
                if(isFirst)
                    this.Task1.Visibility = Visibility.Collapsed;
                else
                    this.HideTask1.Begin();
            }
            if (scores.Any(x => x.Action == ActionPoints.Action.ConfirmationAdded.ToString()))
            {
                if (isFirst)
                    this.Task2.Visibility = Visibility.Collapsed;
                else
                    this.HideTask2.Begin();
            }
            if (scores.Any(x => x.Action == ActionPoints.Action.Shared.ToString()))
            {
                if (isFirst)
                    this.Task3.Visibility = Visibility.Collapsed;
                else
                    this.HideTask3.Begin();
            }
            if (scores.Any(x => x.Action == ActionPoints.Action.LandReassigned.ToString()))
            {
                if (isFirst)
                    this.Task4.Visibility = Visibility.Collapsed;
                else
                    this.HideTask4.Begin();
            }
            if (scores.Count(x => x.Action == ActionPoints.Action.Login.ToString()) > 5)
            {
                if (isFirst)
                    this.Task5.Visibility = Visibility.Collapsed;
                else
                    this.HideTask5.Begin();
            }
            if (scores.Count(x => x.Action == ActionPoints.Action.ConfirmationAdded.ToString()) > 5)
            {
                if (isFirst)
                    this.Task6.Visibility = Visibility.Collapsed;
                else
                    this.HideTask6.Begin();
            }

            if((Task1.Opacity == 0 || Task1.Visibility == Visibility.Collapsed)
            && (Task2.Opacity == 0 || Task2.Visibility == Visibility.Collapsed)
            && (Task3.Opacity == 0 || Task3.Visibility == Visibility.Collapsed)
            && (Task4.Opacity == 0 || Task4.Visibility == Visibility.Collapsed)
            && (Task5.Opacity == 0 || Task5.Visibility == Visibility.Collapsed)
            && (Task6.Opacity == 0 || Task6.Visibility == Visibility.Collapsed))
            {
                this.MainGrid.Opacity = 0;
                this.MainBorder.Opacity = 0;
            }
            else
            {
                this.MainGrid.Opacity = 1;
                this.MainBorder.Opacity = 1;
            }
        }
        public bool CanGetRefactoring()
        {
            var commonStatements = new List<SyntaxNode>();
            var commonExpressions = new List<SyntaxNode>();

            // Get the block of the original method before extracting anything.
            var parentBlockBefore = ASTUtil.GetBlockOfMethod(parentMethodDeclarationBefore);

            // Get the block of the extracted method declaration.
            var extractedMethodBlock = ASTUtil.GetBlockOfMethod(extractedMethodDeclaration);

            // For each decendent node in the block of original method.
            foreach (var node in parentBlockBefore.DescendantNodes())
            {
                // Care about statements.
                if (node is StatementSyntax)
                {
                    // For each statement in the body of the extracted method
                    foreach (var statement in extractedMethodBlock.DescendantNodes().Where(n => n is StatementSyntax))
                    {
                        // If we some how think they are same, memorized that.
                        if (AreNodesEqual(statement, node))
                        {
                            commonStatements.Add(node);
                        }
                    }
                }

                // Care about expressions.
                if (node is ExpressionSyntax)
                {
                    // For each expression in the block of the extracted method.
                    foreach (var expression in extractedMethodBlock.DescendantNodes().Where(n => n is ExpressionSyntax))
                    {
                        // If we somehow think they are same, memorize that.
                        if (AreNodesEqual(expression, node))
                        {
                            commonExpressions.Add(node);
                        }
                    }
                }
            }

            var analyzer = AnalyzerFactory.GetSyntaxNodesAnalyzer();

            // First-class customer: has statements in common.
            if (commonStatements.Any())
            {
                analyzer.SetSyntaxNodes(commonStatements);

                // Get the longest group of statements that are neighbors.
                var extractedStatements = analyzer.GetLongestNeighborredNodesGroup();
                refactoring = ManualRefactoringFactory.CreateManualExtractMethodRefactoring
                    (extractedMethodDeclaration, invocation, extractedStatements);
                return true;
            }

            // Second class customer: has expressions in common.
            if (commonExpressions.Any())
            {
                analyzer.SetSyntaxNodes(commonExpressions);

                // Get the longest node among all the expressions; It is not possible to extract
                // several expressions at the same time.
                var extractedExpression = analyzer.GetLongestNode();
                refactoring = ManualRefactoringFactory.CreateManualExtractMethodRefactoring
                    (extractedMethodDeclaration, invocation, extractedExpression);
                return true;
            }
            return false;
        }
        private void ShowNearbyPreviews(Dot[] nearby, Dot dot, RayHitTestParameters cameraRay, Point center2D)
        {
            #region previews, sizes

            int dotMinSize = Math.Min(dot.PreviewSize.X, dot.PreviewSize.Y);
            int minSize = dotMinSize;

            foreach (Dot nearDot in nearby)
            {
                EnsurePreviewGenerated(nearDot, _getPreview);

                minSize = Math1D.Min(minSize, nearDot.PreviewSize.X, nearDot.PreviewSize.Y);
            }

            double halfMin = minSize / 2d;
            double stepDist = halfMin * .05;

            #endregion

            #region project plane

            // Get a plane that is perpendicular to the look ray
            ITriangle plane = Math3D.GetPlane(dot.Position, cameraRay.Direction);

            // Project the points onto that plane
            var nearbyOnPlane = nearby.
                Select(o => new { Dot = o, PlanePoint = Math3D.GetClosestPoint_Plane_Point(plane, o.Position) }).
                ToArray();

            RotateTransform3D rotate = new RotateTransform3D(new QuaternionRotation3D(Math3D.GetRotation(new DoubleVector(cameraRay.Direction, _camera.UpDirection), new DoubleVector(new Vector3D(0, 0, -1), new Vector3D(0, 1, 0)))));

            #endregion

            // Lay these previews down along the directions of the projected points
            // nearby is sorted by distance from the center image

            // Don't start counter at a distance of zero, that's just wasted steps.  Figure out what cntr to use that is the distance of the two images touching
            int startIncrement = Convert.ToInt32(Math.Floor(((dotMinSize / 2d) + halfMin) / stepDist));

            // Remember the locations of each image rect
            List<Rect> existing = new List<Rect>();
            existing.Add(new Rect(center2D.X - (dot.PreviewSize.X / 2d), center2D.Y - (dot.PreviewSize.Y / 2d), dot.PreviewSize.X, dot.PreviewSize.Y));

            foreach (var nextDot in nearbyOnPlane)
            {
                #region project dot plane

                // Get the 2D direction this sketch is from the main
                Vector direction = rotate.Transform(nextDot.PlanePoint - dot.Position).ToVector2D();

                Vector dirUnit = direction.ToUnit();
                if (Math2D.IsInvalid(dirUnit))
                {
                    dirUnit = Math3D.GetRandomVector_Circular_Shell(1).ToVector2D();        // sitting on top of each other, just push it in a random direction
                }
                dirUnit = new Vector(dirUnit.X, -dirUnit.Y);

                #endregion

                #region find clear space

                Point point = new Point();
                Rect rect = new Rect();
                double halfX = nextDot.Dot.PreviewSize.X / 2d;
                double halfY = nextDot.Dot.PreviewSize.Y / 2d;

                // Keep walking along that direction until the rectangle doesn't intersect any existing sketches
                for (int cntr = startIncrement; cntr < 1000; cntr++)
                {
                    point = center2D + (dirUnit * (stepDist * cntr));
                    rect = new Rect(point.X - halfX, point.Y - halfY, nextDot.Dot.PreviewSize.X, nextDot.Dot.PreviewSize.Y);

                    if (!existing.Any(o => o.IntersectsWith(rect)))
                    {
                        break;
                    }
                }

                existing.Add(rect);

                #endregion

                ShowPreview(nextDot.Dot, point);
            }
        }
            private static Point3D[] GetIntersection_Hull_PlaneSprtConvexHull(List<Tuple<Point3D, Point3D>> lineSegments)
            {
                // Convert the line segments into single points (deduped)
                List<Point3D> points = new List<Point3D>();
                foreach (var segment in lineSegments)
                {
                    if (!points.Any(o => Math3D.IsNearValue(o, segment.Item1)))
                    {
                        points.Add(segment.Item1);
                    }

                    if (!points.Any(o => Math3D.IsNearValue(o, segment.Item2)))
                    {
                        points.Add(segment.Item2);
                    }
                }

                // Build a polygon out of the outermost points
                var hull2D = Math2D.GetConvexHull(points.ToArray());
                if (hull2D == null || hull2D.PerimiterLines.Length == 0)
                {
                    return null;
                }

                // Transform to 3D
                return hull2D.PerimiterLines.Select(o => hull2D.GetTransformedPoint(hull2D.Points[o])).ToArray();
            }
        private IEnumerable<ProductPricing> ConstructDomainEntities(IEnumerable<PricingImport> entities)
        {
           var newpricing = new List<ProductPricing>();
          
               foreach (var importentity in entities)
               {
                   try
                   {
                       var product = ObjectFactory.GetInstance<IPricingMapper>().GetProduct(importentity.ProductCode);
                       if (product != null)
                       {


                           if (!string.IsNullOrEmpty(importentity.PricingTireCode))
                           {
                               ProductPricingTier tire =
                                   ObjectFactory.GetInstance<IProductPricingTierRepository>().GetAll(true).
                                       FirstOrDefault(
                                           p =>
                                           p.Code != null && p.Code.ToLower() == importentity.PricingTireCode.ToLower());
                               if (tire == null)
                               {
                                   tire = new ProductPricingTier(Guid.NewGuid())
                                              {
                                                  Name = importentity.PricingTireCode,
                                                  Code = importentity.PricingTireCode,
                                                  Description = importentity.PricingTireCode,
                                              };
                                   try
                                   {
                                       ObjectFactory.GetInstance<IProductPricingTierRepository>().Save(tire);
                                   }
                                   catch
                                   {
                                   }
                               }
                               if (Update(tire.Id, product.id, importentity.SellingPrice, product.ExFactoryPrice))
                               {
                                   var pricing =
                                       ObjectFactory.GetInstance<IProductPricingRepository>().GetByProductAndTierId(
                                           product.id, tire.Id);
                                   if (pricing != null)
                                   {
                                       pricing.ProductPricingItems.Clear();
                                       pricing.ProductPricingItems.Add(
                                           new ProductPricing.ProductPricingItem(Guid.NewGuid())
                                               {
                                                   EffectiveDate = DateTime.Now,
                                                   ExFactoryRate = product.ExFactoryPrice,
                                                   SellingPrice = importentity.SellingPrice
                                               });
                                       ObjectFactory.GetInstance<IPricingMapper>().Update(pricing);

                                   }
                                   else
                                   {
                                       var newprice =
                                           ObjectFactory.GetInstance<IProductPricingFactory>().CreateProductPricing(
                                               product.id, tire.Id,
                                               product.ExFactoryPrice,
                                               importentity.SellingPrice,
                                               DateTime.Now);
                                       if (newprice != null)
                                           newpricing.Add(newprice);

                                   }
                               }
                           }
                           else
                           {
                               #region default pricing tier

                               var pricingTierDefault =
                                   ObjectFactory.GetInstance<IProductPricingTierRepository>().GetAll(true).
                                       FirstOrDefault(
                                           p => p.Name == "DefaultPricingTier");
                               if (pricingTierDefault == null)
                               {
                                   pricingTierDefault = new ProductPricingTier(Guid.NewGuid())
                                                            {
                                                                Name = "DefaultPricingTier",
                                                                Code = "DefaultPricingTier",
                                                                Description = "DefaultPricingTier",
                                                            };
                                   try
                                   {
                                       ObjectFactory.GetInstance<IProductPricingTierRepository>().Save(
                                           pricingTierDefault);
                                   }
                                   catch
                                   {
                                   }
                               }

                               if (Update(pricingTierDefault.Id, product.id, product.ExFactoryPrice,
                                          product.ExFactoryPrice))
                               {
                                   var defaultPrice =
                                       ObjectFactory.GetInstance<IProductPricingRepository>().GetByProductAndTierId(
                                           product.id, pricingTierDefault.Id);
                                   if (defaultPrice != null)
                                   {
                                       defaultPrice.ProductPricingItems.Clear();
                                       defaultPrice.ProductPricingItems.Add(
                                           new ProductPricing.ProductPricingItem(Guid.NewGuid())
                                               {
                                                   EffectiveDate = DateTime.Now,
                                                   ExFactoryRate = product.ExFactoryPrice,
                                                   SellingPrice = product.ExFactoryPrice
                                               });
                                       ObjectFactory.GetInstance<IPricingMapper>().Update(defaultPrice);

                                   }
                                   else
                                   {
                                       defaultPrice =
                                           ObjectFactory.GetInstance<IProductPricingFactory>().CreateProductPricing(
                                               product.id, pricingTierDefault.Id,
                                               product.ExFactoryPrice,
                                               product.ExFactoryPrice,
                                               DateTime.Now);
                                       if (defaultPrice != null &&
                                           !newpricing.Any(
                                               p =>
                                               p.Tier.Id == pricingTierDefault.Id &&
                                               p.ProductRef.ProductId == product.id))
                                           newpricing.Add(defaultPrice);
                                   }

                               }

                               #endregion
                           }

                       }
                       else
                       {
                           if (
                               !_failedPricings.Any(
                                   p => p.Equals(importentity.ProductCode, StringComparison.CurrentCultureIgnoreCase)))
                           {
                               _failedPricings.Add(importentity.ProductCode);
                           }
                       }

                   }
                   catch (Exception ex)
                   {

                   }
               }
               return newpricing;
           

        }
 private void WriteIntegerList(BinaryWriter bw, List<int> list)
 {
     if (list == null || !list.Any())
     {
         bw.Write(0);
     }
     else
     {
         bw.Write(list.Count);
         list.ForEach(x => bw.Write(x));
     }
 }
 internal static void SaveAsShortcut(PNote note)
 {
     try
     {
         // create shortcut
         var counter = 1;
         var arguments = "-i " + note.ID;
         var pntargets = new List<string>();
         var desktop = new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory));
         var shortcuts = desktop.GetFiles("*.lnk");
         //get all desktop shortcuts first
         foreach (var f in shortcuts)
         {
             using (var link = new PNShellLink())
             {
                 link.Load(f.FullName);
                 if (string.Equals(link.Target, System.Windows.Forms.Application.ExecutablePath, StringComparison.OrdinalIgnoreCase))
                 {
                     //collect shortcuts to PNotes.NET
                     pntargets.Add(f.FullName);
                 }
             }
         }
         var shortcutName = note.Name;
         while (true)
         {
             if (pntargets.Any(s =>
             {
                 var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(s);
                 return fileNameWithoutExtension != null && string.Equals(fileNameWithoutExtension, shortcutName, StringComparison.OrdinalIgnoreCase);
             }))
             {
                 counter++;
                 shortcutName = note.Name + "(" + counter + ")";
                 continue;
             }
             break;
         }
         foreach (var s in pntargets)
         {
             using (var link = new PNShellLink())
             {
                 link.Load(s);
                 if (link.Arguments == arguments)
                 {
                     //exit if there is shortcut to the current note
                     return;
                 }
             }
         }
         var shortcutFile = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "\\" +
                            shortcutName + ".lnk";
         if (File.Exists(shortcutFile)) return;
         using (var link = new PNShellLink())
         {
             link.ShortcutFile = shortcutFile;
             link.Target = System.Windows.Forms.Application.ExecutablePath;
             link.WorkingDirectory = System.Windows.Forms.Application.StartupPath;
             link.IconPath = System.Windows.Forms.Application.ExecutablePath;
             link.IconIndex = 1;
             link.Arguments = arguments;
             link.Save();
         }
         if (PNStatic.Settings.GeneralSettings.CloseOnShortcut)
         {
             ShowHideSpecificNote(note, false);
         }
     }
     catch (Exception ex)
     {
         PNStatic.LogException(ex);
     }
 }
Beispiel #24
0
        private void BtnStartClick(object sender, RoutedEventArgs e)
        {
            if (lstViewTestcases.SelectedItems.Count == 0 || languages.SelectedItems.Count == 0 ||
                lstBrowser.SelectedItems.Count == 0)
            {
                ShowErrorMessage("You must select at least one test, one language and one browser. At least one of them is missing.", "Missing arguments!");
                return;
            }

            SetSelectedItems(languages);
            SetSelectedItems(lstBrowser);

            List<string> selectedBrowsersLocal = new List<string>();
            List<string> selectedBrowsersRemote = new List<string>();

            foreach (object selectedObject in lstBrowser.SelectedItems)
            {
                CheckBox checkBox = selectedObject as CheckBox;
                if (checkBox != null)
                {
                    string selectedBrowser = checkBox.Tag.ToString();
                    if(selectedBrowser.StartsWith(LocalPrefix))
                        selectedBrowsersLocal.Add(selectedBrowser.Substring(LocalPrefix.Length));
                    if (selectedBrowser.StartsWith(RemotePrefix))
                        selectedBrowsersRemote.Add(selectedBrowser.Substring(RemotePrefix.Length));
                }
            }

            List<string> selectedLanguages = languages.SelectedItems.Cast<CheckBox>().Where(checkBox => checkBox.IsChecked.HasValue && checkBox.IsChecked.Value).Select(checkBox => checkBox.Tag.ToString()).ToList();
            List<string> selectedTestcases = lstViewTestcases.SelectedItems.Cast<string>().ToList();

            _localTestLogic.SetAppSetting("TestcaseFilter", txtFilter.Text);
            _localTestLogic.SetAppSetting("TestcaseFile", txtFile.Text);
            _localTestLogic.SetAppSetting("Testsystem", txtTestsystem.Text);
            _localTestLogic.SetAppSetting("Language", string.Join("|", selectedLanguages));
            _localTestLogic.SetAppSetting("Browser", string.Join("|", lstBrowser.SelectedItems.Cast<CheckBox>().Where(checkBox => checkBox.IsChecked.HasValue && checkBox.IsChecked.Value).Select(checkBox => checkBox.Tag.ToString())));
            _localTestLogic.SetAppSetting("Testcase", string.Join("|", lstViewTestcases.SelectedItems.Cast<string>()));

            string testsystem = txtTestsystem.Text;
            string fileName = txtFile.Text;

            LoadTestcaseFile(txtFile.Text);

            if(selectedBrowsersLocal.Any())
                TestLocal(testsystem,selectedBrowsersLocal,selectedTestcases,selectedLanguages);

            if (selectedBrowsersRemote.Any())
                TestRemote(fileName,testsystem, selectedBrowsersRemote, selectedTestcases, selectedLanguages);
        }
Beispiel #25
0
        private void Delete()
        {
            List<Group> groups = new List<Group>();
            groups = LoadGroupsForInstructor(selected_instructor);

            if ((groups.Any()) && (DeleteGroupsCheck.IsChecked == false))
            {
                MessageBox.Show("Opening Edit window to assign new instructor for associated groups");
                foreach (Group gp in groups)
                {
                    EditGroupWindow edit = new EditGroupWindow(gp, connection);
                    edit.ShowDialog();
                }
                Delete();
                
            }
            else if ((groups.Any()) && (DeleteGroupsCheck.IsChecked == true))
            {
                foreach (Group gp in groups)
                {
                    groups_to_delete.Add(gp);
                }
                instructors_to_delete.Add(selected_instructor);
                MessageBox.Show("Instructor added to deletion list.\n All associated groups marked for deletion \n Waiting for confirmation");
            }
            else
            {
                instructors_to_delete.Add(selected_instructor);
                MessageBox.Show("Instructor added to deletion list. Waiting for confirmation");
            }
        }
Beispiel #26
0
        private void MyAnalyze()
        {
            List<Product> listProductsSend;
            if (countProverok > 0 && listProducts == null)
            {
                countProverok++;
                textBlock.Dispatcher.BeginInvoke(new Action(delegate ()
                {
                    textBlock.DataContext = null;
                    textBlock.Text = "Идет проверка №" + countProverok;
                }));
                List<Product> listProducts2;
                EasyAnalyze esAnalyze = new EasyAnalyze();
                listProducts = esAnalyze.GoToPage(urlSite);

                if (!File.Exists("Products.json"))
                {
                    //первый запуск
                    try
                    {
                        File.WriteAllText(@"Products.json", JsonConvert.SerializeObject(listProducts));
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Ошибка записи файла. " + ex.Message);
                    }


                }
                else
                {
                    listProducts2 = JsonConvert.DeserializeObject<List<Product>>(File.ReadAllText("Products.json"));
                    

                    var differences = listProducts2.Where(l2 => listProducts.Any(l1 => l1.Id == l2.Id && l1.Price != l2.Price)).ToList();

                    listProductsSend = listProducts2.Except(listProducts, new ProductComparer()).ToList();
                    listProductsSend.AddRange(differences);
                    listProductsSend.AddRange(listProducts.Except(listProducts2, new ProductComparer()).ToList());
                    if (listProductsSend.Count > 0)
                    {
                        string allprod = "";
                        foreach (var prod in listProductsSend)
                        {
                            prod.Url = Regex.Replace(prod.Url, @"vk.com/wkview\.php\?act=show&al=1&loc=market-([0-9]{1,22}?)&w=product-([0-9)]{1,33})",
                                "vk.com/market-$1?w=product-$2");
                            allprod = allprod + " | " + prod.Name + " | " + prod.Price + " | " + prod.Url + " ; \n\r ";
                        }
                        Email.SendMail(login, pass, osn, allprod);
                        try
                        {
                            File.WriteAllText(@"Products.json", JsonConvert.SerializeObject(listProducts));
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("Файл не записался. " + ex.Message);
                        }

                    }

                }
                

                listProducts = null;

                //Distinct(new ProductComparer()).ToList(); ;
            }
            else if (countProverok == 0 && listProducts == null)
            {
                textBlock.Dispatcher.BeginInvoke(new Action(delegate ()
                {
                    textBlock.DataContext = null;
                    textBlock.Text = "Первичный сбор информации";
                }));
                
                EasyAnalyze esAnalyze = new EasyAnalyze();
                listProducts = esAnalyze.GoToPage(urlSite);

                if (!File.Exists("Products.json"))
                {
                    File.WriteAllText(@"Products.json", JsonConvert.SerializeObject(listProducts));

                }

                countProverok++;
                listProducts = null;
            }
            
        }
Beispiel #27
0
        /// <summary>
        /// track every item in the host's list (these are data items)
        /// Generate an appropriate depth for them
        /// </summary>
        /// <param name="host"></param>
        private void UpdateItemsTracker(TwitterPanel host)
        {
            trackedItems = (from trackers in trackedItems
                               where host.Items.Contains(trackers.Item)
                               select trackers).ToList();

            var newtrackers = from item in host.Items
                              where trackedItems.Any(t => t.Item.Equals(item)) == false
                              select MakeTracker(item, null);
            trackedItems.AddRange(newtrackers);

            // order trackedItems to be the right order according to the host

            trackedItems = (from item in host.Items
                            select trackedItems.First(t => t.Item.Equals(item))).ToList();

            // Adjust the depths for all the trackers, to account for new items
            int depth = -300;
            foreach (var track in trackedItems)
            {
                track.Z = depth;
                depth -= 1000;
            }

            // join every item in the hosts data list with all our known tracked items
            // this is a left join so we preserve existing tracker items

            //var newlist = (from child in host.Items
            //              join known in trackedItems on child equals known.Item into joined
            //              from item in joined.DefaultIfEmpty()
            //              select MakeTracker(child, item)).ToList();

            //int cnt = host.Items.Count;
            //var x = (from child in host.Items
            //         join known in trackedItems on child equals known.Item into joined
            //         from item in joined.DefaultIfEmpty()
            //         where item == null
            //         select child).ToList();

            //// Adjust the depths for all the trackers, to account for new items
            //int depth = -300;
            //foreach (var track in newlist)
            //{
            //    track.Z = depth;
            //    depth -= 1000;
            //}
            //trackedItems = newlist;
        }
        private void ShowNearbySketches(Dot[] nearby, Point3D center3D, RayHitTestParameters cameraRay, Point center2D)
        {
            // Get a plane that is perpendicular to the look ray
            ITriangle plane = Math3D.GetPlane(center3D, cameraRay.Direction);

            // Project the points onto that plane
            var nearbyOnPlane = nearby.
                Select(o => new { Sketch = o, PlanePoint = Math3D.GetClosestPoint_Plane_Point(plane, o.Position) }).
                ToArray();

            RotateTransform3D rotate = new RotateTransform3D(new QuaternionRotation3D(Math3D.GetRotation(new DoubleVector(cameraRay.Direction, _camera.UpDirection), new DoubleVector(new Vector3D(0, 0, -1), new Vector3D(0, 1, 0)))));

            // Lay these images down along the directions of the projected points
            // nearby is sorted by distance from the center image

            double halfLarge = SKETCHSIZE_LARGE / 2;
            double halfSmall = SKETCHSIZE_SMALL / 2;

            double stepDist = SKETCHSIZE_SMALL * .05;

            // Don't start counter at a distance of zero, that's just wasted steps.  Figure out what cntr to use that is the distance of the two images touching
            int startIncrement = Convert.ToInt32(Math.Floor((halfSmall + halfLarge) / stepDist));

            // Remember the locations of each image rect
            List<Rect> existing = new List<Rect>();
            existing.Add(new Rect(center2D.X - halfLarge, center2D.Y - halfLarge, SKETCHSIZE_LARGE, SKETCHSIZE_LARGE));

            foreach (var nextSketch in nearbyOnPlane)
            {
                // Get the 2D direction this sketch is from the main
                Vector direction = rotate.Transform(nextSketch.PlanePoint - center3D).ToVector2D();

                Vector dirUnit = direction.ToUnit();
                if (Math2D.IsInvalid(dirUnit))
                {
                    dirUnit = Math3D.GetRandomVector_Circular_Shell(1).ToVector2D();        // sitting on top of each other, just push it in a random direction
                }
                dirUnit = new Vector(dirUnit.X, -dirUnit.Y);

                Point point = new Point();
                Rect rect = new Rect();

                // Keep walking along that direction until the rectangle doesn't intersect any existing sketches
                for (int cntr = startIncrement; cntr < 1000; cntr++)
                {
                    point = center2D + (dirUnit * (stepDist * cntr));
                    rect = new Rect(point.X - halfSmall, point.Y - halfSmall, SKETCHSIZE_SMALL, SKETCHSIZE_SMALL);

                    if (!existing.Any(o => o.IntersectsWith(rect)))
                    {
                        break;
                    }
                }

                existing.Add(rect);

                ShowImage(nextSketch.Sketch, point, false);
            }
        }
Beispiel #29
0
        private void RichTextBoxContextMenuOpening(object sender, ContextMenuEventArgs e)
        {
            List<Control> menuItems = new List<Control>();

            SpellingError spellingError = richTextBox.GetSpellingError(richTextBox.CaretPosition);
            if (spellingError != null)
            {
                foreach (string suggestion in spellingError.Suggestions.Take(5))
                {
                    MenuItem menuItem = new MenuItem()
                    {
                        Header = suggestion,
                        FontWeight = FontWeights.Bold,
                        Command = EditingCommands.CorrectSpellingError,
                        CommandParameter = suggestion
                    };
                    menuItems.Add(menuItem);
                }

                if (!menuItems.Any())
                {
                    MenuItem noSpellingSuggestions = new MenuItem()
                    {
                        Header = Properties.Resources.NoSpellingSuggestions,
                        FontWeight = FontWeights.Bold,
                        IsEnabled = false,
                    };
                    menuItems.Add(noSpellingSuggestions);
                }

                menuItems.Add(new Separator());

                MenuItem ignoreAllMenuItem = new MenuItem()
                {
                    Header = Properties.Resources.IgnoreAllMenu,
                    Command = EditingCommands.IgnoreSpellingError
                };
                menuItems.Add(ignoreAllMenuItem);

                menuItems.Add(new Separator());
            }

            foreach (Control item in menuItems.Reverse<Control>())
            {
                contextMenu.Items.Insert(0, item);
            }

            dynamicContextMenuItems = menuItems;
        }
        public IList<ImportValidationResultInfo> ValidateAndSave(List<PricingImport> entities)
        {
            int batchSize = Convert.ToInt32(0.2 * entities.Count);
            var productPricingImports = entities.OrderBy(p => p.ProductCode).Batch(batchSize).Select(x => x.ToList()).ToList();

            #region Contruct Items
            var taskArray = new Task<IEnumerable<ProductPricing>>[productPricingImports.Count];
            var results = new List<ProductPricing>();
            try
            {
                for (int i = 0; i < taskArray.Length; i++)
                {
                    var current = productPricingImports.FirstOrDefault();
                    if (current != null && current.Any())
                    {
                        //taskArray[i] = Task<IEnumerable<ProductPricing>>.Factory.StartNew(() => ConstructDomainEntities(current));
                        ConstructDomainEntities(current);
                        productPricingImports.Remove(current);
                    }
                }

                foreach (var result in taskArray.Select(n => n.Result).ToList())
                {
                    results.AddRange(result);
                }
            }
            catch (AggregateException ex)
            {
            }
            #endregion

            #region Validate
            var validationResults = new List<ImportValidationResultInfo>();
            if (results.Any())
            {
                batchSize = Convert.ToInt32(0.2 * results.Count);
                var products = results.OrderBy(p => p.CurrentEffectiveDate).Batch(batchSize).Select(x => x.ToList()).ToList();
                var validationTaskArray = new Task<ImportValidationResultInfo[]>[products.Count];


                try
                {
                    for (int i = 0; i < validationTaskArray.Length; i++)
                    {
                        var current = products.FirstOrDefault();
                        if (current != null && current.Any())
                        {
                            validationTaskArray[i] =
                                Task<ImportValidationResultInfo[]>.Factory.StartNew(() => ValidatePricings(current));
                            products.Remove(current);
                        }
                    }

                    foreach (var result in validationTaskArray.Select(n => n.Result).ToList())
                    {
                        validationResults.AddRange(result);
                    }
                }
                catch (AggregateException ex)
                {
                }

            }
            #endregion

            #region Save valid Items
            var validatedPricings = validationResults.Where(n => n.IsValid).Select(n => (ProductPricing)n.Entity).ToList();
            if (validatedPricings.Any())
            {
                batchSize = Convert.ToInt32(0.2 * validatedPricings.Count);
                var products =
                    validatedPricings.OrderBy(p => p.CurrentEffectiveDate).Batch(batchSize).Select(x => x.ToList()).ToList();
                var saveTasksArray = new Task<Guid[]>[products.Count];
                try
                {
                    for (int i = 0; i < saveTasksArray.Length; i++)
                    {
                        var current = products.FirstOrDefault();
                        if (current != null && current.Any())
                        {
                            saveTasksArray[i] =
                                Task<Guid[]>.Factory.StartNew(() => SaveProductPricings(current));
                            products.Remove(current);
                        }
                    }
                    var savedResults = new List<Guid>();
                    foreach (var result in saveTasksArray.Select(n => n.Result).ToList())
                    {
                        savedResults.AddRange(result);
                    }
                }
                catch (AggregateException ex)
                {
                }
            }
            #endregion

            return validationResults.Where(p => !p.IsValid).ToList();
        }