idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
41,100
public byte [ ] processBlock ( byte [ ] in , int inOff , int inLen ) { if ( core == null ) { throw new IllegalStateException ( "RSA engine not initialised" ) ; } return core . convertOutput ( core . processBlock ( core . convertInput ( in , inOff , inLen ) ) ) ; }
Process a single block using the basic RSA algorithm .
41,101
public byte [ ] transform ( byte [ ] classfileBuffer , Configuration configuration ) { InstrumentationActions instrumentationActions = calculateTransformationParameters ( classfileBuffer , configuration ) ; if ( ! instrumentationActions . includeClass ) { return classfileBuffer ; } return transform ( classfileBuffer , ...
Instrument the given class based on the configuration .
41,102
private InstrumentationActions calculateTransformationParameters ( byte [ ] classfileBuffer , Configuration configuration ) { DiscoveryClassVisitor discoveryClassVisitor = new DiscoveryClassVisitor ( configuration ) ; new ClassReader ( classfileBuffer ) . accept ( discoveryClassVisitor , 0 ) ; return discoveryClassVisi...
Based on the structure of the class and the supplied configuration determine the concrete instrumentation actions for the class .
41,103
private byte [ ] transform ( byte [ ] classfileBuffer , InstrumentationActions instrumentationActions ) { ClassReader classReader = new ClassReader ( classfileBuffer ) ; ClassWriter classWriter = new ClassWriter ( classReader , ClassWriter . COMPUTE_FRAMES ) ; ClassVisitor localVariableStateEmitterTestClassVisitor = ne...
Perform the given instrumentation actions on a class .
41,104
private LocalVariableScope calculateScope ( LocalVariableScopeData scope ) { final TryCatchBlockLabels enclosingTry = getEnclosingTry ( scope ) ; final Label start = scope . labels . start ; final Label end = getTryFixedEndLabel ( scope , enclosingTry ) ; int startIndex = getIndex ( start ) ; int endIndex = getIndex ( ...
Calculate the start and end line numbers for variable scopes . If the LocalVariableScope start line is 0 then it is an input parameter as it s scope start label appeared before the method body .
41,105
public static IBAN parse ( String input ) { if ( input == null || input . length ( ) == 0 ) { throw new IllegalArgumentException ( "Input is null or empty string." ) ; } if ( ! isLetterOrDigit ( input . charAt ( 0 ) ) || ! isLetterOrDigit ( input . charAt ( input . length ( ) - 1 ) ) ) { throw new IllegalArgumentExcept...
Parses the given string into an IBAN object and confirms the check digits .
41,106
public static String toPlain ( String input ) { Matcher matcher = SPACE_PATTERN . matcher ( input ) ; if ( matcher . find ( ) ) { return matcher . replaceAll ( "" ) ; } else { return input ; } }
Removes any spaces contained in the String thereby converting the input into a plain IBAN
41,107
private static String addSpaces ( String value ) { final int length = value . length ( ) ; final int lastPossibleBlock = length - 4 ; final StringBuilder sb = new StringBuilder ( length + ( length - 1 ) / 4 ) ; int i ; for ( i = 0 ; i < lastPossibleBlock ; i += 4 ) { sb . append ( value , i , i + 4 ) ; sb . append ( ' ...
Converts a plain to a pretty printed IBAN
41,108
public static int calculateCheckDigits ( CharSequence input ) { if ( input == null || input . length ( ) < 5 || input . charAt ( 2 ) != '0' || input . charAt ( 3 ) != '0' ) { throw new IllegalArgumentException ( "The input must be non-null, have a minimum length of five characters, and the characters at indices 2 and 3...
Calculates the check digits to be used in a MOD97 checked string .
41,109
public static int getLengthForCountryCode ( String countryCode ) { int index = indexOf ( countryCode ) ; if ( index > - 1 ) { return CountryCodes . COUNTRY_IBAN_LENGTHS [ index ] & REMOVE_SEPA_MASK ; } return - 1 ; }
Returns the IBAN length for a given country code .
41,110
public static boolean isSEPACountry ( String countryCode ) { int index = indexOf ( countryCode ) ; if ( index > - 1 ) { return ( CountryCodes . COUNTRY_IBAN_LENGTHS [ index ] & SEPA ) == SEPA ; } return false ; }
Returns whether the given country code is in SEPA .
41,111
public static boolean isKnownCountryCode ( String aCountryCode ) { if ( aCountryCode == null || aCountryCode . length ( ) != 2 ) { return false ; } return indexOf ( aCountryCode ) >= 0 ; }
Returns whether the given string is a known country code .
41,112
public void stop ( ) { try { if ( this . socket != null ) { this . socket . close ( ) ; } } catch ( final IOException e1 ) { GPSdEndpoint . LOG . debug ( "Close forced: " + e1 . getMessage ( ) ) ; } this . listeners . clear ( ) ; if ( this . listenThread != null ) { this . listenThread . halt ( ) ; } this . listenThrea...
Stops the endpoint .
41,113
void handleDisconnected ( ) throws IOException { synchronized ( this . asyncMutex ) { if ( socket != null ) { socket . close ( ) ; } this . socket = new Socket ( server , port ) ; this . in = new BufferedReader ( new InputStreamReader ( this . socket . getInputStream ( ) ) ) ; this . out = new BufferedWriter ( new Outp...
Our socket thread got disconnect and is exiting .
41,114
@ SuppressWarnings ( { "unchecked" , "unused" } ) protected < T extends IGPSObject > List < T > parseObjectArray ( final JSONArray array , final Class < T > type ) throws ParseException { try { if ( array == null ) { return new ArrayList < T > ( 10 ) ; } final List < T > objects = new ArrayList < T > ( 10 ) ; for ( int...
parse a whole JSONArray into a list of IGPSObjects
41,115
public State < T > onEvent ( T stateful , String event , Object ... args ) throws TooBusyException { int attempts = 0 ; while ( this . retryAttempts == - 1 || attempts < this . retryAttempts ) { try { State < T > current = this . getCurrentState ( stateful ) ; Transition < T > transition = this . getTransition ( event ...
Process event . Will handle all retry attempts . If attempts exceed maximum retries it will throw a TooBusyException .
41,116
public static Field getField ( final Class < ? > clazz , final String fieldName ) { Field field = null ; for ( Class < ? > current = clazz ; current != null && field == null ; current = current . getSuperclass ( ) ) { try { field = current . getDeclaredField ( fieldName ) ; } catch ( final NoSuchFieldException e ) { } ...
Climb the class hierarchy starting with the clazz provided looking for the field with fieldName
41,117
protected Annotation [ ] createParameterAnnotations ( String parmName , MethodInfo methodInfo , java . lang . annotation . Annotation [ ] annotations , ConstPool parameterConstPool ) throws IllegalArgumentException , IllegalAccessException , InvocationTargetException { List < Annotation > ctParmAnnotations = new Linked...
Clone all the parameter Annotations from the StatefulController to the Proxy
41,118
public void onAfterSave ( Object source , DBObject dbo ) { this . persister . onAfterSave ( source , dbo ) ; }
Pass the Save event to the MongoPersister to cascade to the StateDocument
41,119
private void mapControllerAndEntityClasses ( BeanDefinitionRegistry reg , Map < String , Class < ? > > controllerToEntityMapping , Map < Class < ? > , String > entityToRepositoryMapping , Map < Class < ? > , Set < String > > entityToControllerMappings ) throws ClassNotFoundException { for ( String bfName : reg . getBea...
Iterate thru all beans and fetch the StatefulControllers
41,120
public V getValue ( T object ) { try { if ( this . getMethod != null ) { return ( V ) this . getMethod . invoke ( object ) ; } else { return ( V ) this . field . get ( object ) ; } } catch ( IllegalAccessException e ) { throw new RuntimeException ( e ) ; } catch ( InvocationTargetException e ) { throw new RuntimeExcept...
Return the value of the object
41,121
public void setValue ( T object , V value ) { try { if ( this . setMethod != null ) { this . setMethod . invoke ( object , value ) ; } else { this . field . set ( object , value ) ; } } catch ( IllegalAccessException e ) { throw new RuntimeException ( e ) ; } catch ( InvocationTargetException e ) { throw new RuntimeExc...
Set s the value of the object
41,122
public static Annotation cloneAnnotation ( ConstPool constPool , java . lang . annotation . Annotation annotation ) throws IllegalArgumentException , IllegalAccessException , InvocationTargetException { Class < ? > clazz = annotation . annotationType ( ) ; Annotation annot = new Annotation ( clazz . getName ( ) , const...
Clone an annotation and all of it s methods
41,123
private void refitText ( ) { if ( ! mSizeToFit ) { return ; } if ( mMaxLines <= 0 ) { return ; } String text = mTextView . getText ( ) . toString ( ) ; int targetWidth = mTextView . getWidth ( ) - mTextView . getPaddingLeft ( ) - mTextView . getPaddingRight ( ) ; if ( targetWidth > 0 ) { Context context = mTextView . g...
Re size the font so the specified text fits in the text box assuming the text box is the specified width .
41,124
protected View onCreateView ( String name , AttributeSet attrs ) throws ClassNotFoundException { View view = null ; for ( String prefix : CLASS_PREFIX_LIST ) { try { view = createView ( name , prefix , attrs ) ; } catch ( ClassNotFoundException ignored ) { } } if ( view == null ) view = super . onCreateView ( name , at...
The LayoutInflater onCreateView is the fourth port of call for LayoutInflation . BUT only for none CustomViews . Basically if this method doesn t inflate the View nothing probably will .
41,125
public RECORD parse ( final String value ) throws DissectionFailure , InvalidDissectorException , MissingDissectorsException { assembleDissectors ( ) ; final Parsable < RECORD > parsable = createParsable ( ) ; if ( parsable == null ) { return null ; } parsable . setRootDissection ( rootType , value ) ; return parse ( p...
Parse the value and return a new instance of RECORD . For this method to work the RECORD class may NOT be an inner class .
41,126
public List < String > getPossiblePaths ( int maxDepth ) { if ( allDissectors . isEmpty ( ) ) { return Collections . emptyList ( ) ; } try { assembleDissectors ( ) ; } catch ( MissingDissectorsException | InvalidDissectorException e ) { } List < String > paths = new ArrayList < > ( ) ; Map < String , List < String > > ...
This method is for use by the developer to query the parser about the possible paths that may be extracted .
41,127
public static String resilientUrlDecode ( String input ) { String cookedInput = input ; if ( cookedInput . indexOf ( '%' ) > - 1 ) { cookedInput = VALID_STANDARD . matcher ( cookedInput ) . replaceAll ( "%00%$1" ) ; cookedInput = CHOPPED_STANDARD . matcher ( cookedInput ) . replaceAll ( "" ) ; if ( cookedInput . contai...
The main goal of the resilientUrlDecode is to have a UrlDecode that keeps working even if the input is seriously flawed or even uses a rejected standard .
41,128
public Dissector getNewInstance ( ) { try { Constructor < ? extends Dissector > co = this . getClass ( ) . getConstructor ( ) ; Dissector newInstance = co . newInstance ( ) ; initializeNewInstance ( newInstance ) ; return newInstance ; } catch ( Exception e ) { LOG . error ( "Unable to create instance of {}: {}" , this...
Create an additional instance of this dissector . This is needed because in the parse tree we may need the same dissector multiple times . In order to optimize per node we need separate instances .
41,129
public void declareRequestedFieldname ( String name ) { if ( name . endsWith ( ".*" ) ) { stringSetValues . put ( name , new HashMap < > ( ) ) ; stringSetPrefixes . put ( name . substring ( 0 , name . length ( ) - 1 ) , name ) ; } }
For multivalue things we need to know what the name is we are expecting . For those patterns we match the values we get against
41,130
public JSONAPIDocument < User > fetchUser ( Collection < User . UserField > optionalFields ) throws IOException { URIBuilder pathBuilder = new URIBuilder ( ) . setPath ( "current_user" ) . addParameter ( "include" , "pledges" ) ; if ( optionalFields != null ) { Set < User . UserField > optionalAndDefaultFields = new Ha...
Get the user object of the creator
41,131
public < T > T eval ( XMLResource resource , Class < T > aReturnType ) throws Exception { T retVal = ( T ) xPathExpression . evaluate ( resource . doc ( ) , getConstant ( aReturnType ) ) ; return retVal ; }
Evaluate the XPath on an XMLResource and convert the result into aReturnType .
41,132
protected Object unmarshal ( ) throws IOException , JSONException { json = new JSONTokener ( new InputStreamReader ( inputStream , "UTF-8" ) ) . nextValue ( ) ; inputStream . close ( ) ; return json ; }
Transforming the JSON on the fly
41,133
public JSONResource json ( JSONPathQuery path ) throws Exception { Object jsonValue = path . eval ( this ) ; return json ( jsonValue . toString ( ) ) ; }
Execute the given path query on the json GET the returned URI expecting JSON
41,134
protected void addContent ( URLConnection con ) throws IOException { con . setDoOutput ( true ) ; con . addRequestProperty ( "Content-Type" , mime ) ; con . addRequestProperty ( "Content-Length" , String . valueOf ( content . length ) ) ; OutputStream os = con . getOutputStream ( ) ; writeContent ( os ) ; os . close ( ...
Add the content to the URLConnection used .
41,135
public void writeHeader ( OutputStream os ) throws IOException { os . write ( ascii ( "Content-Type: " + mime + "\r\n" ) ) ; os . write ( ascii ( "Content-Length: " + String . valueOf ( content . length ) + "\r\n" ) ) ; }
Used as a mime part writing content headers
41,136
public static String [ ] getNames ( Object object ) { if ( object == null ) { return null ; } Class < ? extends Object > klass = object . getClass ( ) ; Field [ ] fields = klass . getFields ( ) ; int length = fields . length ; if ( length == 0 ) { return null ; } String [ ] names = new String [ length ] ; for ( int i =...
Get an array of field names from an Object .
41,137
public static String encodeIfNecessary ( String text , Usage usage , int usedCharacters ) { if ( hasToBeEncoded ( text , usedCharacters ) ) return encodeEncodedWord ( text , usage , usedCharacters ) ; else return text ; }
Shortcut method that encodes the specified text into an encoded - word if the text has to be encoded .
41,138
public static String encodeEncodedWord ( String text , Usage usage , int usedCharacters , Charset charset , Encoding encoding ) { if ( text == null ) throw new IllegalArgumentException ( ) ; if ( usedCharacters < 0 || usedCharacters > MAX_USED_CHARACTERS ) throw new IllegalArgumentException ( ) ; if ( charset == null )...
Encodes the specified text into an encoded word or a sequence of encoded words separated by space . The text is separated into a sequence of encoded words if it does not fit in a single one .
41,139
public static String encodeB ( byte [ ] bytes ) { StringBuilder sb = new StringBuilder ( ) ; int idx = 0 ; final int end = bytes . length ; for ( ; idx < end - 2 ; idx += 3 ) { int data = ( bytes [ idx ] & 0xff ) << 16 | ( bytes [ idx + 1 ] & 0xff ) << 8 | bytes [ idx + 2 ] & 0xff ; sb . append ( ( char ) BASE64_TABLE ...
Encodes the specified byte array using the B encoding defined in RFC 2047 .
41,140
public static String encodeQ ( byte [ ] bytes , Usage usage ) { BitSet qChars = usage == Usage . TEXT_TOKEN ? Q_REGULAR_CHARS : Q_RESTRICTED_CHARS ; StringBuilder sb = new StringBuilder ( ) ; final int end = bytes . length ; for ( int idx = 0 ; idx < end ; idx ++ ) { int v = bytes [ idx ] & 0xff ; if ( v == 32 ) { sb ....
Encodes the specified byte array using the Q encoding defined in RFC 2047 .
41,141
public static boolean isToken ( String str ) { final int length = str . length ( ) ; if ( length == 0 ) return false ; for ( int idx = 0 ; idx < length ; idx ++ ) { char ch = str . charAt ( idx ) ; if ( ! TOKEN_CHARS . get ( ch ) ) return false ; } return true ; }
Tests whether the specified string is a token as defined in RFC 2045 section 5 . 1 .
41,142
private static boolean isDotAtomText ( String str ) { char prev = '.' ; final int length = str . length ( ) ; if ( length == 0 ) return false ; for ( int idx = 0 ; idx < length ; idx ++ ) { char ch = str . charAt ( idx ) ; if ( ch == '.' ) { if ( prev == '.' || idx == length - 1 ) return false ; } else { if ( ! ATEXT_C...
RFC 5322 section 3 . 2 . 3
41,143
public Resty setOptions ( Option ... someOptions ) { options = ( someOptions == null ) ? new Option [ 0 ] : someOptions ; for ( Option o : options ) { o . init ( this ) ; } return this ; }
Set options if you missed your opportunity in the c tor or if you want to change the options .
41,144
public void authenticate ( URI aSite , String aLogin , char [ ] aPwd ) { rath . addSite ( aSite , aLogin , aPwd ) ; }
Register this root URI for authentication . Whenever a URL is requested that starts with this root the credentials given are used for HTTP AUTH . Note that currently authentication information is shared across all Resty instances . This is due to the shortcomings of the java . net authentication mechanism . This might ...
41,145
public void authenticateForRealm ( String realm , String aLogin , char [ ] charArray ) { rath . addRealm ( realm , aLogin , charArray ) ; }
Register a login password for the realm returned by the authorization challenge . Use this method instead of authenticate in case the URL is not made available to the java . net . Authenticator class
41,146
public JSONResource json ( URI anUri , AbstractContent requestContent ) throws IOException { return doPOSTOrPUT ( anUri , requestContent , createJSONResource ( ) ) ; }
POST to a URI and parse the result as JSON
41,147
public XMLResource xml ( URI anUri , AbstractContent requestContent ) throws IOException { return doPOSTOrPUT ( anUri , requestContent , createXMLResource ( ) ) ; }
POST to a URI and parse the result as XML
41,148
protected void addAdditionalHeaders ( URLConnection con ) { for ( Map . Entry < String , String > header : getAdditionalHeaders ( ) . entrySet ( ) ) { con . addRequestProperty ( header . getKey ( ) , header . getValue ( ) ) ; } }
Add all headers that have been set with the alwaysSend call .
41,149
protected < T extends AbstractResource > T fillResourceFromURL ( URLConnection con , T resource ) throws IOException { resource . fill ( con ) ; resource . getAdditionalHeaders ( ) . putAll ( getAdditionalHeaders ( ) ) ; return resource ; }
Get the content from the URLConnection create a Resource representing the content and carry over some metadata like HTTP Result and location header .
41,150
public static Content content ( JSONObject someJson ) { Content c = null ; try { c = new Content ( "application/json; charset=UTF-8" , someJson . toString ( ) . getBytes ( "UTF-8" ) ) ; } catch ( UnsupportedEncodingException e ) { } return c ; }
Create a content object from a JSON object . Use this to POST the content to a URL .
41,151
public static Content content ( String somePlainText ) { Content c = null ; try { c = new Content ( "text/plain; charset=UTF-8" , somePlainText . getBytes ( "UTF-8" ) ) ; } catch ( UnsupportedEncodingException e ) { } return c ; }
Create a content object from plain text . Use this to POST the content to a URL .
41,152
public static String enc ( String unencodedString ) { try { return URLEncoder . encode ( unencodedString , "UTF-8" ) ; } catch ( UnsupportedEncodingException e ) { } return null ; }
Shortcut to URLEncoder . encode with UTF - 8 .
41,153
public Document doc ( ) throws IOException { InputSource is ; if ( document == null ) { if ( text == null ) { is = new InputSource ( inputStream ) ; is . setEncoding ( getCharSet ( ) . name ( ) ) ; } else { is = new InputSource ( new StringReader ( text ) ) ; } try { document = DocumentBuilderFactory . newInstance ( ) ...
Return the DOM of the XML resource .
41,154
public JSONResource json ( XPathQuery path ) throws Exception { String uri = path . eval ( this , String . class ) ; return json ( uri ) ; }
Execute the given path query on the XML GET the returned URI expecting JSON as content
41,155
public XMLResource xml ( XPathQuery path , Content aContent ) throws Exception { String uri = path . eval ( this , String . class ) ; return xml ( uri , aContent ) ; }
Execute the given path query on the XML POST the returned URI expecting XML
41,156
public NodeList get ( String xPath ) throws Exception { XPathQuery xp = new XPathQuery ( xPath ) ; return xp . eval ( this ) ; }
Access the XML evaluating an XPath on it returning the resulting NodeList .
41,157
public < T > T get ( String xPath , Class < T > returnType ) throws Exception { XPathQuery xp = new XPathQuery ( xPath ) ; return xp . eval ( this , returnType ) ; }
Access the XML evaluating an XPath on it returning the resulting Object of the desired type Supported types are NodeList String Boolean Double Node .
41,158
public void addSite ( URI aRootUrl , String login , char [ ] pwd ) { String rootUri = aRootUrl . normalize ( ) . toString ( ) ; boolean replaced = false ; for ( Site site : sites ) { if ( site . root . equals ( rootUri ) ) { site . login = login ; site . pwd = pwd ; replaced = true ; break ; } } if ( ! replaced ) { Sit...
Add or replace an authentication for a root URL aka site .
41,159
public boolean status ( int responseCode ) { if ( urlConnection instanceof HttpURLConnection ) { HttpURLConnection http = ( HttpURLConnection ) urlConnection ; try { return http . getResponseCode ( ) == responseCode ; } catch ( IOException e ) { e . printStackTrace ( ) ; return false ; } } else return false ; }
Check if the URLConnection has returned the specified responseCode
41,160
public URI location ( ) { String loc = http ( ) . getHeaderField ( "Location" ) ; if ( loc != null ) { return URI . create ( loc ) ; } return null ; }
Get the location header as URI . Returns null if there is no location header .
41,161
public String printResponseHeaders ( ) { StringBuilder sb = new StringBuilder ( ) ; HttpURLConnection http = http ( ) ; if ( http != null ) { Map < String , List < String > > header = http . getHeaderFields ( ) ; for ( String key : header . keySet ( ) ) { for ( String val : header . get ( key ) ) { sb . append ( key ) ...
Print out the response headers for this resource .
41,162
public File save ( File aFileName ) throws IOException { BufferedOutputStream bos = new BufferedOutputStream ( new FileOutputStream ( aFileName ) , 1024 ) ; byte [ ] buffer = new byte [ 1024 ] ; int len = - 1 ; while ( ( len = inputStream . read ( buffer ) ) != - 1 ) { bos . write ( buffer , 0 , len ) ; } bos . close (...
Save the contents of the resource to a file . This reads the data from the stream and stores it into the given file . Depending on the resource the data might or might not be available afterwards .
41,163
protected Charset getCharSet ( ) { String contentType = urlConnection . getContentType ( ) ; Charset charset = Charset . forName ( "iso-8859-1" ) ; if ( contentType != null ) { Matcher m = charsetPattern . matcher ( contentType ) ; if ( m . find ( ) ) { String charsetString = m . group ( 1 ) ; try { charset = Charset ....
Get charset for this content type . Parses charset = attribute of content type or falls back to a default
41,164
private final String getOperationText ( final BinaryOperation exp ) { final String text ; if ( exp instanceof AdditionOperation ) { text = " + " ; } else if ( exp instanceof SubtractionOperation ) { text = " - " ; } else if ( exp instanceof MultiplicationOperation ) { text = " * " ; } else if ( exp instanceof DivisionO...
Returns the text value of the received operation .
41,165
private final V process ( final Iterable < DiceNotationExpression > nodes ) { accumulator . reset ( ) ; for ( final DiceNotationExpression current : nodes ) { if ( current instanceof BinaryOperation ) { accumulator . binaryOperation ( ( BinaryOperation ) current ) ; } else if ( current instanceof ConstantOperand ) { ac...
Returns the result from applying the accumulator in all the nodes .
41,166
private final IntegerOperand getIntegerOperand ( final String expression ) { final Integer value ; value = Integer . parseInt ( expression ) ; return new IntegerOperand ( value ) ; }
Creates an integer operand from the parsed expression .
41,167
private final DiceNotationExpression unwrap ( final DiceNotationExpression expression ) { final DiceNotationExpression result ; if ( expression instanceof ExpressionWrapper ) { result = ( ( ExpressionWrapper ) expression ) . getWrappedExpression ( ) ; } else { result = expression ; } return result ; }
Removes the expression wrappers used to temporally prune the nodes .
41,168
public synchronized void setPollingInterval ( final long pollingInterval ) { if ( pollingInterval <= 0 ) { throw new IllegalArgumentException ( "'pollingInterval' must be greater than 0" ) ; } currentPollingInterval = pollingInterval ; if ( listeners . size ( ) > 0 ) { stop ( ) ; start ( ) ; } }
Sets the polling interval
41,169
private void updateConnectedDevices ( final List < USBStorageDevice > currentConnectedDevices ) { final List < USBStorageDevice > removedDevices = new ArrayList < > ( ) ; synchronized ( this ) { final Iterator < USBStorageDevice > itConnectedDevices = connectedDevices . iterator ( ) ; while ( itConnectedDevices . hasNe...
Updates the internal state of this manager and sends
41,170
public boolean isMisspelled ( final String word ) { String wordToCheck = word ; if ( ! dictionaryMetadata . getInputConversionPairs ( ) . isEmpty ( ) ) { wordToCheck = DictionaryLookup . applyReplacements ( word , dictionaryMetadata . getInputConversionPairs ( ) ) ; } boolean isAlphabetic = wordToCheck . length ( ) != ...
Checks whether the word is misspelled by performing a series of checks according to properties of the dictionary .
41,171
public boolean isInDictionary ( final CharSequence word ) { try { byteBuffer = charSequenceToBytes ( word ) ; } catch ( UnmappableInputException e ) { return false ; } final MatchResult match = matcher . match ( matchResult , byteBuffer . array ( ) , 0 , byteBuffer . remaining ( ) , rootNode ) ; if ( containsSeparators...
Test whether the word is found in the dictionary .
41,172
public int getFrequency ( final CharSequence word ) { if ( ! dictionaryMetadata . isFrequencyIncluded ( ) ) { return 0 ; } final byte separator = dictionaryMetadata . getSeparator ( ) ; try { byteBuffer = charSequenceToBytes ( word ) ; } catch ( UnmappableInputException e ) { return 0 ; } final MatchResult match = matc...
Get the frequency value for a word form . It is taken from the first entry with this word form .
41,173
public List < String > replaceRunOnWords ( final String original ) { final List < String > candidates = new ArrayList < String > ( ) ; String wordToCheck = original ; if ( ! dictionaryMetadata . getInputConversionPairs ( ) . isEmpty ( ) ) { wordToCheck = DictionaryLookup . applyReplacements ( original , dictionaryMetad...
Propose suggestions for misspelled run - on words . This algorithm is inspired by spell . cc in s_fsa package by Jan Daciuk .
41,174
public ArrayList < String > findReplacements ( String word ) { final List < CandidateData > result = findReplacementCandidates ( word ) ; final ArrayList < String > resultSuggestions = new ArrayList < String > ( result . size ( ) ) ; for ( CandidateData cd : result ) { resultSuggestions . add ( cd . getWord ( ) ) ; } r...
Find suggestions by using K . Oflazer s algorithm . See Jan Daciuk s s_fsa package spell . cc for further explanation .
41,175
public int ed ( final int i , final int j , final int wordIndex , final int candIndex ) { int result ; int a , b , c ; if ( areEqual ( wordProcessed [ wordIndex ] , candidate [ candIndex ] ) ) { result = hMatrix . get ( i , j ) ; } else if ( wordIndex > 0 && candIndex > 0 && wordProcessed [ wordIndex ] == candidate [ c...
Calculates edit distance .
41,176
private boolean areEqual ( final char x , final char y ) { if ( x == y ) { return true ; } if ( dictionaryMetadata . getEquivalentChars ( ) != null ) { List < Character > chars = dictionaryMetadata . getEquivalentChars ( ) . get ( x ) ; if ( chars != null && chars . contains ( y ) ) { return true ; } } if ( dictionaryM...
by Jaume Ortola
41,177
public int cuted ( final int depth , final int wordIndex , final int candIndex ) { final int l = Math . max ( 0 , depth - effectEditDistance ) ; final int u = Math . min ( wordLen - 1 - ( wordIndex - depth ) , depth + effectEditDistance ) ; int minEd = effectEditDistance + 1 ; int wi = wordIndex + l - depth ; int d ; f...
Calculates cut - off edit distance .
41,178
private int matchAnyToOne ( final int wordIndex , final int candIndex ) { if ( replacementsAnyToOne . containsKey ( candidate [ candIndex ] ) ) { for ( final char [ ] rep : replacementsAnyToOne . get ( candidate [ candIndex ] ) ) { int i = 0 ; while ( i < rep . length && ( wordIndex + i ) < wordLen && rep [ i ] == word...
Match the last letter of the candidate against two or more letters of the word .
41,179
static boolean containsNoDigit ( final String s ) { for ( int k = 0 ; k < s . length ( ) ; k ++ ) { if ( Character . isDigit ( s . charAt ( k ) ) ) { return false ; } } return true ; }
Checks whether a string contains a digit . Used for ignoring words with numbers
41,180
void setWordAndCandidate ( final String word , final String candidate ) { wordProcessed = word . toCharArray ( ) ; wordLen = wordProcessed . length ; this . candidate = candidate . toCharArray ( ) ; candLen = this . candidate . length ; effectEditDistance = wordLen <= editDistance ? wordLen - 1 : editDistance ; }
Sets up the word and candidate . Used only to test the edit distance in JUnit tests .
41,181
static int sharedPrefixLength ( ByteBuffer a , int aStart , ByteBuffer b , int bStart ) { int i = 0 ; final int max = Math . min ( a . remaining ( ) - aStart , b . remaining ( ) - bStart ) ; aStart += a . position ( ) ; bStart += b . position ( ) ; while ( i < max && a . get ( aStart ++ ) == b . get ( bStart ++ ) ) { i...
Compute the length of the shared prefix between two byte sequences .
41,182
public static ByteBuffer charsToBytes ( CharsetEncoder encoder , CharBuffer chars , ByteBuffer bytes ) throws UnmappableInputException { assert encoder . malformedInputAction ( ) == CodingErrorAction . REPORT ; bytes = clearAndEnsureCapacity ( bytes , ( int ) ( chars . remaining ( ) * encoder . maxBytesPerChar ( ) ) ) ...
Convert chars into bytes .
41,183
public void add ( byte [ ] sequence , int start , int len ) { assert serialized != null : "Automaton already built." ; assert previous == null || len == 0 || compare ( previous , 0 , previousLength , sequence , start , len ) <= 0 : "Input must be sorted: " + Arrays . toString ( Arrays . copyOf ( previous , previousLeng...
Add a single sequence of bytes to the FSA . The input must be lexicographically greater than any previously added sequence .
41,184
public static FSA build ( byte [ ] [ ] input ) { final FSABuilder builder = new FSABuilder ( ) ; for ( byte [ ] chs : input ) { builder . add ( chs , 0 , chs . length ) ; } return builder . complete ( ) ; }
Build a minimal deterministic automaton from a sorted list of byte sequences .
41,185
private int getArcTarget ( int arc ) { arc += ADDRESS_OFFSET ; return ( serialized [ arc ] ) << 24 | ( serialized [ arc + 1 ] & 0xff ) << 16 | ( serialized [ arc + 2 ] & 0xff ) << 8 | ( serialized [ arc + 3 ] & 0xff ) ; }
Returns the address of an arc .
41,186
private void expandAndRehash ( ) { final int [ ] newHashSet = new int [ hashSet . length * 2 ] ; final int bucketMask = ( newHashSet . length - 1 ) ; for ( int j = 0 ; j < hashSet . length ; j ++ ) { final int state = hashSet [ j ] ; if ( state > 0 ) { int slot = hash ( state , stateLength ( state ) ) & bucketMask ; fo...
Reallocate and rehash the hash set .
41,187
private int serialize ( final int activePathIndex ) { expandBuffers ( ) ; final int newState = size ; final int start = activePath [ activePathIndex ] ; final int len = nextArcOffset [ activePathIndex ] - start ; System . arraycopy ( serialized , start , serialized , newState , len ) ; size += len ; return newState ; }
Serialize a given state on the active path .
41,188
private void expandActivePath ( int size ) { if ( activePath . length < size ) { final int p = activePath . length ; activePath = java . util . Arrays . copyOf ( activePath , size ) ; nextArcOffset = java . util . Arrays . copyOf ( nextArcOffset , size ) ; for ( int i = p ; i < size ; i ++ ) { nextArcOffset [ i ] = act...
Append a new mutable state to the active path .
41,189
private void expandBuffers ( ) { if ( this . serialized . length < size + ARC_SIZE * MAX_LABELS ) { serialized = java . util . Arrays . copyOf ( serialized , serialized . length + bufferGrowthSize ) ; serializationBufferReallocations ++ ; } }
Expand internal buffers for the next state .
41,190
public static String applyReplacements ( CharSequence word , LinkedHashMap < String , String > replacements ) { StringBuilder sb = new StringBuilder ( word ) ; for ( final Map . Entry < String , String > e : replacements . entrySet ( ) ) { String key = e . getKey ( ) ; int index = sb . indexOf ( e . getKey ( ) ) ; whil...
Apply partial string replacements from a given map .
41,191
private void computeLabelsIndex ( final FSA fsa ) { final int [ ] countByValue = new int [ 256 ] ; fsa . visitAllStates ( new StateVisitor ( ) { public boolean accept ( int state ) { for ( int arc = fsa . getFirstArc ( state ) ; arc != 0 ; arc = fsa . getNextArc ( arc ) ) countByValue [ fsa . getArcLabel ( arc ) & 0xff...
Compute a set of labels to be integrated with the flags field .
41,192
private void linearizeState ( final FSA fsa , IntStack nodes , IntArrayList linearized , BitSet visited , int node ) { linearized . add ( node ) ; visited . set ( node ) ; for ( int arc = fsa . getFirstArc ( node ) ; arc != 0 ; arc = fsa . getNextArc ( arc ) ) { if ( ! fsa . isArcTerminal ( arc ) ) { final int target =...
Add a state to linearized list .
41,193
private int [ ] computeFirstStates ( IntIntHashMap inlinkCount , int maxStates , int minInlinkCount ) { Comparator < IntIntHolder > comparator = new Comparator < FSAUtils . IntIntHolder > ( ) { public int compare ( IntIntHolder o1 , IntIntHolder o2 ) { int v = o1 . a - o2 . a ; return v == 0 ? ( o1 . b - o2 . b ) : v ;...
Compute the set of states that should be linearized first to minimize other states goto length .
41,194
private IntIntHashMap computeInlinkCount ( final FSA fsa ) { IntIntHashMap inlinkCount = new IntIntHashMap ( ) ; BitSet visited = new BitSet ( ) ; IntStack nodes = new IntStack ( ) ; nodes . push ( fsa . getRootNode ( ) ) ; while ( ! nodes . isEmpty ( ) ) { final int node = nodes . pop ( ) ; if ( visited . get ( node )...
Compute in - link count for each state .
41,195
private int emitNodeArcs ( FSA fsa , OutputStream os , final int state , final int nextState ) throws IOException { int offset = 0 ; for ( int arc = fsa . getFirstArc ( state ) ; arc != 0 ; arc = fsa . getNextArc ( arc ) ) { int targetOffset ; final int target ; if ( fsa . isArcTerminal ( arc ) ) { target = 0 ; targetO...
Emit all arcs of a single node .
41,196
static int writeVInt ( byte [ ] array , int offset , int value ) { assert value >= 0 : "Can't v-code negative ints." ; while ( value > 0x7F ) { array [ offset ++ ] = ( byte ) ( 0x80 | ( value & 0x7F ) ) ; value >>= 7 ; } array [ offset ++ ] = ( byte ) value ; return offset ; }
Write a v - int to a byte array .
41,197
public static IntIntHashMap rightLanguageForAllStates ( final FSA fsa ) { final IntIntHashMap numbers = new IntIntHashMap ( ) ; fsa . visitInPostOrder ( new StateVisitor ( ) { public boolean accept ( int state ) { int thisNodeNumber = 0 ; for ( int arc = fsa . getFirstArc ( state ) ; arc != 0 ; arc = fsa . getNextArc (...
Calculate the size of right language for each state in an FSA . The right language is the number of sequences encoded from a given node in the automaton .
41,198
static int readVInt ( byte [ ] array , int offset ) { byte b = array [ offset ] ; int value = b & 0x7F ; for ( int shift = 7 ; b < 0 ; shift += 7 ) { b = array [ ++ offset ] ; value |= ( b & 0x7F ) << shift ; } return value ; }
Read a v - int .
41,199
public static Dictionary read ( Path location ) throws IOException { final Path metadata = DictionaryMetadata . getExpectedMetadataLocation ( location ) ; try ( InputStream fsaStream = Files . newInputStream ( location ) ; InputStream metadataStream = Files . newInputStream ( metadata ) ) { return read ( fsaStream , me...
Attempts to load a dictionary using the path to the FSA file and the expected metadata extension .