Ejemplo n.º 1
0
        public Session(IReceiver receiver, IAnalysis analysis)
        {
            Id = Guid.NewGuid();
            Receiver = receiver;

            DiagnoseOutputEntries = new ReactiveCollection<IDiagnoseOutputEntry>();
            Analysis = new ReactiveCollection<IAnalysis>();

            Analysis.ItemsAdded.Subscribe(x =>
                {
                    foreach (var diagnoseOutputEntry in DiagnoseOutputEntries)
                    {
                        x.ProcessNewDiagnoseOutputEntry(diagnoseOutputEntry);
                    }
                });

            Analysis.Add(analysis);

            DiagnoseOutputEntries.ItemsAdded.Subscribe(x =>
                {
                    foreach (var analyse in Analysis)
                    {
                        analyse.ProcessNewDiagnoseOutputEntry(x);
                    }
                });
        }
Ejemplo n.º 2
0
		/// <summary>
		/// Create a new one.
		/// </summary>
		/// <param name="cache"></param>
		/// <param name="ss"></param>
		/// <param name="choices"></param>
		/// <param name="analysis"></param>
		/// <param name="mediator"></param>
		public TryAWordSandbox(FdoCache cache, Mediator mediator, IVwStylesheet ss, InterlinLineChoices choices,
			IAnalysis analysis)
			: base(cache, mediator, ss, choices)
		{
			SizeToContent = true;
			LoadForWordBundleAnalysis(analysis.Hvo);
		}
 /// ------------------------------------------------------------------------------------
 /// <summary>
 /// Constructor for ParaFragment
 /// </summary>
 /// <param name="seg">The segment.</param>
 /// <param name="ichBegin">The character offset to the start of the fragment, relative
 /// to the start of the paragraph.</param>
 /// <param name="ichEnd">The character offset to the end (actually the limit) of the
 /// fragment, relative to the start of the paragraph.</param>
 /// <param name="analyis">The analyis.</param>
 /// ------------------------------------------------------------------------------------
 public ParaFragment(ISegment seg, int ichBegin, int ichEnd, IAnalysis analyis)
 {
     Segment     = seg;
     BeginOffset = ichBegin;
     EndOffset   = ichEnd;
     Analysis    = analyis;
 }
Ejemplo n.º 4
0
 /// <summary>
 /// Create a new one.
 /// </summary>
 /// <param name="cache"></param>
 /// <param name="ss"></param>
 /// <param name="choices"></param>
 /// <param name="analysis"></param>
 /// <param name="mediator"></param>
 public TryAWordSandbox(FdoCache cache, Mediator mediator, IVwStylesheet ss, InterlinLineChoices choices,
                        IAnalysis analysis)
     : base(cache, mediator, ss, choices)
 {
     SizeToContent = true;
     LoadForWordBundleAnalysis(analysis.Hvo);
 }
Ejemplo n.º 5
0
 private void Analysis()
 {
     _state = true;
     SetControlEnable(ButtonAnalysis, false);
     if (!String.IsNullOrEmpty(textBoxUrl.Text.TrimStart().TrimEnd()))
     {
         IAnalysis analysis = ArticleAnalysisFactory.Instance().CreateAnalysis(1);
         if (analysis != null)
         {
             ArticleDownAction downAction  = new ArticleDownAction();
             String            html        = downAction.GetHtml(textBoxUrl.Text.TrimStart().TrimEnd());
             ArticleModel      article     = analysis.Analysis(html);
             String            articleJson = Newtonsoft.Json.JsonConvert.SerializeObject(article);
             AddMessage(articleJson);
         }
         else
         {
             AddMessage("暂时还未支持该站点的文章采集,程序猿正在紧张处理中!!!");
         }
     }
     else
     {
         AddMessage("请输入需要采集的文章地址!");
     }
     _state = false;
     SetControlEnable(ButtonAnalysis, true);
 }
Ejemplo n.º 6
0
        public AnalysisViewModel(IDispatcher dispatcher,
                                 AnalysisViewTemplate viewTemplate,
                                 IAnalysis analyser,
                                 IAnalysisStorage analysisStorage,
                                 IPluginLoader pluginLoader)
        {
            _dispatcher             = dispatcher ?? throw new ArgumentNullException(nameof(dispatcher));
            _analyser               = analyser ?? throw new ArgumentNullException(nameof(analyser));
            _analysisStorage        = analysisStorage ?? throw new ArgumentNullException(nameof(analysisStorage));
            _viewTemplate           = viewTemplate ?? throw new ArgumentNullException(nameof(viewTemplate));
            _pluginLoader           = pluginLoader ?? throw new ArgumentNullException(nameof(pluginLoader));
            _pages                  = new ObservableCollection <AnalysisPageViewModel>();
            _addPageCommand         = new DelegateCommand(AddNewPage);
            _removeCommand          = new DelegateCommand(RemoveThis);
            _captureSnapshotCommand = new DelegateCommand2(CaptureSnapshot)
            {
                CanBeExecuted = true
            };

            if (viewTemplate.Pages.Any())
            {
                foreach (var pageTemplate in viewTemplate.Pages)
                {
                    // TODO: Solve this conundrum!
                    AddPage((PageTemplate)pageTemplate);
                }
            }
            else
            {
                AddNewPage();
            }

            _selectedPage = _pages.FirstOrDefault();
        }
