idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
12,800
private Set < String > getSet ( boolean isInflected ) { Set < String > set = new HashSet < > ( ) ; for ( PatternToken patternToken : patternTokens ) { boolean acceptInflectionValue = isInflected ? patternToken . isInflected ( ) : ! patternToken . isInflected ( ) ; if ( acceptInflectionValue && ! patternToken . getNegation ( ) && ! patternToken . isRegularExpression ( ) && ! patternToken . isReferenceElement ( ) && patternToken . getMinOccurrence ( ) > 0 ) { String str = patternToken . getString ( ) ; if ( ! StringTools . isEmpty ( str ) ) { set . add ( str . toLowerCase ( ) ) ; } } } return Collections . unmodifiableSet ( set ) ; }
tokens that just refer to a word - no regex and optionally no inflection etc .
12,801
public Query buildRelaxedQuery ( AbstractPatternRule rule ) throws UnsupportedPatternRuleException { BooleanQuery . Builder builder = new BooleanQuery . Builder ( ) ; for ( PatternToken patternToken : rule . getPatternTokens ( ) ) { try { BooleanClause clause = makeQuery ( patternToken ) ; builder . add ( clause ) ; } catch ( UnsupportedPatternRuleException e ) { } catch ( Exception e ) { throw new RuntimeException ( "Could not create query for rule " + rule . getId ( ) , e ) ; } } BooleanQuery query = builder . build ( ) ; if ( query . clauses ( ) . isEmpty ( ) ) { throw new UnsupportedPatternRuleException ( "No items found in rule that can be used to build a search query: " + rule ) ; } return query ; }
Iterate over all elements ignore those not supported add the other ones to a BooleanQuery .
12,802
List < Language > getLanguages ( ) throws IllegalAccessException , InstantiationException { List < Language > languages = new ArrayList < > ( ) ; for ( File ruleFile : ruleFiles ) { if ( ruleFile != null ) { Language newLanguage = LanguageBuilder . makeAdditionalLanguage ( ruleFile ) ; languages . add ( newLanguage ) ; } } return languages ; }
Return all external Languages .
12,803
public List < RuleMatchApplication > applySuggestionsToOriginalText ( RuleMatch match ) { List < String > replacements = new ArrayList < > ( match . getSuggestedReplacements ( ) ) ; boolean hasRealReplacements = replacements . size ( ) > 0 ; if ( ! hasRealReplacements ) { String plainText = textMapping . getPlainText ( ) ; replacements . add ( plainText . substring ( match . getFromPos ( ) , match . getToPos ( ) ) ) ; } List < RuleMatchApplication > ruleMatchApplications = new ArrayList < > ( ) ; Location fromPosLocation = textMapping . getOriginalTextPositionFor ( match . getFromPos ( ) + 1 ) ; Location toPosLocation = textMapping . getOriginalTextPositionFor ( match . getToPos ( ) + 1 ) ; int fromPos = LocationHelper . absolutePositionFor ( fromPosLocation , originalText ) ; int toPos = LocationHelper . absolutePositionFor ( toPosLocation , originalText ) ; for ( String replacement : replacements ) { String errorText = textMapping . getPlainText ( ) . substring ( match . getFromPos ( ) , match . getToPos ( ) ) ; int contextFrom = findNextWhitespaceToTheLeft ( originalText , fromPos ) ; int contextTo = findNextWhitespaceToTheRight ( originalText , toPos ) ; String context = originalText . substring ( contextFrom , contextTo ) ; String text = originalText . substring ( 0 , contextFrom ) + errorMarker . getStartMarker ( ) + context + errorMarker . getEndMarker ( ) + originalText . substring ( contextTo ) ; String newContext ; if ( StringUtils . countMatches ( context , errorText ) == 1 ) { newContext = context . replace ( errorText , replacement ) ; } else { newContext = context ; hasRealReplacements = false ; } String newText = originalText . substring ( 0 , contextFrom ) + errorMarker . getStartMarker ( ) + newContext + errorMarker . getEndMarker ( ) + originalText . substring ( contextTo ) ; RuleMatchApplication application ; if ( hasRealReplacements ) { application = RuleMatchApplication . forMatchWithReplacement ( match , text , newText , errorMarker ) ; } else { application = RuleMatchApplication . forMatchWithoutReplacement ( match , text , newText , errorMarker ) ; } ruleMatchApplications . add ( application ) ; } return ruleMatchApplications ; }
Applies the suggestions from the rule to the original text . For rules that have no suggestion a pseudo - correction is generated that contains the same text as before .
12,804
String [ ] tokenize ( String sentence ) { TokenizerME tokenizer = new TokenizerME ( tokenModel ) ; String cleanString = sentence . replace ( '’', ' ''); return tokenizer . tokenize ( cleanString ) ; }
non - private for test cases
12,805
public void checkSimpleXMLString ( String xml ) throws IOException { Pattern pattern = Pattern . compile ( "(<error.*?/>)" , Pattern . DOTALL | Pattern . MULTILINE ) ; Matcher matcher = pattern . matcher ( xml ) ; int pos = 0 ; while ( matcher . find ( pos ) ) { String errorElement = matcher . group ( ) ; pos = matcher . end ( ) ; if ( errorElement . contains ( "\n" ) || errorElement . contains ( "\r" ) ) { throw new IOException ( "<error ...> may not contain line breaks" ) ; } char beforeError = xml . charAt ( matcher . start ( ) - 1 ) ; if ( beforeError != '\n' && beforeError != '\r' ) { throw new IOException ( "Each <error ...> must start on a new line" ) ; } } }
Check some limits of our simplified XML output .
12,806
public void validateXMLString ( String xml , String dtdFile , String docType ) throws SAXException , IOException , ParserConfigurationException { validateInternal ( xml , dtdFile , docType ) ; }
Validate XML with the given DTD . Throws exception on error .
12,807
public void validateWithDtd ( String filename , String dtdPath , String docType ) throws IOException { try ( InputStream xmlStream = this . getClass ( ) . getResourceAsStream ( filename ) ) { if ( xmlStream == null ) { throw new IOException ( "Not found in classpath: " + filename ) ; } try { String xml = StringTools . readStream ( xmlStream , "utf-8" ) ; validateInternal ( xml , dtdPath , docType ) ; } catch ( Exception e ) { throw new IOException ( "Cannot load or parse '" + filename + "'" , e ) ; } } }
Validate XML file in classpath with the given DTD . Throws exception on error .
12,808
public void activateNeuralNetworkRules ( File modelDir ) throws IOException { ResourceBundle messages = getMessageBundle ( language ) ; List < Rule > rules = language . getRelevantNeuralNetworkModels ( messages , modelDir ) ; userRules . addAll ( rules ) ; }
Activate rules that depend on pretrained neural network models .
12,809
public void activateLanguageModelRules ( File indexDir ) throws IOException { LanguageModel languageModel = language . getLanguageModel ( indexDir ) ; if ( languageModel != null ) { ResourceBundle messages = getMessageBundle ( language ) ; List < Rule > rules = language . getRelevantLanguageModelRules ( messages , languageModel ) ; userRules . addAll ( rules ) ; updateOptionalLanguageModelRules ( languageModel ) ; } }
Activate rules that depend on a language model . The language model currently consists of Lucene indexes with ngram occurrence counts .
12,810
public void activateWord2VecModelRules ( File indexDir ) throws IOException { Word2VecModel word2vecModel = language . getWord2VecModel ( indexDir ) ; if ( word2vecModel != null ) { ResourceBundle messages = getMessageBundle ( language ) ; List < Rule > rules = language . getRelevantWord2VecModelRules ( messages , word2vecModel ) ; userRules . addAll ( rules ) ; } }
Activate rules that depend on a word2vec language model .
12,811
public RuleMatch adjustRuleMatchPos ( RuleMatch match , int charCount , int columnCount , int lineCount , String sentence , AnnotatedText annotatedText ) { int fromPos = match . getFromPos ( ) + charCount ; int toPos = match . getToPos ( ) + charCount ; if ( annotatedText != null ) { fromPos = annotatedText . getOriginalTextPositionFor ( fromPos ) ; toPos = annotatedText . getOriginalTextPositionFor ( toPos - 1 ) + 1 ; } RuleMatch thisMatch = new RuleMatch ( match ) ; thisMatch . setOffsetPosition ( fromPos , toPos ) ; List < SuggestedReplacement > replacements = match . getSuggestedReplacementObjects ( ) ; thisMatch . setSuggestedReplacementObjects ( extendSuggestions ( replacements ) ) ; String sentencePartToError = sentence . substring ( 0 , match . getFromPos ( ) ) ; String sentencePartToEndOfError = sentence . substring ( 0 , match . getToPos ( ) ) ; int lastLineBreakPos = sentencePartToError . lastIndexOf ( '\n' ) ; int column ; int endColumn ; if ( lastLineBreakPos == - 1 ) { column = sentencePartToError . length ( ) + columnCount ; } else { column = sentencePartToError . length ( ) - lastLineBreakPos ; } int lastLineBreakPosInError = sentencePartToEndOfError . lastIndexOf ( '\n' ) ; if ( lastLineBreakPosInError == - 1 ) { endColumn = sentencePartToEndOfError . length ( ) + columnCount ; } else { endColumn = sentencePartToEndOfError . length ( ) - lastLineBreakPosInError ; } int lineBreaksToError = countLineBreaks ( sentencePartToError ) ; int lineBreaksToEndOfError = countLineBreaks ( sentencePartToEndOfError ) ; thisMatch . setLine ( lineCount + lineBreaksToError ) ; thisMatch . setEndLine ( lineCount + lineBreaksToEndOfError ) ; thisMatch . setColumn ( column ) ; thisMatch . setEndColumn ( endColumn ) ; return thisMatch ; }
Change RuleMatch positions so they are relative to the complete text not just to the sentence .
12,812
static int countLineBreaks ( String s ) { int pos = - 1 ; int count = 0 ; while ( true ) { int nextPos = s . indexOf ( '\n' , pos + 1 ) ; if ( nextPos == - 1 ) { break ; } pos = nextPos ; count ++ ; } return count ; }
non - private only for test case
12,813
public Map < CategoryId , Category > getCategories ( ) { Map < CategoryId , Category > map = new HashMap < > ( ) ; for ( Rule rule : getAllRules ( ) ) { map . put ( rule . getCategory ( ) . getId ( ) , rule . getCategory ( ) ) ; } return map ; }
Get all rule categories for the current language .
12,814
public List < Rule > getAllActiveOfficeRules ( ) { List < Rule > rules = new ArrayList < > ( ) ; List < Rule > rulesActive = new ArrayList < > ( ) ; rules . addAll ( builtinRules ) ; rules . addAll ( userRules ) ; for ( Rule rule : rules ) { if ( ! ignoreRule ( rule ) && ! rule . isOfficeDefaultOff ( ) ) { rulesActive . add ( rule ) ; } else if ( rule . isOfficeDefaultOn ( ) ) { rulesActive . add ( rule ) ; enableRule ( rule . getId ( ) ) ; } else if ( ! ignoreRule ( rule ) && rule . isOfficeDefaultOff ( ) ) { disableRule ( rule . getId ( ) ) ; } } return rulesActive ; }
Works like getAllActiveRules but overrides defaults by officeefaults
12,815
private boolean matchPreservesCase ( List < Match > suggestionMatches , String msg ) { if ( suggestionMatches != null && ! suggestionMatches . isEmpty ( ) ) { int sugStart = msg . indexOf ( SUGGESTION_START_TAG ) + SUGGESTION_START_TAG . length ( ) ; for ( Match sMatch : suggestionMatches ) { if ( ! sMatch . isInMessageOnly ( ) && sMatch . convertsCase ( ) && msg . charAt ( sugStart ) == '\\' ) { return false ; } } } return true ; }
Checks if the suggestion starts with a match that is supposed to preserve case . If it does not perform the default conversion to uppercase .
12,816
private int translateElementNo ( int i ) { if ( ! useList || i < 0 ) { return i ; } int j = 0 ; PatternRule rule = ( PatternRule ) this . rule ; for ( int k = 0 ; k < i ; k ++ ) { j += rule . getElementNo ( ) . get ( k ) ; } return j ; }
Gets the index of the element indexed by i adding any offsets because of the phrases in the rule .
12,817
private static String [ ] combineLists ( String [ ] [ ] input , String [ ] output , int r , Language lang ) { List < String > outputList = new ArrayList < > ( ) ; if ( r == input . length ) { StringBuilder sb = new StringBuilder ( ) ; for ( int k = 0 ; k < output . length ; k ++ ) { sb . append ( output [ k ] ) ; if ( k < output . length - 1 ) { sb . append ( StringTools . addSpace ( output [ k + 1 ] , lang ) ) ; } } outputList . add ( sb . toString ( ) ) ; } else { for ( int c = 0 ; c < input [ r ] . length ; c ++ ) { output [ r ] = input [ r ] [ c ] ; String [ ] sList = combineLists ( input , output , r + 1 , lang ) ; outputList . addAll ( Arrays . asList ( sList ) ) ; } } return outputList . toArray ( new String [ 0 ] ) ; }
Creates a Cartesian product of the arrays stored in the input array .
12,818
private Language getLanguageForLocalizedName ( String languageName ) { for ( Language element : Languages . get ( ) ) { if ( languageName . equals ( element . getTranslatedName ( messages ) ) ) { return element ; } } return null ; }
Get the Language object for the given localized language name .
12,819
private XLinguServiceManager GetLinguSvcMgr ( XComponentContext xContext ) { try { XMultiComponentFactory xMCF = UnoRuntime . queryInterface ( XMultiComponentFactory . class , xContext . getServiceManager ( ) ) ; if ( xMCF == null ) { printText ( "XMultiComponentFactory == null" ) ; return null ; } XPropertySet props = UnoRuntime . queryInterface ( XPropertySet . class , xMCF ) ; if ( props == null ) { printText ( "XPropertySet == null" ) ; return null ; } Object defaultContext = props . getPropertyValue ( "DefaultContext" ) ; XComponentContext xComponentContext = UnoRuntime . queryInterface ( XComponentContext . class , defaultContext ) ; if ( xComponentContext == null ) { printText ( "XComponentContext == null" ) ; return null ; } Object o = xMCF . createInstanceWithContext ( "com.sun.star.linguistic2.LinguServiceManager" , xComponentContext ) ; XLinguServiceManager mxLinguSvcMgr = UnoRuntime . queryInterface ( XLinguServiceManager . class , o ) ; if ( mxLinguSvcMgr == null ) { printText ( "XLinguServiceManager2 == null" ) ; return null ; } return mxLinguSvcMgr ; } catch ( Throwable t ) { printMessage ( t ) ; } return null ; }
Get the LinguServiceManager to be used for example to access spell checker thesaurus and hyphenator
12,820
private XThesaurus GetThesaurus ( XLinguServiceManager mxLinguSvcMgr ) { try { if ( mxLinguSvcMgr != null ) { return mxLinguSvcMgr . getThesaurus ( ) ; } } catch ( Throwable t ) { printMessage ( t ) ; } return null ; }
Get the Thesaurus to be used .
12,821
private XHyphenator GetHyphenator ( XLinguServiceManager mxLinguSvcMgr ) { try { if ( mxLinguSvcMgr != null ) { return mxLinguSvcMgr . getHyphenator ( ) ; } } catch ( Throwable t ) { printMessage ( t ) ; } return null ; }
Get the Hyphenator to be used .
12,822
private XSpellChecker GetSpellChecker ( XLinguServiceManager mxLinguSvcMgr ) { try { if ( mxLinguSvcMgr != null ) { return mxLinguSvcMgr . getSpellChecker ( ) ; } } catch ( Throwable t ) { printMessage ( t ) ; } return null ; }
Get the SpellChecker to be used .
12,823
public List < String > getSynonyms ( String word , Language lang ) { return getSynonyms ( word , getLocale ( lang ) ) ; }
Get all synonyms of a word as list of strings .
12,824
public boolean isCorrectSpell ( String word , Language lang ) { return isCorrectSpell ( word , getLocale ( lang ) ) ; }
Returns true if the spell check is positive
12,825
public int getNumberOfSyllables ( String word , Language lang ) { return getNumberOfSyllables ( word , getLocale ( lang ) ) ; }
Returns the number of syllable of a word Returns - 1 if the word was not found or anything goes wrong
12,826
public boolean isMisspelled ( String word ) { for ( MorfologikSpeller speller : spellers ) { if ( ! speller . isMisspelled ( word ) ) { return false ; } } return true ; }
Accept the word if at least one of the dictionaries accepts it as not misspelled .
12,827
public final void setToken ( AnalyzedTokenReadings [ ] tokens , int index , int next ) { int idx = index ; if ( index >= tokens . length ) { idx = tokens . length - 1 ; } setToken ( tokens [ idx ] ) ; IncludeRange includeSkipped = match . getIncludeSkipped ( ) ; if ( next > 1 && includeSkipped != IncludeRange . NONE ) { StringBuilder sb = new StringBuilder ( ) ; if ( includeSkipped == IncludeRange . FOLLOWING ) { formattedToken = null ; } for ( int k = index + 1 ; k < index + next ; k ++ ) { if ( tokens [ k ] . isWhitespaceBefore ( ) && ! ( k == index + 1 && includeSkipped == IncludeRange . FOLLOWING ) ) { sb . append ( ' ' ) ; } sb . append ( tokens [ k ] . getToken ( ) ) ; } skippedTokens = sb . toString ( ) ; } else { skippedTokens = "" ; } }
Sets the token to be formatted etc . and includes the support for including the skipped tokens .
12,828
public final String getTargetPosTag ( ) { String targetPosTag = match . getPosTag ( ) ; List < String > posTags = new ArrayList < > ( ) ; Pattern pPosRegexMatch = match . getPosRegexMatch ( ) ; String posTagReplace = match . getPosTagReplace ( ) ; if ( match . isStaticLemma ( ) ) { for ( AnalyzedToken analyzedToken : matchedToken ) { String tst = analyzedToken . getPOSTag ( ) ; if ( tst != null && pPosRegexMatch . matcher ( tst ) . matches ( ) ) { targetPosTag = analyzedToken . getPOSTag ( ) ; posTags . add ( targetPosTag ) ; } } if ( pPosRegexMatch != null && posTagReplace != null && ! posTags . isEmpty ( ) ) { targetPosTag = pPosRegexMatch . matcher ( targetPosTag ) . replaceAll ( posTagReplace ) ; } } else { for ( AnalyzedToken analyzedToken : formattedToken ) { String tst = analyzedToken . getPOSTag ( ) ; if ( tst != null && pPosRegexMatch . matcher ( tst ) . matches ( ) ) { targetPosTag = analyzedToken . getPOSTag ( ) ; posTags . add ( targetPosTag ) ; } } if ( pPosRegexMatch != null && posTagReplace != null ) { if ( posTags . isEmpty ( ) ) { posTags . add ( targetPosTag ) ; } StringBuilder sb = new StringBuilder ( ) ; int posTagLen = posTags . size ( ) ; int l = 0 ; for ( String lPosTag : posTags ) { l ++ ; lPosTag = pPosRegexMatch . matcher ( lPosTag ) . replaceAll ( posTagReplace ) ; if ( match . setsPos ( ) ) { lPosTag = synthesizer . getPosTagCorrection ( lPosTag ) ; } sb . append ( lPosTag ) ; if ( l < posTagLen ) { sb . append ( '|' ) ; } } targetPosTag = sb . toString ( ) ; } } return targetPosTag ; }
on the other hand many POS tags = too many suggestions?
12,829
final String toTokenString ( ) throws IOException { String [ ] stringToFormat = toFinalString ( null ) ; return String . join ( "|" , Arrays . asList ( stringToFormat ) ) ; }
Method for getting the formatted match as a single string . In case of multiple matches it joins them using a regular expression operator | .
12,830
ProofreadingResult getCheckResults ( String paraText , Locale locale , ProofreadingResult paRes , int [ ] footnotePositions , boolean isParallelThread , JLanguageTool langTool ) { try { SingleProofreadingError [ ] sErrors = null ; paraNum = getParaPos ( paraText , isParallelThread ) ; if ( numParasToCheck != 0 && paraNum >= 0 && doResetCheck ) { sErrors = sentencesCache . getMatches ( paraNum , paRes . nStartOfSentencePosition ) ; if ( sErrors != null ) { paRes . nStartOfNextSentencePosition = sentencesCache . getNextSentencePosition ( paraNum , paRes . nStartOfSentencePosition ) ; paRes . nBehindEndOfSentencePosition = paRes . nStartOfNextSentencePosition ; } } if ( debugMode > 1 ) { MessageHandler . printToLogFile ( "... Check Sentence: numCurPara: " + paraNum + "; startPos: " + paRes . nStartOfSentencePosition + "; Paragraph: " + paraText + ", sErrors: " + ( sErrors == null ? 0 : sErrors . length ) + logLineBreak ) ; } if ( sErrors == null ) { SentenceFromPara sfp = new SentenceFromPara ( paraText , paRes . nStartOfSentencePosition , langTool ) ; String sentence = sfp . getSentence ( ) ; paRes . nStartOfSentencePosition = sfp . getPosition ( ) ; paRes . nStartOfNextSentencePosition = sfp . getPosition ( ) + sentence . length ( ) ; paRes . nBehindEndOfSentencePosition = paRes . nStartOfNextSentencePosition ; sErrors = checkSentence ( sentence , paRes . nStartOfSentencePosition , paRes . nStartOfNextSentencePosition , paraNum , footnotePositions , isParallelThread , langTool ) ; } SingleProofreadingError [ ] pErrors = checkParaRules ( paraText , paraNum , paRes . nStartOfSentencePosition , paRes . nStartOfNextSentencePosition , isParallelThread , langTool ) ; paRes . aErrors = mergeErrors ( sErrors , pErrors ) ; if ( debugMode > 1 ) { MessageHandler . printToLogFile ( "paRes.aErrors.length: " + paRes . aErrors . length + "; docID: " + docID + logLineBreak ) ; } textIsChanged = false ; } catch ( Throwable t ) { MessageHandler . showError ( t ) ; } return paRes ; }
get the result for a check of a single document
12,831
void setConfigValues ( Configuration config ) { this . config = config ; numParasToCheck = config . getNumParasToCheck ( ) ; defaultParaCheck = numParasToCheck * PARA_CHECK_FACTOR ; doResetCheck = config . isResetCheck ( ) ; }
set values set by configuration dialog
12,832
void optimizeReset ( ) { FlatParagraphTools flatPara = new FlatParagraphTools ( xContext ) ; flatPara . markFlatParasAsChecked ( resetFrom + divNum , resetTo + divNum , isChecked ) ; resetCheck = false ; }
Reset only changed paragraphs
12,833
public void loadIsChecked ( ) { FlatParagraphTools flatPara = new FlatParagraphTools ( xContext ) ; isChecked = flatPara . isChecked ( ) ; if ( debugMode > 0 ) { int nChecked = 0 ; for ( boolean bChecked : isChecked ) { if ( bChecked ) { nChecked ++ ; } } MessageHandler . printToLogFile ( "Checked parapraphs: docID: " + docID + ", Number of Paragraphs: " + isChecked . size ( ) + ", Checked: " + nChecked + logLineBreak ) ; } }
load checked status of all paragraphs
12,834
private String getDocAsString ( int numCurPara ) { if ( numCurPara < 0 || allParas == null || allParas . size ( ) < numCurPara - 1 ) { return "" ; } int startPos ; int endPos ; if ( numParasToCheck < 1 ) { startPos = 0 ; endPos = allParas . size ( ) ; } else { startPos = numCurPara - numParasToCheck ; if ( textIsChanged && doResetCheck ) { startPos -= numParasToCheck ; } if ( startPos < 0 ) { startPos = 0 ; } endPos = numCurPara + 1 + numParasToCheck ; if ( ! textIsChanged ) { endPos += defaultParaCheck ; } else if ( doResetCheck ) { endPos += numParasToCheck ; } if ( endPos > allParas . size ( ) ) { endPos = allParas . size ( ) ; } } StringBuilder docText = new StringBuilder ( fixLinebreak ( allParas . get ( startPos ) ) ) ; for ( int i = startPos + 1 ; i < endPos ; i ++ ) { docText . append ( END_OF_PARAGRAPH ) . append ( fixLinebreak ( allParas . get ( i ) ) ) ; } return docText . toString ( ) ; }
Gives Back the full Text as String
12,835
private int getStartOfParagraph ( int nPara , int checkedPara ) { if ( allParas != null && nPara >= 0 && nPara < allParas . size ( ) ) { int startPos ; if ( numParasToCheck < 1 ) { startPos = 0 ; } else { startPos = checkedPara - numParasToCheck ; if ( textIsChanged && doResetCheck ) { startPos -= numParasToCheck ; } if ( startPos < 0 ) startPos = 0 ; } int pos = 0 ; for ( int i = startPos ; i < nPara ; i ++ ) { pos += allParas . get ( i ) . length ( ) + 1 ; } return pos ; } return - 1 ; }
Gives Back the StartPosition of Paragraph
12,836
public Map < String , List < String > > loadWords ( String path ) { InputStream stream = JLanguageTool . getDataBroker ( ) . getFromRulesDirAsStream ( path ) ; Map < String , List < String > > map = new HashMap < > ( ) ; try ( Scanner scanner = new Scanner ( stream , "utf-8" ) ) { while ( scanner . hasNextLine ( ) ) { String line = scanner . nextLine ( ) ; if ( line . isEmpty ( ) || line . charAt ( 0 ) == '#' ) { continue ; } String [ ] parts = line . split ( "=" ) ; if ( parts . length != 2 ) { throw new RuntimeException ( "Could not load simple replacement data from: " + path + ". " + "Error in line '" + line + "', expected format 'word=replacement'" ) ; } String [ ] wrongForms = parts [ 0 ] . split ( "\\|" ) ; List < String > replacements = Arrays . asList ( parts [ 1 ] . split ( "\\|" ) ) ; for ( String wrongForm : wrongForms ) { map . put ( wrongForm , replacements ) ; } } } return Collections . unmodifiableMap ( map ) ; }
Load replacement rules from a utf - 8 file in the classpath .
12,837
private boolean matchLemmaRegexp ( AnalyzedTokenReadings aToken , Pattern pattern ) { boolean matches = false ; for ( AnalyzedToken analyzedToken : aToken ) { final String posTag = analyzedToken . getLemma ( ) ; if ( posTag != null ) { final Matcher m = pattern . matcher ( posTag ) ; if ( m . matches ( ) ) { matches = true ; break ; } } } return matches ; }
Match lemma with regular expression
12,838
private boolean matchLemmaList ( AnalyzedTokenReadings aToken , List < String > list ) { boolean matches = false ; for ( AnalyzedToken analyzedToken : aToken ) { if ( list . contains ( analyzedToken . getLemma ( ) ) ) { matches = true ; break ; } } return matches ; }
Match lemma with String list
12,839
private boolean matchRegexp ( String s , Pattern pattern ) { final Matcher m = pattern . matcher ( s ) ; return m . matches ( ) ; }
Match String with regular expression
12,840
private boolean isTherePronoun ( final AnalyzedTokenReadings [ ] tokens , int i , Pattern lemma , Pattern postag ) { int j = 1 ; boolean keepCounting = true ; while ( i - j > 0 && keepCounting ) { if ( matchPostagRegexp ( tokens [ i - j ] , postag ) && matchLemmaRegexp ( tokens [ i - j ] , lemma ) ) return true ; keepCounting = matchPostagRegexp ( tokens [ i - j ] , PREP_VERB_PRONOM ) ; j ++ ; } j = 1 ; keepCounting = true ; while ( i + j < tokens . length && keepCounting ) { if ( matchPostagRegexp ( tokens [ i + j ] , postag ) && matchLemmaRegexp ( tokens [ i + j ] , lemma ) ) return true ; keepCounting = matchPostagRegexp ( tokens [ i + j ] , PREP_VERB_PRONOM ) ; j ++ ; } return false ; }
Checks if there is a desired pronoun near the verb
12,841
public void stop ( ) { if ( httpHandler != null ) { httpHandler . shutdown ( ) ; } if ( server != null ) { ServerTools . print ( "Stopping server..." ) ; server . stop ( 5 ) ; isRunning = false ; ServerTools . print ( "Server stopped" ) ; } }
Stop the server . Once stopped a server cannot be used again .
12,842
private static List < ContextWords > loadContextWords ( String path ) { List < ContextWords > set = new ArrayList < > ( ) ; InputStream stream = JLanguageTool . getDataBroker ( ) . getFromRulesDirAsStream ( path ) ; try ( Scanner scanner = new Scanner ( stream , "utf-8" ) ) { while ( scanner . hasNextLine ( ) ) { String line = scanner . nextLine ( ) ; if ( line . trim ( ) . isEmpty ( ) || line . charAt ( 0 ) == '#' ) { continue ; } String [ ] column = line . split ( "\t" ) ; if ( column . length >= 6 ) { ContextWords contextWords = new ContextWords ( ) ; contextWords . setWord ( 0 , column [ 0 ] ) ; contextWords . setWord ( 1 , column [ 1 ] ) ; contextWords . matches [ 0 ] = column [ 2 ] ; contextWords . matches [ 1 ] = column [ 3 ] ; contextWords . setContext ( 0 , column [ 4 ] ) ; contextWords . setContext ( 1 , column [ 5 ] ) ; if ( column . length > 6 ) { contextWords . explanations [ 0 ] = column [ 6 ] ; if ( column . length > 7 ) { contextWords . explanations [ 1 ] = column [ 7 ] ; } } set . add ( contextWords ) ; } } } return Collections . unmodifiableList ( set ) ; }
Load words contexts and explanations .
12,843
private String getFilteredText ( String filename , String encoding , boolean xmlFiltering ) throws IOException { if ( options . isVerbose ( ) ) { lt . setOutput ( System . err ) ; } try ( InputStreamReader reader = getInputStreamReader ( filename , encoding ) ) { String fileContents = readerToString ( reader ) ; if ( xmlFiltering ) { return filterXML ( fileContents ) ; } else { return fileContents ; } } }
Loads filename and filters out XML . Note that the XML filtering can lead to incorrect positions in the list of matching rules .
12,844
public final ProofreadingResult doProofreading ( String docID , String paraText , Locale locale , int startOfSentencePos , int nSuggestedBehindEndOfSentencePosition , PropertyValue [ ] propertyValues ) { ProofreadingResult paRes = new ProofreadingResult ( ) ; paRes . nStartOfSentencePosition = startOfSentencePos ; paRes . nStartOfNextSentencePosition = nSuggestedBehindEndOfSentencePosition ; paRes . nBehindEndOfSentencePosition = paRes . nStartOfNextSentencePosition ; paRes . xProofreader = this ; paRes . aLocale = locale ; paRes . aDocumentIdentifier = docID ; paRes . aText = paraText ; paRes . aProperties = propertyValues ; try { int [ ] footnotePositions = getPropertyValues ( "FootnotePositions" , propertyValues ) ; paRes = documents . getCheckResults ( paraText , locale , paRes , footnotePositions ) ; if ( disabledRules == null ) { prepareConfig ( ) ; } if ( documents . doResetCheck ( ) ) { resetCheck ( ) ; documents . optimizeReset ( ) ; } } catch ( Throwable t ) { MessageHandler . showError ( t ) ; } return paRes ; }
Runs the grammar checker on paragraph text .
12,845
void endCompoundEdit ( ) { if ( ! compoundMode ) { throw new RuntimeException ( "not in compound mode" ) ; } ce . end ( ) ; undoManager . addEdit ( ce ) ; ce = null ; compoundMode = false ; }
Notify manager to stop merging undoable edits .
12,846
public static synchronized Hunspell getInstance ( String libDir ) throws UnsatisfiedLinkError , UnsupportedOperationException { if ( hunspell != null ) { return hunspell ; } hunspell = new Hunspell ( libDir ) ; return hunspell ; }
The instance of the HunspellManager looks for the native lib in the directory specified .
12,847
public static String libName ( ) throws UnsupportedOperationException { String os = System . getProperty ( "os.name" ) . toLowerCase ( ) ; if ( os . startsWith ( "windows" ) ) { return libNameBare ( ) + ".dll" ; } else if ( os . startsWith ( "mac os x" ) ) { return libNameBare ( ) + ".jnilib" ; } else { return "lib" + libNameBare ( ) + ".so" ; } }
Calculate the filename of the native hunspell lib . The files have completely different names to allow them to live in the same directory and avoid confusion .
12,848
public Dictionary getDictionary ( String baseFileName ) throws IOException { if ( map . containsKey ( baseFileName ) ) { return map . get ( baseFileName ) ; } else { Dictionary d = new Dictionary ( baseFileName ) ; map . put ( baseFileName , d ) ; return d ; } }
Gets an instance of the dictionary .
12,849
protected String formatPosTag ( String posTag , int position , int multiwordLength ) { return tagFormat != null ? String . format ( tagFormat , posTag ) : posTag ; }
Override this method if you want format POS tag differently
12,850
private void addTokens ( List < AnalyzedToken > taggedTokens , List < AnalyzedToken > l ) { if ( taggedTokens != null ) { for ( AnalyzedToken at : taggedTokens ) { l . add ( at ) ; } } }
please do not make protected this breaks other languages
12,851
static File openFileDialog ( Frame frame , FileFilter fileFilter , File initialDir ) { return openFileDialog ( frame , fileFilter , initialDir , JFileChooser . FILES_ONLY ) ; }
Show a file chooser dialog in a specified directory
12,852
static File openDirectoryDialog ( Frame frame , File initialDir ) { return openFileDialog ( frame , null , initialDir , JFileChooser . DIRECTORIES_ONLY ) ; }
Show a directory chooser dialog starting with a specified directory
12,853
public static char getMnemonic ( String label ) { int mnemonicPos = label . indexOf ( '&' ) ; while ( mnemonicPos != - 1 && mnemonicPos == label . indexOf ( "&&" ) && mnemonicPos < label . length ( ) ) { mnemonicPos = label . indexOf ( '&' , mnemonicPos + 2 ) ; } if ( mnemonicPos == - 1 || mnemonicPos == label . length ( ) ) { return '\u0000' ; } return label . charAt ( mnemonicPos + 1 ) ; }
Returns mnemonic of a UI element .
12,854
public static void centerDialog ( JDialog dialog ) { Dimension screenSize = Toolkit . getDefaultToolkit ( ) . getScreenSize ( ) ; Dimension frameSize = dialog . getSize ( ) ; dialog . setLocation ( screenSize . width / 2 - frameSize . width / 2 , screenSize . height / 2 - frameSize . height / 2 ) ; dialog . setLocationByPlatform ( true ) ; }
Set dialog location to the center of the screen
12,855
static ResultSet executeStatement ( SQL sql ) throws SQLException { try ( SqlSession session = sqlSessionFactory . openSession ( true ) ) { try ( Connection conn = session . getConnection ( ) ) { try ( Statement stmt = conn . createStatement ( ) ) { return stmt . executeQuery ( sql . toString ( ) ) ; } } } }
For unit tests only
12,856
public boolean isExceptionMatched ( AnalyzedToken token ) { if ( exceptionSet ) { for ( PatternToken testException : exceptionList ) { if ( ! testException . exceptionValidNext ) { if ( testException . isMatched ( token ) ) { return true ; } } } } return false ; }
Checks whether an exception matches .
12,857
public boolean isAndExceptionGroupMatched ( AnalyzedToken token ) { for ( PatternToken testAndGroup : andGroupList ) { if ( testAndGroup . isExceptionMatched ( token ) ) { return true ; } } return false ; }
Enables testing multiple conditions specified by multiple element exceptions . Works as logical AND operator .
12,858
public boolean isSentenceStart ( ) { return posToken != null && JLanguageTool . SENTENCE_START_TAGNAME . equals ( posToken . posTag ) && ! posToken . negation ; }
Checks if the token is a sentence start .
12,859
private boolean isPosTokenMatched ( AnalyzedToken token ) { if ( posToken == null || posToken . posTag == null ) { return true ; } if ( token . getPOSTag ( ) == null ) { return posToken . posUnknown && token . hasNoTag ( ) ; } boolean match ; if ( posToken . regExp ) { Matcher mPos = posToken . posPattern . matcher ( token . getPOSTag ( ) ) ; match = mPos . matches ( ) ; } else { match = posToken . posTag . equals ( token . getPOSTag ( ) ) ; } if ( ! match && posToken . posUnknown ) { match = token . hasNoTag ( ) ; } return match ; }
Tests if part of speech matches a given string . Special value UNKNOWN_TAG matches null POS tags .
12,860
private boolean isStringTokenMatched ( AnalyzedToken token ) { String testToken = getTestToken ( token ) ; if ( stringRegExp ) { Matcher m = pattern . matcher ( new InterruptibleCharSequence ( testToken ) ) ; return m . matches ( ) ; } if ( caseSensitive ) { return stringToken . equals ( testToken ) ; } return stringToken . equalsIgnoreCase ( testToken ) ; }
Tests whether the string token element matches a given token .
12,861
public void setExceptionSpaceBefore ( boolean isWhite ) { if ( previousExceptionList != null && exceptionValidPrevious ) { previousExceptionList . get ( previousExceptionList . size ( ) - 1 ) . setWhitespaceBefore ( isWhite ) ; } else { if ( exceptionList != null ) { exceptionList . get ( exceptionList . size ( ) - 1 ) . setWhitespaceBefore ( isWhite ) ; } } }
Sets the attribute on the exception that determines matching of patterns that depends on whether there was a space before the token matching the exception or not . The same procedure is used for tokens that are valid for previous or current tokens .
12,862
public final AnalyzedSentence replace ( AnalyzedSentence sentence ) throws IOException { DisambiguationPatternRuleReplacer replacer = new DisambiguationPatternRuleReplacer ( this ) ; return replacer . replace ( sentence ) ; }
Performs disambiguation on the source sentence .
12,863
private static boolean isRemovableWhite ( AnalyzedTokenReadings token ) { return ( token . isWhitespace ( ) || StringTools . isNonBreakingWhitespace ( token . getToken ( ) ) ) && ! token . isLinebreak ( ) && ! token . getToken ( ) . equals ( "\t" ) && ! token . getToken ( ) . equals ( "\u200B" ) ; }
Removable white space are not linebreaks tabs functions or footnotes
12,864
private String getRomanNumber ( int num ) { String roman = "" ; int N = num ; for ( int i = 0 ; i < numbers . length ; i ++ ) { while ( N >= numbers [ i ] ) { roman += letters [ i ] ; N -= numbers [ i ] ; } } return roman ; }
Gets the Roman notation for numbers .
12,865
void setSelectedFont ( Font font ) { this . selectedFont = font ; fontNameList . setSelectedValue ( font . getFamily ( ) , true ) ; fontStyleList . setSelectedValue ( getStyle ( font ) , true ) ; fontSizeList . setSelectedValue ( font . getSize ( ) , true ) ; }
Sets the current font of the font chooser to the specified font .
12,866
public List < String > getSynonyms ( AnalyzedTokenReadings token ) { List < String > synonyms = new ArrayList < String > ( ) ; if ( linguServices == null || token == null ) { return synonyms ; } List < AnalyzedToken > readings = token . getReadings ( ) ; for ( AnalyzedToken reading : readings ) { String lemma = reading . getLemma ( ) ; if ( lemma != null ) { List < String > rawSynonyms = linguServices . getSynonyms ( lemma , lang ) ; for ( String synonym : rawSynonyms ) { synonym = synonym . replaceAll ( "\\(.*\\)" , "" ) . trim ( ) ; if ( ! synonym . isEmpty ( ) && ! synonyms . contains ( synonym ) ) { synonyms . add ( synonym ) ; } } } } if ( synonyms . isEmpty ( ) ) { List < String > rawSynonyms = linguServices . getSynonyms ( token . getToken ( ) , lang ) ; for ( String synonym : rawSynonyms ) { synonym = synonym . replaceAll ( "\\(.*\\)" , "" ) . trim ( ) ; if ( ! synonym . isEmpty ( ) && ! synonyms . contains ( synonym ) ) { synonyms . add ( synonym ) ; } } } return synonyms ; }
get synonyms for a repeated word
12,867
protected void lookup ( String lemma , String posTag , List < String > results ) { synchronized ( this ) { List < WordData > wordForms = stemmer . lookup ( lemma + "|" + posTag ) ; for ( WordData wd : wordForms ) { results . add ( wd . getStem ( ) . toString ( ) ) ; } } }
Lookup the inflected forms of a lemma defined by a part - of - speech tag .
12,868
Configuration copy ( Configuration configuration ) { Configuration copy = new Configuration ( ) ; copy . restoreState ( configuration ) ; return copy ; }
Returns a copy of the given configuration .
12,869
void restoreState ( Configuration configuration ) { this . configFile = configuration . configFile ; this . language = configuration . language ; this . motherTongue = configuration . motherTongue ; this . ngramDirectory = configuration . ngramDirectory ; this . word2vecDirectory = configuration . word2vecDirectory ; this . runServer = configuration . runServer ; this . autoDetect = configuration . autoDetect ; this . taggerShowsDisambigLog = configuration . taggerShowsDisambigLog ; this . guiConfig = configuration . guiConfig ; this . fontName = configuration . fontName ; this . fontStyle = configuration . fontStyle ; this . fontSize = configuration . fontSize ; this . serverPort = configuration . serverPort ; this . numParasToCheck = configuration . numParasToCheck ; this . doResetCheck = configuration . doResetCheck ; this . noMultiReset = configuration . noMultiReset ; this . useDocLanguage = configuration . useDocLanguage ; this . lookAndFeelName = configuration . lookAndFeelName ; this . externalRuleDirectory = configuration . externalRuleDirectory ; this . disabledRuleIds . clear ( ) ; this . disabledRuleIds . addAll ( configuration . disabledRuleIds ) ; this . enabledRuleIds . clear ( ) ; this . enabledRuleIds . addAll ( configuration . enabledRuleIds ) ; this . disabledCategoryNames . clear ( ) ; this . disabledCategoryNames . addAll ( configuration . disabledCategoryNames ) ; this . enabledCategoryNames . clear ( ) ; this . enabledCategoryNames . addAll ( configuration . enabledCategoryNames ) ; this . configForOtherLanguages . clear ( ) ; for ( String key : configuration . configForOtherLanguages . keySet ( ) ) { this . configForOtherLanguages . put ( key , configuration . configForOtherLanguages . get ( key ) ) ; } this . underlineColors . clear ( ) ; for ( Map . Entry < String , Color > entry : configuration . underlineColors . entrySet ( ) ) { this . underlineColors . put ( entry . getKey ( ) , entry . getValue ( ) ) ; } this . configurableRuleValues . clear ( ) ; for ( Map . Entry < String , Integer > entry : configuration . configurableRuleValues . entrySet ( ) ) { this . configurableRuleValues . put ( entry . getKey ( ) , entry . getValue ( ) ) ; } this . styleLikeCategories . clear ( ) ; this . styleLikeCategories . addAll ( configuration . styleLikeCategories ) ; this . specialTabCategories . clear ( ) ; for ( Map . Entry < String , String > entry : configuration . specialTabCategories . entrySet ( ) ) { this . specialTabCategories . put ( entry . getKey ( ) , entry . getValue ( ) ) ; } }
Restore the state of this object from configuration .
12,870
public boolean hasPosTag ( String posTag ) { boolean found = false ; for ( AnalyzedToken reading : anTokReadings ) { if ( reading . getPOSTag ( ) != null ) { found = posTag . equals ( reading . getPOSTag ( ) ) ; if ( found ) { break ; } } } return found ; }
Checks if the token has a particular POS tag .
12,871
public boolean hasLemma ( String lemma ) { boolean found = false ; for ( AnalyzedToken reading : anTokReadings ) { if ( reading . getLemma ( ) != null ) { found = lemma . equals ( reading . getLemma ( ) ) ; if ( found ) { break ; } } } return found ; }
Checks if one of the token s readings has a particular lemma .
12,872
public boolean hasAnyLemma ( String ... lemmas ) { boolean found = false ; for ( String lemma : lemmas ) { for ( AnalyzedToken reading : anTokReadings ) { if ( reading . getLemma ( ) != null ) { found = lemma . equals ( reading . getLemma ( ) ) ; if ( found ) { return found ; } } } } return found ; }
Checks if one of the token s readings has one of the given lemmas
12,873
public boolean hasPartialPosTag ( String posTag ) { boolean found = false ; for ( AnalyzedToken reading : anTokReadings ) { if ( reading . getPOSTag ( ) != null ) { found = reading . getPOSTag ( ) . contains ( posTag ) ; if ( found ) { break ; } } } return found ; }
Checks if the token has a particular POS tag where only a part of the given POS tag needs to match .
12,874
public boolean hasPosTagStartingWith ( String posTag ) { boolean found = false ; for ( AnalyzedToken reading : anTokReadings ) { if ( reading . getPOSTag ( ) != null ) { found = reading . getPOSTag ( ) . startsWith ( posTag ) ; if ( found ) { break ; } } } return found ; }
Checks if the token has a POS tag starting with the given string .
12,875
public boolean matchesPosTagRegex ( String posTagRegex ) { Pattern pattern = Pattern . compile ( posTagRegex ) ; boolean found = false ; for ( AnalyzedToken reading : anTokReadings ) { if ( reading . getPOSTag ( ) != null ) { found = pattern . matcher ( reading . getPOSTag ( ) ) . matches ( ) ; if ( found ) { break ; } } } return found ; }
Checks if at least one of the readings matches a given POS tag regex .
12,876
public void addReading ( AnalyzedToken token ) { List < AnalyzedToken > l = new ArrayList < > ( Arrays . asList ( anTokReadings ) . subList ( 0 , anTokReadings . length - 1 ) ) ; if ( anTokReadings [ anTokReadings . length - 1 ] . getPOSTag ( ) != null ) { l . add ( anTokReadings [ anTokReadings . length - 1 ] ) ; } token . setWhitespaceBefore ( isWhitespaceBefore ) ; l . add ( token ) ; anTokReadings = l . toArray ( new AnalyzedToken [ 0 ] ) ; if ( token . getToken ( ) . length ( ) > this . token . length ( ) ) { this . token = token . getToken ( ) ; } anTokReadings [ anTokReadings . length - 1 ] . setWhitespaceBefore ( isWhitespaceBefore ) ; isParaEnd = hasPosTag ( PARAGRAPH_END_TAGNAME ) ; isSentEnd = hasPosTag ( SENTENCE_END_TAGNAME ) ; setNoRealPOStag ( ) ; hasSameLemmas = areLemmasSame ( ) ; }
Add a new reading .
12,877
public void leaveReading ( AnalyzedToken token ) { List < AnalyzedToken > l = new ArrayList < > ( ) ; AnalyzedToken tmpTok = new AnalyzedToken ( token . getToken ( ) , token . getPOSTag ( ) , token . getLemma ( ) ) ; tmpTok . setWhitespaceBefore ( isWhitespaceBefore ) ; for ( AnalyzedToken anTokReading : anTokReadings ) { if ( anTokReading . matches ( tmpTok ) ) { l . add ( anTokReading ) ; } } if ( l . isEmpty ( ) ) { l . add ( new AnalyzedToken ( this . token , null , null ) ) ; l . get ( 0 ) . setWhitespaceBefore ( isWhitespaceBefore ) ; } anTokReadings = l . toArray ( new AnalyzedToken [ 0 ] ) ; setNoRealPOStag ( ) ; hasSameLemmas = areLemmasSame ( ) ; }
Removes all readings but the one that matches the token given .
12,878
public void setParagraphEnd ( ) { if ( ! isParagraphEnd ( ) ) { AnalyzedToken paragraphEnd = new AnalyzedToken ( getToken ( ) , PARAGRAPH_END_TAGNAME , getAnalyzedToken ( 0 ) . getLemma ( ) ) ; addReading ( paragraphEnd ) ; } }
Add a reading with a paragraph end token unless this is already a paragraph end .
12,879
public void setSentEnd ( ) { if ( ! isSentenceEnd ( ) ) { AnalyzedToken sentenceEnd = new AnalyzedToken ( getToken ( ) , SENTENCE_END_TAGNAME , getAnalyzedToken ( 0 ) . getLemma ( ) ) ; addReading ( sentenceEnd ) ; } }
Add a SENT_END tag .
12,880
private boolean areLemmasSame ( ) { String previousLemma = anTokReadings [ 0 ] . getLemma ( ) ; if ( previousLemma == null ) { for ( AnalyzedToken element : anTokReadings ) { if ( element . getLemma ( ) != null ) { return false ; } } return true ; } for ( AnalyzedToken element : anTokReadings ) { if ( ! previousLemma . equals ( element . getLemma ( ) ) ) { return false ; } } return true ; }
Used to configure the internal variable for lemma equality .
12,881
protected void addUnit ( String pattern , Unit base , String symbol , double factor , boolean metric ) { Unit unit = base . multiply ( factor ) ; unitPatterns . put ( Pattern . compile ( "\\b" + NUMBER_REGEX + "\\s{0," + WHITESPACE_LIMIT + "}" + pattern + "\\b" ) , unit ) ; unitSymbols . putIfAbsent ( unit , new ArrayList < > ( ) ) ; unitSymbols . get ( unit ) . add ( symbol ) ; if ( metric && ! metricUnits . contains ( unit ) ) { metricUnits . add ( unit ) ; } }
Associate a notation with a given unit .
12,882
private List < String > getFormattedConversions ( List < Map . Entry < Unit , Double > > conversions ) { List < String > formatted = new ArrayList < > ( ) ; for ( Map . Entry < Unit , Double > equivalent : conversions ) { Unit metric = equivalent . getKey ( ) ; double converted = equivalent . getValue ( ) ; long rounded = Math . round ( converted ) ; for ( String symbol : unitSymbols . getOrDefault ( metric , new ArrayList < > ( ) ) ) { if ( formatted . size ( ) > MAX_SUGGESTIONS ) { break ; } if ( Math . abs ( converted - rounded ) / Math . abs ( converted ) < ROUNDING_DELTA && rounded != 0 ) { String formattedStr = formatRounded ( getNumberFormat ( ) . format ( rounded ) + " " + symbol ) ; if ( ! formatted . contains ( formattedStr ) ) { formatted . add ( formattedStr ) ; } } String formattedNumber = getNumberFormat ( ) . format ( converted ) ; String formattedStr = formattedNumber + " " + symbol ; if ( ! formatted . contains ( formattedStr ) && ! formattedNumber . equals ( "0" ) ) { formatted . add ( formattedStr ) ; } } } return formatted ; }
Adds different formatted variants of the given conversions up to MAX_SUGGESTIONS .
12,883
public static XDesktop getCurrentDesktop ( XComponentContext xContext ) { try { if ( xContext == null ) { return null ; } XMultiComponentFactory xMCF = UnoRuntime . queryInterface ( XMultiComponentFactory . class , xContext . getServiceManager ( ) ) ; if ( xMCF == null ) { return null ; } Object desktop = xMCF . createInstanceWithContext ( "com.sun.star.frame.Desktop" , xContext ) ; if ( desktop == null ) { return null ; } return UnoRuntime . queryInterface ( XDesktop . class , desktop ) ; } catch ( Throwable t ) { MessageHandler . printException ( t ) ; return null ; } }
Returns the current XDesktop Returns null if it fails
12,884
public static XComponent getCurrentComponent ( XComponentContext xContext ) { try { XDesktop xdesktop = getCurrentDesktop ( xContext ) ; if ( xdesktop == null ) { return null ; } else return xdesktop . getCurrentComponent ( ) ; } catch ( Throwable t ) { MessageHandler . printException ( t ) ; return null ; } }
Returns the current XComponent Returns null if it fails
12,885
public Pair < List < SuggestedReplacement > , SortedMap < String , Float > > computeFeatures ( List < String > suggestions , String word , AnalyzedSentence sentence , int startPos ) { if ( suggestions . isEmpty ( ) ) { return Pair . of ( Collections . emptyList ( ) , Collections . emptySortedMap ( ) ) ; } if ( topN <= 0 ) { topN = suggestions . size ( ) ; } List < String > topSuggestions = suggestions . subList ( 0 , Math . min ( suggestions . size ( ) , topN ) ) ; EditDistance levenstheinDistance = new EditDistance ( word , EditDistance . DistanceAlgorithm . Damerau ) ; SimilarityScore < Double > jaroWrinklerDistance = new JaroWinklerDistance ( ) ; List < Feature > features = new ArrayList < > ( topSuggestions . size ( ) ) ; for ( String candidate : topSuggestions ) { double prob1 = languageModel . getPseudoProbability ( Collections . singletonList ( candidate ) ) . getProb ( ) ; double prob3 = LanguageModelUtils . get3gramProbabilityFor ( language , languageModel , startPos , sentence , candidate ) ; long wordCount = ( ( BaseLanguageModel ) languageModel ) . getCount ( candidate ) ; int levenstheinDist = levenstheinDistance . compare ( candidate , 3 ) ; double jaroWrinklerDist = jaroWrinklerDistance . apply ( word , candidate ) ; DetailedDamerauLevenstheinDistance . Distance detailedDistance = DetailedDamerauLevenstheinDistance . compare ( word , candidate ) ; features . add ( new Feature ( prob1 , prob3 , wordCount , levenstheinDist , detailedDistance , jaroWrinklerDist , candidate ) ) ; } if ( ! "noop" . equals ( score ) ) { features . sort ( Feature :: compareTo ) ; } List < String > words = features . stream ( ) . map ( Feature :: getWord ) . collect ( Collectors . toList ( ) ) ; SortedMap < String , Float > matchData = new TreeMap < > ( ) ; matchData . put ( "candidateCount" , ( float ) words . size ( ) ) ; List < SuggestedReplacement > suggestionsData = features . stream ( ) . map ( f -> { SuggestedReplacement s = new SuggestedReplacement ( f . getWord ( ) ) ; s . setFeatures ( f . getData ( ) ) ; return s ; } ) . collect ( Collectors . toList ( ) ) ; return Pair . of ( suggestionsData , matchData ) ; }
compute features for training or prediction of a ranking model for suggestions
12,886
public static boolean ignoreForIncompleteSentences ( String ruleId , Language lang ) { return rules . contains ( new Key ( lang . getShortCode ( ) , ruleId ) ) ; }
Whether this rule should be ignored when the sentence isn t finished yet .
12,887
public static String i18n ( ResourceBundle messages , String key , Object ... messageArguments ) { MessageFormat formatter = new MessageFormat ( "" ) ; formatter . applyPattern ( messages . getString ( key ) . replaceAll ( "'" , "''" ) ) ; return formatter . format ( messageArguments ) ; }
Translate a text string based on our i18n files .
12,888
private static List < BitextRule > getAllBuiltinBitextRules ( Language language , ResourceBundle messages ) { List < BitextRule > rules = new ArrayList < > ( ) ; try { List < Class < ? extends BitextRule > > classes = BitextRule . getRelevantRules ( ) ; for ( Class class1 : classes ) { Constructor [ ] constructors = class1 . getConstructors ( ) ; boolean foundConstructor = false ; for ( Constructor constructor : constructors ) { Class [ ] paramTypes = constructor . getParameterTypes ( ) ; if ( paramTypes . length == 0 ) { rules . add ( ( BitextRule ) constructor . newInstance ( ) ) ; foundConstructor = true ; break ; } if ( paramTypes . length == 1 && paramTypes [ 0 ] . equals ( ResourceBundle . class ) ) { rules . add ( ( BitextRule ) constructor . newInstance ( messages ) ) ; foundConstructor = true ; break ; } if ( paramTypes . length == 2 && paramTypes [ 0 ] . equals ( ResourceBundle . class ) && paramTypes [ 1 ] . equals ( Language . class ) ) { rules . add ( ( BitextRule ) constructor . newInstance ( messages , language ) ) ; foundConstructor = true ; break ; } } if ( ! foundConstructor ) { throw new RuntimeException ( "Unknown constructor type for rule class " + class1 . getName ( ) + ", it supports only these constructors: " + Arrays . toString ( constructors ) ) ; } } } catch ( Exception e ) { throw new RuntimeException ( "Failed to load bitext rules" , e ) ; } return rules ; }
Use reflection to add bitext rules .
12,889
public static void selectRules ( JLanguageTool lt , List < String > disabledRuleIds , List < String > enabledRuleIds , boolean useEnabledOnly ) { Set < String > disabledRuleIdsSet = new HashSet < > ( ) ; disabledRuleIdsSet . addAll ( disabledRuleIds ) ; Set < String > enabledRuleIdsSet = new HashSet < > ( ) ; enabledRuleIdsSet . addAll ( enabledRuleIds ) ; selectRules ( lt , Collections . emptySet ( ) , Collections . emptySet ( ) , disabledRuleIdsSet , enabledRuleIdsSet , useEnabledOnly ) ; }
Enable and disable rules of the given LanguageTool instance .
12,890
public static List < BitextRule > selectBitextRules ( List < BitextRule > bRules , List < String > disabledRules , List < String > enabledRules , boolean useEnabledOnly ) { List < BitextRule > newBRules = new ArrayList < > ( bRules . size ( ) ) ; newBRules . addAll ( bRules ) ; List < BitextRule > rulesToDisable = new ArrayList < > ( ) ; if ( useEnabledOnly ) { for ( String enabledRule : enabledRules ) { for ( BitextRule b : bRules ) { if ( ! b . getId ( ) . equals ( enabledRule ) ) { rulesToDisable . add ( b ) ; } } } } else { for ( String disabledRule : disabledRules ) { for ( BitextRule b : newBRules ) { if ( b . getId ( ) . equals ( disabledRule ) ) { rulesToDisable . add ( b ) ; } } } } newBRules . removeAll ( rulesToDisable ) ; return newBRules ; }
Enable and disable bitext rules .
12,891
private String getNumAgreedPosTag ( String leftPosTag , String rightPosTag , boolean leftNv ) { String agreedPosTag = null ; if ( leftPosTag . contains ( ":p:" ) && SING_REGEX_F . matcher ( rightPosTag ) . find ( ) || SING_REGEX_F . matcher ( leftPosTag ) . find ( ) && rightPosTag . contains ( ":p:" ) ) { String leftConj = PosTagHelper . getConj ( leftPosTag ) ; if ( leftConj != null && leftConj . equals ( PosTagHelper . getConj ( rightPosTag ) ) ) { agreedPosTag = leftPosTag ; } } return agreedPosTag ; }
right part is numr
12,892
public PatternTokenBuilder csToken ( String token ) { this . token = Objects . requireNonNull ( token ) ; caseSensitive = true ; return this ; }
Add a case - sensitive token .
12,893
static UserLimits getLimitsFromToken ( HTTPServerConfig config , String jwtToken ) { Objects . requireNonNull ( jwtToken ) ; try { String secretKey = config . getSecretTokenKey ( ) ; if ( secretKey == null ) { throw new RuntimeException ( "You specified a 'token' parameter but this server doesn't accept tokens" ) ; } Algorithm algorithm = Algorithm . HMAC256 ( secretKey ) ; DecodedJWT decodedToken ; try { JWT . require ( algorithm ) . build ( ) . verify ( jwtToken ) ; decodedToken = JWT . decode ( jwtToken ) ; } catch ( JWTDecodeException e ) { throw new AuthException ( "Could not decode token '" + jwtToken + "'" , e ) ; } Claim maxTextLengthClaim = decodedToken . getClaim ( "maxTextLength" ) ; Claim premiumClaim = decodedToken . getClaim ( "premium" ) ; boolean hasPremium = ! premiumClaim . isNull ( ) && premiumClaim . asBoolean ( ) ; Claim uidClaim = decodedToken . getClaim ( "uid" ) ; long uid = uidClaim . isNull ( ) ? - 1 : uidClaim . asLong ( ) ; return new UserLimits ( maxTextLengthClaim . isNull ( ) ? config . maxTextLength : maxTextLengthClaim . asInt ( ) , config . maxCheckTimeMillis , hasPremium ? uid : null ) ; } catch ( UnsupportedEncodingException e ) { throw new RuntimeException ( e ) ; } }
Get limits from the JWT key itself no database access needed .
12,894
public static UserLimits getLimitsByApiKey ( HTTPServerConfig config , String username , String apiKey ) { DatabaseAccess db = DatabaseAccess . getInstance ( ) ; Long id = db . getUserId ( username , apiKey ) ; return new UserLimits ( config . maxTextLengthWithApiKey , config . maxCheckTimeWithApiKeyMillis , id ) ; }
Get limits from the api key itself database access is needed .
12,895
public Language getLanguage ( ) { XComponent xComponent = OfficeTools . getCurrentComponent ( xContext ) ; Locale charLocale ; XPropertySet xCursorProps ; try { XModel model = UnoRuntime . queryInterface ( XModel . class , xComponent ) ; if ( model == null ) { return Languages . getLanguageForShortCode ( "en-US" ) ; } XTextViewCursorSupplier xViewCursorSupplier = UnoRuntime . queryInterface ( XTextViewCursorSupplier . class , model . getCurrentController ( ) ) ; XTextViewCursor xCursor = xViewCursorSupplier . getViewCursor ( ) ; if ( xCursor . isCollapsed ( ) ) { xCursorProps = UnoRuntime . queryInterface ( XPropertySet . class , xCursor ) ; } else { xCursorProps = UnoRuntime . queryInterface ( XPropertySet . class , xCursor . getText ( ) . createTextCursorByRange ( xCursor . getStart ( ) ) ) ; } if ( new KhmerDetector ( ) . isThisLanguage ( xCursor . getText ( ) . getString ( ) ) ) { return Languages . getLanguageForShortCode ( "km" ) ; } if ( new TamilDetector ( ) . isThisLanguage ( xCursor . getText ( ) . getString ( ) ) ) { return Languages . getLanguageForShortCode ( "ta" ) ; } Object obj = xCursorProps . getPropertyValue ( "CharLocale" ) ; if ( obj == null ) { return Languages . getLanguageForShortCode ( "en-US" ) ; } charLocale = ( Locale ) obj ; boolean langIsSupported = false ; for ( Language element : Languages . get ( ) ) { if ( charLocale . Language . equalsIgnoreCase ( LIBREOFFICE_SPECIAL_LANGUAGE_TAG ) && element . getShortCodeWithCountryAndVariant ( ) . equalsIgnoreCase ( charLocale . Variant ) ) { langIsSupported = true ; break ; } if ( element . getShortCode ( ) . equals ( charLocale . Language ) ) { langIsSupported = true ; break ; } } if ( ! langIsSupported ) { String message = Tools . i18n ( messages , "language_not_supported" , charLocale . Language ) ; JOptionPane . showMessageDialog ( null , message ) ; return null ; } } catch ( Throwable t ) { MessageHandler . showError ( t ) ; return null ; } return getLanguage ( charLocale ) ; }
Checks the language under the cursor . Used for opening the configuration dialog .
12,896
private void setConfigValues ( Configuration config , JLanguageTool langTool ) { this . config = config ; this . langTool = langTool ; this . noMultiReset = config . isNoMultiReset ( ) ; for ( SingleDocument document : documents ) { document . setConfigValues ( config ) ; } }
Set config Values for all documents
12,897
private int getNumDoc ( String docID ) { if ( goneContext != null ) { removeDoc ( docID ) ; } for ( int i = 0 ; i < documents . size ( ) ; i ++ ) { if ( documents . get ( i ) . getDocID ( ) . equals ( docID ) ) { if ( ! testMode && documents . get ( i ) . getXComponent ( ) == null ) { XComponent xComponent = OfficeTools . getCurrentComponent ( xContext ) ; if ( xComponent == null ) { MessageHandler . printToLogFile ( "Error: Document (ID: " + docID + ") has no XComponent -> Internal space will not be deleted when document disposes" ) ; } else { try { xComponent . addEventListener ( xEventListener ) ; } catch ( Throwable t ) { MessageHandler . printToLogFile ( "Error: Document (ID: " + docID + ") has no XComponent -> Internal space will not be deleted when document disposes" ) ; xComponent = null ; } if ( xComponent != null ) { documents . get ( i ) . setXComponent ( xContext , xComponent ) ; MessageHandler . printToLogFile ( "Fixed: XComponent set for Document (ID: " + docID + ")" ) ; } } } return i ; } } XComponent xComponent = null ; if ( ! testMode ) { xComponent = OfficeTools . getCurrentComponent ( xContext ) ; if ( xComponent == null ) { MessageHandler . printToLogFile ( "Error: Document (ID: " + docID + ") has no XComponent -> Internal space will not be deleted when document disposes" ) ; } else { try { xComponent . addEventListener ( xEventListener ) ; } catch ( Throwable t ) { MessageHandler . printToLogFile ( "Error: Document (ID: " + docID + ") has no XComponent -> Internal space will not be deleted when document disposes" ) ; xComponent = null ; } } } documents . add ( new SingleDocument ( xContext , config , docID , xComponent ) ) ; setMenuTextForSwitchOff ( xContext ) ; if ( debugMode ) { MessageHandler . printToLogFile ( "Document " + docNum + " created; docID = " + docID ) ; } return documents . size ( ) - 1 ; }
Get or Create a Number from docID Return - 1 if failed
12,898
private void removeDoc ( String docID ) { int rmNum = - 1 ; int docNum = - 1 ; for ( int i = 0 ; i < documents . size ( ) ; i ++ ) { XComponent xComponent = documents . get ( i ) . getXComponent ( ) ; if ( xComponent != null && xComponent . equals ( goneContext ) ) { rmNum = i ; break ; } } if ( rmNum < 0 ) { MessageHandler . printToLogFile ( "Error: Disposed document not found" ) ; goneContext = null ; } for ( int i = 0 ; i < documents . size ( ) ; i ++ ) { if ( documents . get ( i ) . getDocID ( ) . equals ( docID ) ) { docNum = i ; break ; } } if ( rmNum >= 0 && docNum != rmNum ) { documents . remove ( rmNum ) ; goneContext = null ; if ( debugMode ) { MessageHandler . printToLogFile ( "Document " + rmNum + " deleted" ) ; } } }
Delete a document number and all internal space
12,899
public boolean setMenuTextForSwitchOff ( XComponentContext xContext ) { boolean ret = true ; XMenuBar menubar = OfficeTools . getMenuBar ( xContext ) ; if ( menubar == null ) { MessageHandler . printToLogFile ( "Menubar is null" ) ; return ret ; } XPopupMenu toolsMenu = null ; XPopupMenu ltMenu = null ; short toolsId = 0 ; short ltId = 0 ; try { for ( short i = 0 ; i < menubar . getItemCount ( ) ; i ++ ) { toolsId = menubar . getItemId ( i ) ; String command = menubar . getCommand ( toolsId ) ; if ( TOOLS_COMMAND . equals ( command ) ) { toolsMenu = menubar . getPopupMenu ( toolsId ) ; break ; } } if ( toolsMenu == null ) { MessageHandler . printToLogFile ( "Tools Menu is null" ) ; return ret ; } for ( short i = 0 ; i < toolsMenu . getItemCount ( ) ; i ++ ) { String command = toolsMenu . getCommand ( toolsMenu . getItemId ( i ) ) ; if ( WORD_COUNT_COMMAND . equals ( command ) ) { ltId = toolsMenu . getItemId ( ( short ) ( i - 1 ) ) ; ltMenu = toolsMenu . getPopupMenu ( ltId ) ; break ; } } if ( ltMenu == null ) { MessageHandler . printToLogFile ( "LT Menu is null" ) ; return ret ; } short switchOffId = 0 ; for ( short i = 0 ; i < ltMenu . getItemCount ( ) ; i ++ ) { String command = ltMenu . getCommand ( ltMenu . getItemId ( i ) ) ; if ( LT_SWITCH_OFF_COMMAND . equals ( command ) ) { switchOffId = ltMenu . getItemId ( i ) ; break ; } } if ( switchOffId == 0 ) { MessageHandler . printToLogFile ( "switchOffId not found" ) ; return ret ; } boolean isSwitchOff = ltMenu . isItemChecked ( switchOffId ) ; if ( ( switchOff && isSwitchOff ) || ( ! switchOff && ! isSwitchOff ) ) { ret = false ; } ltMenu . setItemText ( switchOffId , messages . getString ( "loMenuSwitchOff" ) ) ; if ( switchOff ) { ltMenu . checkItem ( switchOffId , true ) ; } else { ltMenu . checkItem ( switchOffId , false ) ; } } catch ( Throwable t ) { MessageHandler . printException ( t ) ; } toolsMenu . setPopupMenu ( ltId , ltMenu ) ; menubar . setPopupMenu ( toolsId , toolsMenu ) ; return ret ; }
Set or remove a check mark to the LT menu item Switch Off return true if text should be rechecked