Ejemplo n.º 7
0
 private void SimpleAnalysis()
 {
     _state = true;
     SetControlEnable(buttonSimpleAnalysis, false);
     if (!String.IsNullOrEmpty(textBoxUrl.Text.TrimStart().TrimEnd()))
     {
         IAnalysis analysis = ArticleAnalysisFactory.Instance().CreateAnalysis(1);
         if (analysis != null)
         {
             ArticleDownAction downAction = new ArticleDownAction();
             String            html       = downAction.GetHtml(textBoxUrl.Text.TrimStart().TrimEnd());
             _simpleArticleModel = analysis.SimpleAnalysis(html);
             String        articleJson = Newtonsoft.Json.JsonConvert.SerializeObject(_simpleArticleModel);
             StringBuilder builder     = new StringBuilder();
             builder.AppendFormat("<html><body>{0}</body></html>", _simpleArticleModel.ContentModels);
             _filePath = String.Format(@"{0}html\\htmltest_{1}.html", AppDomain.CurrentDomain.BaseDirectory, DateTime.Now.ToString("ffff"));
             File.WriteAllText(_filePath, builder.ToString(), Encoding.Unicode);
             //_filePath = string.Format("file:///{0}", _filePath);
             AddMessage(articleJson);
         }
         else
         {
             AddMessage("暂时还未支持该站点的文章采集,程序猿正在紧张处理中!!!");
         }
     }
     else
     {
         AddMessage("请输入需要采集的文章地址!");
     }
     _state = false;
     SetControlEnable(buttonSimpleAnalysis, true);
 }
Ejemplo n.º 8
0
        public static ForwardAnalysisSolver <AState, Type, EdgeData> Make <Local, Parameter, Method, Field, Source, Dest, Context>(
            IDecodeMSIL <APC, Local, Parameter, Method, Field, Type, Source, Dest, Context, EdgeData> decoder,
            IAnalysis <APC, AState, IVisitMSIL <APC, Local, Parameter, Method, Field, Type, Source, Dest, AState, AState>, EdgeData> driver,
            ILPrinter <APC> printer
            )
            where Context : IMethodContext <Field, Method>
        {
            Contract.Requires(decoder != null);
            Contract.Requires(driver != null);

            IVisitMSIL <APC, Local, Parameter, Method, Field, Type, Source, Dest, AState, AState> visitor = driver.Visitor();
            var result = new ForwardAnalysisSolver <AState, Type, EdgeData>(
                decoder.Context.MethodContext.CFG,
                delegate(APC pc, AState state) { return(decoder.ForwardDecode <AState, AState, IVisitMSIL <APC, Local, Parameter, Method, Field, Type, Source, Dest, AState, AState> >(pc, visitor, state)); },
                driver.EdgeConversion,
                driver.Join,
                driver.ImmutableVersion,
                driver.MutableVersion,
                driver.Dump,
                delegate(APC pc, AState state) { return(decoder.IsUnreachable(pc) || driver.IsBottom(pc, state)); },
                delegate(APC pc, AState state) { return(driver.IsTop(pc, state)); },
                printer,
                decoder.Display,
                decoder.EdgeData
                );

            result.CachePolicy = driver.CacheStates(result);
            return(result);
        }
Ejemplo n.º 9
0
        /// <inheritdoc />
        public Task SaveSnapshot(IAnalysis analysis, AnalysisViewTemplate viewTemplate)
        {
            var tmp = analysis as ActiveAnalysis;

            if (tmp == null)
            {
                throw new ArgumentException("It makes no sense to create a snapshot from anything else but an active analysis",
                                            nameof(analysis));
            }

            var analysisSnapshot = tmp.CreateSnapshot();
            var template         = new AnalysisTemplate(analysisSnapshot.Analysers.Select(x => new AnalyserTemplate
            {
                Id = x.Id,
                AnalyserPluginId = x.AnalyserPluginId,
                Configuration    = x.Configuration
            }));
            var clone   = viewTemplate.Clone();
            var results = analysisSnapshot.Analysers.Select(x => new AnalyserResult
            {
                AnalyserId = x.Id,
                Result     = x.Result
            }).ToList();
            var snapshot = new Core.Analysis.AnalysisSnapshot(template, clone, results);

            return(_snapshots.Save(snapshot));
        }
Ejemplo n.º 10
0
        /// <summary>
        /// add any alternative forms (in alternative writing systems) to the wordform.
        /// Overwrite any existing alternative form in a given alternative writing system.
        /// </summary>
        /// <param name="analysis"></param>
        /// <param name="word"></param>
        /// <param name="wsMainVernWs"></param>
        /// <param name="strFactory"></param>
        private static void AddAlternativeWssToWordform(IAnalysis analysis, Word word, ILgWritingSystem wsMainVernWs, ITsStrFactory strFactory)
        {
            ILgWritingSystemFactory wsFact = analysis.Cache.WritingSystemFactory;
            var wf = analysis.Wordform;

            foreach (var wordItem in word.Items)
            {
                ITsString wffAlt = null;
                switch (wordItem.type)
                {
                case "txt":
                    var wsAlt = GetWsEngine(wsFact, wordItem.lang);
                    if (wsAlt.Handle == wsMainVernWs.Handle)
                    {
                        continue;
                    }
                    wffAlt = strFactory.MakeString(wordItem.Value, wsAlt.Handle);
                    if (wffAlt.Length > 0)
                    {
                        wf.Form.set_String(wsAlt.Handle, wffAlt);
                    }
                    break;
                }
            }
        }
        public Session(IReceiver receiver, IAnalysis analysis)
        {
            Id       = Guid.NewGuid();
            Receiver = receiver;

            DiagnoseOutputEntries = new ReactiveCollection <IDiagnoseOutputEntry>();
            Analysis = new ReactiveCollection <IAnalysis>();

            Analysis.ItemsAdded.Subscribe(x =>
            {
                foreach (var diagnoseOutputEntry in DiagnoseOutputEntries)
                {
                    x.ProcessNewDiagnoseOutputEntry(diagnoseOutputEntry);
                }
            });

            Analysis.Add(analysis);

            DiagnoseOutputEntries.ItemsAdded.Subscribe(x =>
            {
                foreach (var analyse in Analysis)
                {
                    analyse.ProcessNewDiagnoseOutputEntry(x);
                }
            });
        }
        private FDO.IText MakeText(string contents)
        {
            var text   = Cache.ServiceLocator.GetInstance <ITextFactory>().Create();
            var stText = Cache.ServiceLocator.GetInstance <IStTextFactory>().Create();

            text.ContentsOA = stText;
            var para = Cache.ServiceLocator.GetInstance <IStTxtParaFactory>().Create();

            stText.ParagraphsOS.Add(para);
            para.Contents = Cache.TsStrFactory.MakeString(contents, Cache.DefaultVernWs);

            using (var pp = new ParagraphParser(Cache))
            {
                pp.Parse(para);
            }

            ISegment seg = para.SegmentsOS.First();

            for (int i = 0; i < seg.AnalysesRS.Count; i++)
            {
                IAnalysis analysis = seg.AnalysesRS[i];
                var       wordform = analysis as IWfiWordform;
                if (wordform != null)
                {
                    seg.AnalysesRS[i] = wordform.AnalysesOC.First().MeaningsOC.First();
                }
            }
            return(text);
        }
Ejemplo n.º 13
0
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='job'>
 /// </param>
 /// <param name='workitem'>
 /// </param>
 /// <param name='analysisType'>
 /// </param>
 /// <param name='analysisName'>
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <object> GetDetailsAsync(this IAnalysis operations, string job, string workitem, string analysisType, string analysisName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
 {
     using (var _result = await operations.GetDetailsWithHttpMessagesAsync(job, workitem, analysisType, analysisName, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
Ejemplo n.º 14
0
        public static ForwardAnalysis <AbstractState, EdgeData> Make <Source, Dest, Context> (
            IILDecoder <APC, Source, Dest, Context, EdgeData> decoder,
            IAnalysis <APC, AbstractState, IILVisitor <APC, Source, Dest, AbstractState, AbstractState>, EdgeData> analysis)
            where Context : IMethodContextProvider
        {
            IILVisitor <APC, Source, Dest, AbstractState, AbstractState> visitor = analysis.GetVisitor();
            var forwardAnalysisSolver = new ForwardAnalysis <AbstractState, EdgeData> (
                decoder.ContextProvider.MethodContext.CFG,
                (pc, state) => decoder.ForwardDecode <AbstractState, AbstractState, IILVisitor <APC, Source, Dest, AbstractState, AbstractState> > (pc, visitor, state),
                analysis.Join,
                analysis.ImmutableVersion,
                analysis.MutableVersion,
                analysis.EdgeConversion,
                decoder.EdgeData,
                (pc, state) => {
                if (!decoder.IsUnreachable(pc))
                {
                    return(analysis.IsBottom(pc, state));
                }

                return(true);
            },
                analysis.Dump
                );

            analysis.SaveFixPointInfo(forwardAnalysisSolver);
            return(forwardAnalysisSolver);
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Informs the guess service that the indicated occurrence is being replaced with the specified new
        /// analysis. If necessary clear the GuessTable. If possible update it. The most common and
        /// performance-critical case is confirming a guess. Return true if the cache was changed.
        /// </summary>
        public bool UpdatingOccurrence(IAnalysis oldAnalysis, IAnalysis newAnalysis)
        {
            if (m_guessTable == null)
            {
                return(false);                // already cleared, forget it.
            }
            if (oldAnalysis == newAnalysis)
            {
                return(false);                // nothing changed, no problem.
            }
            if (!(oldAnalysis is IWfiWordform))
            {
                // In general, no predicting what effect it has on the guess for the
                // wordform or analysis that owns the old analysis. If the old analysis is
                // not the default for its owner or owner's owner, we are OK, but that's too rare
                // to worry about.
                ClearGuessData();
                return(true);
            }
            if (newAnalysis is IWfiWordform || newAnalysis.Wordform == null)
            {
                return(false);                // unlikely but doesn't mess up our guesses.
            }
            var result = false;
            // if the new analysis is NOT the guess for one of its owners, one more occurrence might
            // make it the guess, so we need to regenerate.
            IAnalysis currentDefault;

            if (!m_guessTable.TryGetValue(newAnalysis.Wordform, out currentDefault))
            {
                // We have no guess for this wordform: the new analysis becomes it.
                m_guessTable[newAnalysis.Wordform] = newAnalysis;
                result = true;                 // we didn't clear the cache but did change it.
            }
            else if (currentDefault != newAnalysis)
            {
                // Some other analysis just became more common...maybe now the default?
                ClearGuessData();
                return(true);
            }
            if (newAnalysis is IWfiAnalysis)
            {
                return(result);
            }
            if (!m_guessTable.TryGetValue(newAnalysis.Analysis, out currentDefault))
            {
                // We have no guess for this analysis: the new analysis becomes it.
                m_guessTable[newAnalysis.Analysis] = newAnalysis;
                result = true;                 // we didn't clear the cache but did change it.
            }
            else if (currentDefault != newAnalysis)
            {
                // Some other analysis just became more common...maybe now the default?
                ClearGuessData();
                return(true);
            }
            // We haven't messed up any guesses so the guess table can survive.
            return(result);            // but we may have filled in some guesses.
        }
        public Guid AddSession(IReceiver receiver, IAnalysis analysis)
        {
            var newSession = new Session(receiver, analysis);

            Sessions.Add(newSession);

            return(newSession.Id);
        }
Ejemplo n.º 17
0
        private void ShowAnalysis(string analysisName)
        {
            AnalysisSelected?.Close();
            IAnalysis analysis = _analysisViewModels[analysisName];

            analysis.Initialize();
            AnalysisSelected = analysis;
        }
        public Guid AddSession(IReceiver receiver, IAnalysis analysis)
        {
            var newSession = new Session(receiver, analysis);

            Sessions.Add(newSession);

            return newSession.Id;
        }
Ejemplo n.º 19
0
 public void SaveCommit(IAnalysis analysis, out bool success)
 {
     using (IUnitOfWork u = UnitOfWork.Begin())
     {
         Save(analysis, out success);
         if (success)
             u.Commit();
     }
 }
Ejemplo n.º 20
0
        public Func <AnalysisState, IFixpointInfo <APC, AnalysisState> > CreateForward <AnalysisState>(
            IAnalysis <APC, AnalysisState, IVisitMSIL <APC, Local, Parameter, Method, Field, Type, Expression, Variable, AnalysisState, AnalysisState>, EdgeData> analysis,
            DFAOptions options)
        {
            var solver = ForwardAnalysisSolver <AnalysisState, Type, EdgeData> .Make(this.ildecoder, analysis, this.Printer);

            solver.Options = options;
            return((initialState) => { solver.Run(initialState); return solver; });
        }
Ejemplo n.º 21
0
 public bool Equals(IAnalysis other)
 {
     return(other != null &&
            Name == other.Name &&
            ClosingPrice == other.ClosingPrice &&
            QtyInBuyingPacket == other.QtyInBuyingPacket &&
            EqualityComparer <ITechnicalAnalysis> .Default.Equals(TechnicalAnalysis, other.TechnicalAnalysis) &&
            EqualityComparer <IFinancialAnalysis> .Default.Equals(FinancialAnalysis, other.FinancialAnalysis));
 }
Ejemplo n.º 22
0
        public AnalysisContainer GetSentence()
        {
            if (iAnalysis == null)
            {
                iAnalysis = objAnalysis.GetComponent <IAnalysis>();
            }

            return(iAnalysis.Analysis(testChar));
        }
Ejemplo n.º 23
0
        private void CreateTryAWordSandbox()
        {
            // skip if it's before we've set the word
            if (m_sWordForm == null)
            {
                return;
            }
            // skip if it's before we've set up the rootsite control
            if (m_rootb == null)
            {
                return;
            }
            // skip if we're not visible
            if (!Visible)
            {
                return;
            }
            //Debug.WriteLine("TryAWordRootSite:WordForm - creating sandbox for " + m_sWordForm.Text);
            NonUndoableUnitOfWorkHelper.Do(m_cache.ActionHandlerAccessor, () =>
            {
                m_wordform = WfiWordformServices.FindOrCreateWordform(m_cache, m_sWordForm);
            });
            //if (m_cache.IsDummyObject(hvo))
            //	m_wordform = new WfiWordform();

            IAnalysis analysis = m_vc.GetGuessForWordform(m_wordform, m_cache.DefaultVernWs);

            if (analysis is NullWAG)
            {
                analysis = m_wordform;
            }

            m_rootb.SetRootObject(analysis.Hvo, m_vc, m_kfragSingleInterlinearAnalysisWithLabels, m_styleSheet);

            //Debug.Assert(m_tryAWordSandbox == null);
            m_tryAWordSandbox = new TryAWordSandbox(m_cache,
                                                    Mediator,
                                                    m_propertyTable,
                                                    StyleSheet,
                                                    m_vc.LineChoices,
                                                    analysis);
            m_tryAWordSandbox.Visible = false;
            Controls.Add(m_tryAWordSandbox);
            SetSandboxSize();
            SetSandboxLocation();
            m_tryAWordSandbox.Visible = true;
            SetBackgroundColor();
            int height = Math.Max(ScrollRange.Height, m_tryAWordSandbox.Height) + SystemInformation.HorizontalScrollBarHeight;

            if (Height != height)
            {
                Height = height;
            }
            m_tryAWordSandbox.SizeChanged += m_tryAWordSandbox_SizeChanged;
            //m_tryAWordSandbox.Focus();
        }
Ejemplo n.º 24
0
        public void DeleteCommit(IAnalysis analysis)
        {
            Checks.Argument.IsNotNull(analysis, "analysis");

            using (IUnitOfWork u = UnitOfWork.Begin())
            {
                _repo.Remove(analysis);
                u.Commit();
            }
        }
Ejemplo n.º 25
0
        public Func <AState, IFixPointInfo <APC, AState> > CreateForward <AState> (
            IAnalysis <APC, AState, IILVisitor <APC, Expression, Variable, AState, AState>, EdgeData> analysis)
        {
            ForwardAnalysis <AState, EdgeData> solver = ForwardAnalysis <AState, EdgeData> .Make(ILDecoder, analysis);

            return((initialState) => {
                solver.Run(initialState);
                return solver;
            });
        }
Ejemplo n.º 26
0
        public void DeleteCommit(IAnalysis analysis)
        {
            Checks.Argument.IsNotNull(analysis, "analysis");

            using (IUnitOfWork u = UnitOfWork.Begin())
            {
                _repo.Remove(analysis);
                u.Commit();
            }
        }
Ejemplo n.º 27
0
 public void SaveCommit(IAnalysis analysis, out bool success)
 {
     using (IUnitOfWork u = UnitOfWork.Begin())
     {
         Save(analysis, out success);
         if (success)
         {
             u.Commit();
         }
     }
 }
Ejemplo n.º 28
0
        private static IAnalysis[] LoadRibbonAnalyses(IInterlinRibbon mrib, int[] ribbonHvos)
        {
            var chvos  = ribbonHvos.Length;
            var result = new IAnalysis[chvos];

            for (var i = 0; i < chvos; i++)
            {
                result[i] = ((InterlinRibbonDecorator)mrib.Decorator).OccurrenceFromHvo(ribbonHvos[i]).Analysis;
            }
            return(result);
        }
Ejemplo n.º 29
0
 private IAnalysis GetBestGuess(IAnalysis wag, int ws)
 {
     if (wag is IWfiWordform)
     {
         return(GetBestGuess(wag.Wordform, ws));
     }
     if (wag is IWfiAnalysis)
     {
         return(GetBestGuess(wag.Analysis));
     }
     return(new NullWAG());
 }
Ejemplo n.º 30
0
        private static void AddWordToSegment(ISegment newSegment, Word word, ITsStrFactory strFactory)
        {
            //use the items under the word to determine what kind of thing to add to the segment
            var       cache    = newSegment.Cache;
            IAnalysis analysis = CreateWordAnalysisStack(cache, word, strFactory);

            // Add to segment
            if (analysis != null)
            {
                newSegment.AnalysesRS.Add(analysis);
            }
        }
Ejemplo n.º 31
0
 public IOutputType GetOutputType(IAnalysis analysis)
 {
     while (true)
     {
         _userInterface.AskWhichOutputType(analysis);
         var input = _userInterface.ReadLine();
         if (analysis.ValidOutputOption(input))
             return analysis.GetOutputType(input);
         if (input.Equals("7"))
             _userInterface.EasterEgg();
         _userInterface.NotifyInvalidResponse();
     }
 }
Ejemplo n.º 32
0
        public bool TryGetAnalysisFor(AnalysisId id, out IAnalysis analysis)
        {
            lock (_syncRoot)
            {
                ActiveAnalysis tmp;
                if (_analyses.TryGetValue(id, out tmp))
                {
                    analysis = tmp;
                    return(true);
                }
            }

            analysis = null;
            return(false);
        }
        private DataTable GetCollectionDetails()
        {
            DataTable dtColl = new DataTable();

            try
            {
                IAnalysis objCashdesk = AnalysisBusinessObject.CreateInstance();
                dtColl = objCashdesk.GetWeeklyCollectionDetails(_iWeekID);
            }
            catch (Exception ex)
            {
                ExceptionManager.Publish(ex);
            }
            return(dtColl);
        }
Ejemplo n.º 34
0
        public virtual async Task <T> GetAnalysis <T>(string analysisIdString = "",
                                                      bool recordInDb         = false)
            where T : IAnalysis
        {
            if (typeof(T) != typeof(TAnalysis))
            {
                throw new Exceptions.AnalysisTypeNotRecognizedException(typeof(T));
            }

            IAnalysis retAnalysis = null;

            retAnalysis = await GetAnalysisImpl(analysisIdString, recordInDb);

            AnalysisHasBeenBuilt = true;
            return((T)retAnalysis);
        }
        // Caller must create UOW
        private void ApplyAnalysisToInstancesOfWordform(IAnalysis newAnalysis, IWfiWordform oldWordform, IWfiWordform newWordform)
        {
            var navigator = new SegmentServices.StTextAnnotationNavigator(SelectedOccurrence);

            foreach (var occ in navigator.GetAnalysisOccurrencesAdvancingInStText().ToList())
            {
                // We certainly want to update any occurrence that exactly matches the wordform of the analysis we are confirming.
                // If oldWordform is different, we are confirming a different case form from what occurred in the text,
                // and we only confirm these if SelectedOccurrence and occ are both sentence-initial.
                // We want to do that only for sentence-initial occurrences.
                if (occ.Analysis == newWordform || (occ.Analysis == oldWordform && occ.Index == 0 && SelectedOccurrence.Index == 0))
                {
                    occ.Segment.AnalysesRS[occ.Index] = newAnalysis;
                }
            }
        }
Ejemplo n.º 36
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="socket"></param>
 /// <param name="socketPool"></param>
 /// <param name="id">通道Id</param>
 internal YChannel(Socket socket, SocketAsyncEventArgsPool socketPool, ChannelType ct, string id = "")
 {
     if (socket == null)
     {
         return;
     }
     this.ChannelType = ct;
     SetKeepAliveValues(socket, true, KeepTime, KeepTime * 2);
     this.socket       = socket;
     address           = (((IPEndPoint)socket.RemoteEndPoint).Address).ToString();
     port              = ((IPEndPoint)socket.RemoteEndPoint).Port;
     this.Id           = string.IsNullOrWhiteSpace(id) ? string.Format("{0}:{1}", address, port) : id;
     this.socketPool   = socketPool;
     dataPacketManager = new YDataPacketManager();
     dataPacketManager.DataPacketReceived += dataPacketManager_DataPacketReceived;
 }
Ejemplo n.º 37
0
        public void Save(IAnalysis analysis, out bool success)
        {
            Checks.Argument.IsNotNull(analysis, "myShow");

            success = false;

            if (null == _repo.FindById(analysis.AnalysisId).SingleOrDefault())
            {
                try
                {
                    _repo.Add(analysis);
                    success = true;
                }
                catch (Exception ex)
                {
                    success = false;
                }
            }
        }
Ejemplo n.º 38
0
		/// <summary>
		/// Make sure we have the right list of occurrences for the specified analysis (assumes we are using ExactOccurrences).
		/// </summary>
		public void UpdateExactAnalysisOccurrences(IAnalysis obj)
		{
			UpdateAnalysisOccurrences(obj, false);
		}
Ejemplo n.º 39
0
 public void AskWhichOutputType(IAnalysis analysis)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 40
0
		public MultipleAnalysesModel(IFullName item, IAnalysis[] analyses) {
			this.analyses = analyses;
			Item = item;
			Text = Utils.EscapeString(DisplayNameCreator.CreateFullName(item), false);
		}
Ejemplo n.º 41
0
			/// <summary>
			/// Finds an existing wfiAnalysis related to the given cba.InstanceOf.
			/// If none exists, we'll create one.
			/// </summary>
			private IWfiAnalysis FindOrCreateWfiAnalysis(IAnalysis analysisActual)
			{
				IWfiAnalysis actualWfiAnalysis = analysisActual.Analysis;
				if (actualWfiAnalysis == null)
					actualWfiAnalysis = CreateWfiAnalysisForAnalysis(analysisActual);
				return actualWfiAnalysis;
			}
Ejemplo n.º 42
0
		public void UpdatingOccurrence(IAnalysis oldAnalysis, IAnalysis newAnalysis)
		{
			m_vc.UpdatingOccurrence(oldAnalysis, newAnalysis);
		}
Ejemplo n.º 43
0
		/// <summary>
		/// Get a guess for the given word or analysis.
		/// </summary>
		/// <param name="analysis"></param>
		/// <returns></returns>
		internal int GetGuess(IAnalysis analysis)
		{
			if (Decorator.get_IsPropInCache(analysis.Hvo, InterlinViewDataCache.AnalysisMostApprovedFlid,
				(int)CellarPropertyType.ReferenceAtomic, 0))
			{
				int hvoResult = Decorator.get_ObjectProp(analysis.Hvo, InterlinViewDataCache.AnalysisMostApprovedFlid);
				if (hvoResult != 0)
					return hvoResult;  // may have been cleared by setting to zero.
			}
			return analysis.Hvo;
		}
Ejemplo n.º 44
0
			protected IWfiMorphBundle SetMorphBundle(IAnalysis analysis, int iMorphBundle, ILexSense sense)
			{
				IWfiAnalysis actualWfiAnalysis = analysis.Analysis;
				if (actualWfiAnalysis != null)
				{
					actualWfiAnalysis.MorphBundlesOS[iMorphBundle].SenseRA = sense;
					return actualWfiAnalysis.MorphBundlesOS[iMorphBundle];
				}
				return null;
			}
Ejemplo n.º 45
0
        public void Delete(IAnalysis analysis)
        {
            Checks.Argument.IsNotNull(analysis, "analysis");

            _repo.Remove(analysis);
        }
Ejemplo n.º 46
0
 public PluginBase()
 {
     Analyzer = new MsWebBrowserAnalysis();
 }
Ejemplo n.º 47
0
			private void CompareAnalyses(object expectedNode, IAnalysis actualAnalysis, string context)
			{
				var node = expectedNode as XmlNode;
				int hvoAnalysisExpected = ParagraphBuilder.GetAnalysisId(node);
				if (hvoAnalysisExpected == -1)
				{
					// default: no special analysis set, should have made a wordform or punctform with the same form as the node.
					IAnalysis analysis = (IAnalysis)m_cache.ServiceLocator.GetObject(actualAnalysis.Hvo);
					string expectedText = node.SelectSingleNode("StringValue37").InnerText;
					Assert.AreEqual(expectedText, analysis.GetForm(TsStringUtils.GetWsAtOffset(m_para.Contents, 0)).Text, context);
					string guid = ParagraphBuilder.GetAnnotationTypeGuid(node);
					if (guid == ParagraphBuilder.WficGuid)
						Assert.IsTrue(analysis is IWfiWordform, "default parse should produce wordform here " + context);
					else
						Assert.IsTrue(analysis is IPunctuationForm, "default parse should produce  punctuation form here " + context);
				}
				else
				{
					Assert.AreEqual(hvoAnalysisExpected, actualAnalysis.Hvo, context);
				}
			}
Ejemplo n.º 48
0
		private void MakeFirstSegReferenceAnalysis(IText text, IAnalysis analysis)
		{
			var seg = ((IStTxtPara) text.ContentsOA.ParagraphsOS[0]).SegmentsOS[0];
			seg.AnalysesRS.Add(analysis);
		}
Ejemplo n.º 49
0
			private void GetRealWordformInfo(IAnalysis actualAnalysis, out int hvoActualInstanceOf, out IWfiWordform realWordform)
			{
				hvoActualInstanceOf = actualAnalysis.Hvo;
				realWordform = actualAnalysis.Wordform;
			}
Ejemplo n.º 50
0
			/// <summary>
			/// Set the analysis at the specified segment, index.
			/// Enhance JohnT: may need it to fill in prior segments and/or annotations.
			/// </summary>
			private void SetAnalysis(int iSegment, int iSegForm, IAnalysis newGloss)
			{
				m_para.SegmentsOS[iSegment].AnalysesRS.Replace(iSegForm, 1, new ICmObject[] {newGloss});
			}
Ejemplo n.º 51
0
		private bool HasTrivialAnalysis(IAnalysis analysis)
		{
			return (!(analysis is IWfiAnalysis) && !(analysis is IWfiGloss));
		}
Ejemplo n.º 52
0
			private IWfiAnalysis CreateWfiAnalysisForAnalysis(IAnalysis actualAnalysis)
			{
				int hvoActualInstanceOf;
				IWfiWordform actualWordform;
				GetRealWordformInfo(actualAnalysis, out hvoActualInstanceOf, out actualWordform);

				// Create a new WfiAnalysis for the wordform.
				IWfiAnalysis actualWfiAnalysis = m_cache.ServiceLocator.GetInstance<IWfiAnalysisFactory>().Create();
				actualWordform.AnalysesOC.Add(actualWfiAnalysis);
				return actualWfiAnalysis;
			}
Ejemplo n.º 53
0
		public bool UpdatingOccurrence(IAnalysis oldAnalysis, IAnalysis newAnalysis)
		{
			if (m_loader != null)
			{
				CheckDisposed();
				return m_loader.UpdatingOccurrence(oldAnalysis, newAnalysis);
			}
			return false;
		}
Ejemplo n.º 54
0
			/// <summary>
			/// This awkwardly named method fits into a pattern of names for validating the outer (XML attributes) and inner
			/// (XML content) parts of an XML representation of an expected value. In this case, for an IAnalysis, the only
			/// thing we can verify is that it is the right object.
			/// </summary>
			protected override void ValidateSegFormOuterElements(object expectedSegForm, IAnalysis actualSegForm, string segFormContext)
			{
				CompareAnalyses(expectedSegForm, actualSegForm, segFormContext);
			}
Ejemplo n.º 55
0
			private void DisplayWord(InterlinLineSpec spec, int choiceIndex, IAnalysis wag)
			{
				var wsActual = m_this.GetRealWsOrBestWsForContext(m_hvoWordform, spec);
				var tssRealForm = GetRealForm(wsActual, choiceIndex);
				if (tssRealForm != null && tssRealForm.Length > 0)
				{
					m_this.IsDoingRealWordForm = true;
					// LT-12203 Text chart doesn't want multiple analyses highlighting
					if (m_fshowMultipleAnalyses)
					{
						//identify those words the user has yet to approve which have multiple possible
						//guesses user or machine, and set the background to a special color
						var word = wag as IWfiWordform;
						if (word != null)
						{
							//test if there are multiple analyses that a user might choose from
							if (SandboxBase.GetHasMultipleRelevantAnalyses(word))
							{
								m_this.SetGuessing(m_vwenv, MultipleApprovedGuessColor); //There are multiple options, set the color
							}
						}
					}
					m_vwenv.AddString(tssRealForm);
					m_this.IsDoingRealWordForm = false;
					return;
				}
				switch (m_defaultObj.ClassID)
				{
				case WfiWordformTags.kClassId:
				case WfiAnalysisTags.kClassId:
				case WfiGlossTags.kClassId:
					m_vwenv.AddObj(m_hvoWordform, m_this, kfragLineChoices + choiceIndex);
					break;
				default:
					throw new Exception("Invalid type found in Segment analysis");
				}
			}
Ejemplo n.º 56
0
		/// <summary>
		/// Replacing a single occurrence, we MIGHT need to reset the guess cache.
		/// </summary>
		public bool UpdatingOccurrence(IAnalysis oldAnalysis, IAnalysis newAnalysis)
		{
			var result = GuessServices.UpdatingOccurrence(oldAnalysis, newAnalysis);
			if (result)
				m_sdaDecorator.ClearPropFromCache(InterlinViewDataCache.AnalysisMostApprovedFlid);
			return result;
		}
Ejemplo n.º 57
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Constructor for ParaFragment
		/// </summary>
		/// <param name="seg">The segment.</param>
		/// <param name="ichBegin">The character offset to the start of the fragment, relative
		/// to the start of the paragraph.</param>
		/// <param name="ichEnd">The character offset to the end (actually the limit) of the
		/// fragment, relative to the start of the paragraph.</param>
		/// <param name="analyis">The analyis.</param>
		/// ------------------------------------------------------------------------------------
		public ParaFragment(ISegment seg, int ichBegin, int ichEnd, IAnalysis analyis)
		{
			Segment = seg;
			BeginOffset = ichBegin;
			EndOffset = ichEnd;
			Analysis = analyis;
		}
Ejemplo n.º 58
0
		bool TryReuseAnalysis(ITsString tssTxtWord, int ichMin, int ichLim, int ianalysis, out IWfiWordform wf, out ITsString tssWordAnn, out IAnalysis analysis)
		{
			analysis = null;
			tssWordAnn = tssTxtWord;
			wf = null;	// default
			if (m_preExistingAnalyses.Count == 0)
			{
				// Enhance: This is a new paragraph that may have resulted in breaking
				// up a previously existing paragraph. In that case we'd probably want to
				// try to preserve the annotations/analyses.
				return false;
			}

			// First, see if we have cached annotation ids for the wordform in this paragraph.
			// the wordform and its lowercase form may already be in the cache.
			string key = m_paragraphTextScanner.ToLower(tssTxtWord);
			IList<int> possibleIndices;
			if (!m_wordformAnnotationPossibilities.TryGetValue(key, out possibleIndices) || possibleIndices.Count == 0)
				return false; // we don't have any remaining annotations matching this wordform.
				possibleIndices = m_wordformAnnotationPossibilities[key];

			int iAnnClosest;
			GetBestPossibleAnnotation(ianalysis, possibleIndices, ichMin, ichLim - ichMin, out iAnnClosest);
			if (iAnnClosest == -1)
				return false;	// can happen, if all the possible reuseable ones are actually phrases.

			bool fUsedBestPossible = false;
			try
			{
				wf = m_preExistingAnalyses[iAnnClosest].Wordform;

				int wsTxtWord = TsStringUtils.GetWsAtOffset(tssTxtWord, 0);
				tssWordAnn = wf.Form.get_String(wsTxtWord);

				// Did we find it at the exact expected place in the sequence?
				if (ianalysis != iAnnClosest)
				{
					// No, we didn't. Apply various heuristics to see whether we should use it.

					// Enhance: If the character offsets in this text paragraph overlap
					// the user probably deleted a paragraph break.
					// in that case we could be smarter about looking  for matches at the end of the paragraph
					// rather than at the beginning.

					// Verify the closest is within reasonable bounds.
					if (Math.Abs(ianalysis - iAnnClosest) > 100)
					{
						// someone may have significantly altered the text,
						// or it belongs to a wordform later in the text.
						// Either case, safe not to guess a match.
						tssWordAnn = tssTxtWord;
						return false;
					}

					if (tssWordAnn.Length == 0)
					{
						// There are certain cases (e.g. during import) where
						// the paragraph text will not have a default vernacular writing system for the current
						// wordform. So, instead of trying to find the best vernacular form (again), we'll
						// just assume that it matches some form of the tssWordTxt in this context.
						tssWordAnn = tssTxtWord;
					}

					// JohnT: don't see any equivalent for this optimization, we don't know where in the
					// text the closest occurrence used to be.
					//// see if we can match on the target offset, so we don't have to search more through the text.
					//if (m_paragraphTextScanner.MatchesWordInText(tssWordAnn, ichMinAnnClosest))
					//{
					//    tssWordAnn = tssTxtWord;
					//    return false;
					//}
					// Otherwise, verify there isn't another place in the text closer to the
					// offsets for the annotation's wordform.
					if (ianalysis < iAnnClosest)
					{
						int intermediateWordCount = m_paragraphTextScanner.NextOccurrenceOfWord(tssWordAnn, ichLim,
																								ichMin +
																								tssWordAnn.Length);
						if (intermediateWordCount != -1 && intermediateWordCount < iAnnClosest - ianalysis)
						{
							// we found a closer possible occurrence.
							tssWordAnn = tssTxtWord;
							return false;
						}
					}
					else
					{
						// the match is earlier in the text than expected; it will certainly be closer
						// to this occurrence than any later one.
					}
				}
				else
				{
					// The same wordform occurred at the same position in the old analysis of the paragraph.
					int ichLimAnnClosest = m_preExistingAnalyses[iAnnClosest].GetForm(m_paraWs).Length + ichMin;
					if (ichLimAnnClosest > ichLim)
					{
						// annotation must be for a phrase. See if it matches our text before using the id, otherwise we can crash (LT-6244).
						if (!m_paragraphTextScanner.MatchesWordInText(tssWordAnn, ichMin))
						{
							// annotation didn't actually match our text, so return.
							tssWordAnn = tssTxtWord;
							return false;
						}
					}
					else
					{
						// verify tssWordAnn is actual compatible with our spot in the text.
						if (!m_paragraphTextScanner.MatchesWord(tssWordAnn, tssTxtWord))
						{
							// perhaps they changed the writing system on this word?
							// in any case, we don't want to use it.
							tssWordAnn = tssTxtWord;
							return false;
						}
					}
				}
				// must have found an annotation we can reuse.
				fUsedBestPossible = true;
				analysis = m_preExistingAnalyses[iAnnClosest];
				return true;
			}
			finally
			{
				// remove any annotation possibilities that no longer make sense.
				if (!SegmentFormCollectionMode)
				{
					int iBestPossible = possibleIndices.IndexOf(iAnnClosest);
					int cRemove = iBestPossible + (fUsedBestPossible ? 1 : 0);
					if (cRemove > 0)
						(possibleIndices as List<int>).RemoveRange(0, cRemove);
					if (possibleIndices.Count == 0)
					{
						// remove its key from the Dictionary.
						m_wordformAnnotationPossibilities.Remove(key);
					}
				}
			}
		}
Ejemplo n.º 59
0
		// Make sure we have the right list of occurrences for the specified analysis.
		// If we've ever been asked for it, send a PropChanged notification to indicate that it has changed.
		public void UpdateAnalysisOccurrences(IAnalysis obj, bool includeChildren)
		{
			int hvo = obj.Hvo;
			int[] values;
			if (!m_values.TryGetValue(hvo, out values))
				return; // never loaded it, don't unless we get asked for it.
			m_values.Remove(hvo); // get rid of dubious value.
			int[] newvalues = GetAnalysisOccurrences(hvo, includeChildren);
			int flidExact, flidAll;
			switch (obj.ClassID)
			{
				case WfiWordformTags.kClassId:
					flidExact = kflidWfExactOccurrences;
					flidAll = kflidWfOccurrences;
					break;
				case WfiAnalysisTags.kClassId:
					flidExact = kflidWaExactOccurrences;
					flidAll = kflidWaOccurrences;
					break;
				case WfiGlossTags.kClassId:
					flidExact = kflidWgExactOccurrences;
					flidAll = kflidWgOccurrences;
					break;
				default:
					return;
			}
			if (includeChildren)
				SendPropChanged(hvo, flidAll, 0, newvalues.Length, values.Length);
			else
				SendPropChanged(hvo, flidExact, 0, newvalues.Length, values.Length);
			SendPropChanged(hvo, kflidOccurrenceCount, 0, 0, 0);
		}
Ejemplo n.º 60
0
			/// <summary>
			///
			/// </summary>
			/// <param name="expectedSegForm"></param>
			/// <param name="actualSegForm"></param>
			/// <param name="segFormContext"></param>
			virtual protected void ValidateSegForms(object expectedSegForm, IAnalysis actualSegForm, string segFormContext)
			{
				return;
			}