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 , instrumentationActions ) ; } | 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 discoveryClassVisitor . getTransformationParameters ( ) . build ( ) ; } | 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 = new StateTrackingClassVisitor ( classWriter , instrumentationActions ) ; classReader . accept ( localVariableStateEmitterTestClassVisitor , 0 ) ; return classWriter . toByteArray ( ) ; } | 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 ( end ) ; LocalVariableScopeData . LineNumbers scopeWithLineNumbers = getLineNumbers ( scope , enclosingTry , start , end ) ; return new LocalVariableScope ( scope . var , scope . name , VariableType . getByDesc ( scope . desc ) , scopeWithLineNumbers . startLine , scopeWithLineNumbers . endLine , startIndex , endIndex , getVarReferencesBeforeStart ( scope ) ) ; } | 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 IllegalArgumentException ( "Input begins or ends in an invalid character." ) ; } return new IBAN ( toPlain ( input ) ) ; } | 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 ( ' ' ) ; } sb . append ( value , i , length ) ; return sb . toString ( ) ; } | 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 must be '0'." ) ; } return 98 - checksum ( input ) ; } | 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 . listenThread = null ; } | 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 OutputStreamWriter ( this . socket . getOutputStream ( ) ) ) ; this . listenThread = new SocketThread ( this . in , this , this . resultParser , this . daemon ) ; this . listenThread . start ( ) ; if ( lastWatch != null ) { this . syncCommand ( lastWatch , WatchObject . class ) ; } } } | 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 i = 0 ; i < array . length ( ) ; i ++ ) { objects . add ( ( T ) this . parse ( array . getJSONObject ( i ) ) ) ; } return objects ; } catch ( final JSONException e ) { throw new ParseException ( "Parsing failed" , e ) ; } } | 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 , current ) ; if ( transition != null ) { current = this . transition ( stateful , current , event , transition , args ) ; } else { if ( logger . isDebugEnabled ( ) ) logger . debug ( "{}({})::{}({})->{}/noop" , this . name , stateful . getClass ( ) . getSimpleName ( ) , current . getName ( ) , event , current . getName ( ) ) ; if ( current . isBlocking ( ) ) { this . setCurrent ( stateful , current , current ) ; throw new WaitAndRetryException ( this . retryInterval ) ; } } return current ; } catch ( RetryException re ) { logger . warn ( "{}({})::Retrying event" , this . name , stateful ) ; if ( WaitAndRetryException . class . isInstance ( re ) ) { try { Thread . sleep ( ( ( WaitAndRetryException ) re ) . getWait ( ) ) ; } catch ( InterruptedException ie ) { throw new RuntimeException ( ie ) ; } } attempts ++ ; } } logger . error ( "{}({})::Unable to process event" , this . name , stateful ) ; throw new TooBusyException ( ) ; } | 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 ) { } } return field ; } | 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 LinkedList < Annotation > ( ) ; for ( java . lang . annotation . Annotation annotation : annotations ) { Annotation clone = cloneAnnotation ( parameterConstPool , annotation ) ; if ( RequestParam . class . isAssignableFrom ( annotation . annotationType ( ) ) ) { if ( "" . equals ( ( ( RequestParam ) annotation ) . value ( ) ) && ! StringUtils . isEmpty ( parmName ) ) { MemberValue value = createMemberValue ( parameterConstPool , parmName ) ; clone . addMemberValue ( "value" , value ) ; } } ctParmAnnotations . add ( clone ) ; } return ctParmAnnotations . toArray ( new Annotation [ ] { } ) ; } | 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 . getBeanDefinitionNames ( ) ) { BeanDefinition bf = reg . getBeanDefinition ( bfName ) ; if ( bf . isAbstract ( ) ) { logger . debug ( "Skipping abstract bean " + bfName ) ; continue ; } Class < ? > clazz = getClassFromBeanDefinition ( bf , reg ) ; if ( clazz == null ) { logger . debug ( "Unable to resolve class for bean " + bfName ) ; continue ; } if ( ReflectionUtils . isAnnotationPresent ( clazz , StatefulController . class ) ) { mapEntityWithController ( controllerToEntityMapping , entityToControllerMappings , bfName , clazz ) ; } else if ( RepositoryFactoryBeanSupport . class . isAssignableFrom ( clazz ) ) { mapEntityToRepository ( entityToRepositoryMapping , bfName , bf ) ; } } } | 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 RuntimeException ( e ) ; } } | 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 RuntimeException ( e ) ; } } | 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 ( ) , constPool ) ; for ( Method method : clazz . getDeclaredMethods ( ) ) { MemberValue memberVal = null ; if ( method . getReturnType ( ) . isArray ( ) ) { List < MemberValue > memberVals = new LinkedList < MemberValue > ( ) ; for ( Object val : ( Object [ ] ) method . invoke ( annotation ) ) { memberVals . add ( createMemberValue ( constPool , val ) ) ; } memberVal = new ArrayMemberValue ( constPool ) ; ( ( ArrayMemberValue ) memberVal ) . setValue ( memberVals . toArray ( new MemberValue [ ] { } ) ) ; } else { memberVal = createMemberValue ( constPool , method . invoke ( annotation ) ) ; } annot . addMemberValue ( method . getName ( ) , memberVal ) ; } return annot ; } | 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 . getContext ( ) ; Resources r = Resources . getSystem ( ) ; DisplayMetrics displayMetrics ; float size = mMaxTextSize ; float high = size ; float low = 0 ; if ( context != null ) { r = context . getResources ( ) ; } displayMetrics = r . getDisplayMetrics ( ) ; mPaint . set ( mTextView . getPaint ( ) ) ; mPaint . setTextSize ( size ) ; if ( ( mMaxLines == 1 && mPaint . measureText ( text ) > targetWidth ) || getLineCount ( text , mPaint , size , targetWidth , displayMetrics ) > mMaxLines ) { size = getTextSize ( text , mPaint , targetWidth , mMaxLines , low , high , mPrecision , displayMetrics ) ; } if ( size < mMinTextSize ) { size = mMinTextSize ; } mTextView . setTextSize ( TypedValue . COMPLEX_UNIT_PX , size ) ; } } | 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 , attrs ) ; return mDecorFactory . onViewCreated ( view , name , null , view . getContext ( ) , attrs ) ; } | 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 ( parsable ) . getRecord ( ) ; } | 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 > > pathNodes = new HashMap < > ( ) ; for ( Dissector dissector : allDissectors ) { final String inputType = dissector . getInputType ( ) ; if ( inputType == null ) { LOG . error ( "Dissector returns null on getInputType(): [{}]" , dissector . getClass ( ) . getCanonicalName ( ) ) ; return Collections . emptyList ( ) ; } final List < String > outputs = dissector . getPossibleOutput ( ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "------------------------------------" ) ; LOG . debug ( "Possible: Dissector IN {}" , inputType ) ; for ( String output : outputs ) { LOG . debug ( "Possible: , output ) ; } } List < String > existingOutputs = pathNodes . get ( inputType ) ; if ( existingOutputs != null ) { outputs . addAll ( existingOutputs ) ; } pathNodes . put ( inputType , outputs ) ; } findAdditionalPossiblePaths ( pathNodes , paths , "" , rootType , maxDepth , "" ) ; for ( Entry < String , Set < String > > typeRemappingSet : typeRemappings . entrySet ( ) ) { for ( String typeRemapping : typeRemappingSet . getValue ( ) ) { String remappedPath = typeRemapping + ':' + typeRemappingSet . getKey ( ) ; LOG . debug ( "Adding remapped path: {}" , remappedPath ) ; paths . add ( remappedPath ) ; findAdditionalPossiblePaths ( pathNodes , paths , typeRemappingSet . getKey ( ) , typeRemapping , maxDepth - 1 , "" ) ; } } return paths ; } | 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 . contains ( "%u" ) ) { cookedInput = VALID_NON_STANDARD . matcher ( cookedInput ) . replaceAll ( "%$1%$2" ) ; cookedInput = CHOPPED_NON_STANDARD . matcher ( cookedInput ) . replaceAll ( "" ) ; } } try { return URLDecoder . decode ( cookedInput , "UTF-16" ) ; } catch ( UnsupportedEncodingException e ) { return null ; } } | 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 . getClass ( ) . getCanonicalName ( ) , e ) ; } return null ; } | 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 HashSet < > ( optionalFields ) ; optionalAndDefaultFields . addAll ( User . UserField . getDefaultFields ( ) ) ; addFieldsParam ( pathBuilder , User . class , optionalAndDefaultFields ) ; } return converter . readDocument ( getDataStream ( pathBuilder . toString ( ) ) , User . class ) ; } | 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 = 0 ; i < length ; i += 1 ) { names [ i ] = fields [ i ] . getName ( ) ; } return names ; } | 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 ) charset = determineCharset ( text ) ; String mimeCharset = charset . name ( ) ; if ( mimeCharset == null ) { throw new IllegalArgumentException ( "Unsupported charset" ) ; } byte [ ] bytes = encode ( text , charset ) ; if ( encoding == null ) encoding = determineEncoding ( bytes , usage ) ; if ( encoding == Encoding . B ) { String prefix = ENC_WORD_PREFIX + mimeCharset + "?B?" ; return encodeB ( prefix , text , usedCharacters , charset , bytes ) ; } else { String prefix = ENC_WORD_PREFIX + mimeCharset + "?Q?" ; return encodeQ ( prefix , text , usage , usedCharacters , charset , bytes ) ; } } | 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 [ data >> 18 & 0x3f ] ) ; sb . append ( ( char ) BASE64_TABLE [ data >> 12 & 0x3f ] ) ; sb . append ( ( char ) BASE64_TABLE [ data >> 6 & 0x3f ] ) ; sb . append ( ( char ) BASE64_TABLE [ data & 0x3f ] ) ; } if ( idx == end - 2 ) { int data = ( bytes [ idx ] & 0xff ) << 16 | ( bytes [ idx + 1 ] & 0xff ) << 8 ; sb . append ( ( char ) BASE64_TABLE [ data >> 18 & 0x3f ] ) ; sb . append ( ( char ) BASE64_TABLE [ data >> 12 & 0x3f ] ) ; sb . append ( ( char ) BASE64_TABLE [ data >> 6 & 0x3f ] ) ; sb . append ( ( char ) BASE64_PAD ) ; } else if ( idx == end - 1 ) { int data = ( bytes [ idx ] & 0xff ) << 16 ; sb . append ( ( char ) BASE64_TABLE [ data >> 18 & 0x3f ] ) ; sb . append ( ( char ) BASE64_TABLE [ data >> 12 & 0x3f ] ) ; sb . append ( ( char ) BASE64_PAD ) ; sb . append ( ( char ) BASE64_PAD ) ; } return sb . toString ( ) ; } | 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 . append ( '_' ) ; } else if ( ! qChars . get ( v ) ) { sb . append ( '=' ) ; sb . append ( hexDigit ( v >>> 4 ) ) ; sb . append ( hexDigit ( v & 0xf ) ) ; } else { sb . append ( ( char ) v ) ; } } return sb . toString ( ) ; } | 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_CHARS . get ( ch ) ) return false ; } prev = ch ; } return true ; } | 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 change should Resty adopt HttpClient and is the reason why this method is not a static one . |
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 ( ) . newDocumentBuilder ( ) . parse ( is ) ; } catch ( SAXException e ) { e . printStackTrace ( ) ; } catch ( ParserConfigurationException e ) { e . printStackTrace ( ) ; } inputStream . close ( ) ; } return document ; } | 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 ) { Site s = new Site ( ) ; s . root = rootUri ; s . login = login ; s . pwd = pwd ; sites . add ( s ) ; } } | 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 ) . append ( ": " ) . append ( val ) . append ( "\n" ) ; } } } return sb . toString ( ) ; } | 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 ( ) ; inputStream . close ( ) ; return aFileName ; } | 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 . forName ( charsetString ) ; } catch ( IllegalCharsetNameException e ) { e . printStackTrace ( ) ; } catch ( IllegalArgumentException e ) { e . printStackTrace ( ) ; } } } return 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 DivisionOperation ) { text = " / " ; } else { LOGGER . warn ( "Unsupported expression of type {}" , exp . getClass ( ) ) ; text = "" ; } return text ; } | 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 ) { accumulator . constantOperand ( ( ConstantOperand ) current ) ; } else if ( current instanceof DiceOperand ) { accumulator . diceOperand ( ( DiceOperand ) current ) ; } else { LOGGER . warn ( "Unsupported expression of type {}" , current . getClass ( ) ) ; } } return accumulator . getValue ( ) ; } | 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 . hasNext ( ) ) { final USBStorageDevice device = itConnectedDevices . next ( ) ; if ( currentConnectedDevices . contains ( device ) ) { currentConnectedDevices . remove ( device ) ; } else { removedDevices . add ( device ) ; itConnectedDevices . remove ( ) ; } } connectedDevices . addAll ( currentConnectedDevices ) ; } currentConnectedDevices . forEach ( device -> sendEventToListeners ( new USBStorageEvent ( device , DeviceEventType . CONNECTED ) ) ) ; removedDevices . forEach ( device -> sendEventToListeners ( new USBStorageEvent ( device , DeviceEventType . REMOVED ) ) ) ; } | 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 ( ) != 1 || isAlphabetic ( wordToCheck . charAt ( 0 ) ) ; return wordToCheck . length ( ) > 0 && ( ! dictionaryMetadata . isIgnoringPunctuation ( ) || isAlphabetic ) && ( ! dictionaryMetadata . isIgnoringNumbers ( ) || containsNoDigit ( wordToCheck ) ) && ! ( dictionaryMetadata . isIgnoringCamelCase ( ) && isCamelCase ( wordToCheck ) ) && ! ( dictionaryMetadata . isIgnoringAllUppercase ( ) && isAlphabetic && isAllUppercase ( wordToCheck ) ) && ! isInDictionary ( wordToCheck ) && ( ! dictionaryMetadata . isConvertingCase ( ) || ! ( ! isMixedCase ( wordToCheck ) && ( isInDictionary ( wordToCheck . toLowerCase ( dictionaryMetadata . getLocale ( ) ) ) || isAllUppercase ( wordToCheck ) && isInDictionary ( initialUppercase ( wordToCheck ) ) ) ) ) ; } | 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 && match . kind == EXACT_MATCH ) { containsSeparators = false ; for ( int i = 0 ; i < word . length ( ) ; i ++ ) { if ( word . charAt ( i ) == dictionaryMetadata . getSeparator ( ) ) { containsSeparators = true ; break ; } } } if ( match . kind == EXACT_MATCH && ! containsSeparators ) { return true ; } return containsSeparators && match . kind == SEQUENCE_IS_A_PREFIX && byteBuffer . remaining ( ) > 0 && fsa . getArc ( match . node , dictionaryMetadata . getSeparator ( ) ) != 0 ; } | 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 = matcher . match ( matchResult , byteBuffer . array ( ) , 0 , byteBuffer . remaining ( ) , rootNode ) ; if ( match . kind == SEQUENCE_IS_A_PREFIX ) { final int arc = fsa . getArc ( match . node , separator ) ; if ( arc != 0 && ! fsa . isArcFinal ( arc ) ) { finalStatesIterator . restartFrom ( fsa . getEndNode ( arc ) ) ; if ( finalStatesIterator . hasNext ( ) ) { final ByteBuffer bb = finalStatesIterator . next ( ) ; final byte [ ] ba = bb . array ( ) ; final int bbSize = bb . remaining ( ) ; return ba [ bbSize - 1 ] - FIRST_RANGE_CODE ; } } } return 0 ; } | 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 , dictionaryMetadata . getInputConversionPairs ( ) ) ; } if ( ! isInDictionary ( wordToCheck ) && dictionaryMetadata . isSupportingRunOnWords ( ) ) { for ( int i = 1 ; i < wordToCheck . length ( ) ; i ++ ) { final CharSequence firstCh = wordToCheck . subSequence ( 0 , i ) ; if ( isInDictionary ( firstCh ) && isInDictionary ( wordToCheck . subSequence ( i , wordToCheck . length ( ) ) ) ) { if ( dictionaryMetadata . getOutputConversionPairs ( ) . isEmpty ( ) ) { candidates . add ( firstCh + " " + wordToCheck . subSequence ( i , wordToCheck . length ( ) ) ) ; } else { candidates . add ( DictionaryLookup . applyReplacements ( firstCh + " " + wordToCheck . subSequence ( i , wordToCheck . length ( ) ) , dictionaryMetadata . getOutputConversionPairs ( ) ) . toString ( ) ) ; } } } } return candidates ; } | 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 ( ) ) ; } return resultSuggestions ; } | 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 [ candIndex - 1 ] && wordProcessed [ wordIndex - 1 ] == candidate [ candIndex ] ) { a = hMatrix . get ( i - 1 , j - 1 ) ; b = hMatrix . get ( i + 1 , j ) ; c = hMatrix . get ( i , j + 1 ) ; result = 1 + min ( a , b , c ) ; } else { a = hMatrix . get ( i , j ) ; b = hMatrix . get ( i + 1 , j ) ; c = hMatrix . get ( i , j + 1 ) ; result = 1 + min ( a , b , c ) ; } hMatrix . set ( i + 1 , j + 1 , result ) ; return result ; } | 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 ( dictionaryMetadata . isIgnoringDiacritics ( ) ) { String xn = Normalizer . normalize ( Character . toString ( x ) , Form . NFD ) ; String yn = Normalizer . normalize ( Character . toString ( y ) , Form . NFD ) ; if ( xn . charAt ( 0 ) == yn . charAt ( 0 ) ) { return true ; } if ( dictionaryMetadata . isConvertingCase ( ) ) { if ( Character . isLetter ( xn . charAt ( 0 ) ) ) { boolean testNeeded = Character . isLowerCase ( xn . charAt ( 0 ) ) != Character . isLowerCase ( yn . charAt ( 0 ) ) ; if ( testNeeded ) { return Character . toLowerCase ( xn . charAt ( 0 ) ) == Character . toLowerCase ( yn . charAt ( 0 ) ) ; } } } return xn . charAt ( 0 ) == yn . charAt ( 0 ) ; } return false ; } | 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 ; for ( int i = l ; i <= u ; i ++ , wi ++ ) { if ( ( d = ed ( i , depth , wi , candIndex ) ) < minEd ) { minEd = d ; } } return minEd ; } | 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 ] == wordProcessed [ wordIndex + i ] ) { i ++ ; } if ( i == rep . length ) { return i ; } } } return 0 ; } | 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 ++ ; } return 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 ( ) ) ) ; chars . mark ( ) ; encoder . reset ( ) ; CoderResult cr = encoder . encode ( chars , bytes , true ) ; if ( cr . isError ( ) ) { chars . reset ( ) ; try { cr . throwException ( ) ; } catch ( CharacterCodingException e ) { throw new UnmappableInputException ( "Input cannot be mapped to characters using encoding " + encoder . charset ( ) . name ( ) + ": " + Arrays . toString ( toArray ( bytes ) ) , e ) ; } } assert cr . isUnderflow ( ) ; cr = encoder . flush ( bytes ) ; assert cr . isUnderflow ( ) ; bytes . flip ( ) ; chars . reset ( ) ; return bytes ; } | 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 , previousLength ) ) + " >= " + Arrays . toString ( Arrays . copyOfRange ( sequence , start , len ) ) ; assert setPrevious ( sequence , start , len ) ; final int commonPrefix = commonPrefix ( sequence , start , len ) ; expandActivePath ( len ) ; for ( int i = activePathLen - 1 ; i > commonPrefix ; i -- ) { final int frozenState = freezeState ( i ) ; setArcTarget ( nextArcOffset [ i - 1 ] - ARC_SIZE , frozenState ) ; nextArcOffset [ i ] = activePath [ i ] ; } for ( int i = commonPrefix + 1 , j = start + commonPrefix ; i <= len ; i ++ ) { final int p = nextArcOffset [ i - 1 ] ; serialized [ p + FLAGS_OFFSET ] = ( byte ) ( i == len ? BIT_ARC_FINAL : 0 ) ; serialized [ p + LABEL_OFFSET ] = sequence [ j ++ ] ; setArcTarget ( p , i == len ? TERMINAL_STATE : activePath [ i ] ) ; nextArcOffset [ i - 1 ] = p + ARC_SIZE ; } this . activePathLen = len ; } | 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 ; for ( int i = 0 ; newHashSet [ slot ] > 0 ; ) { slot = ( slot + ( ++ i ) ) & bucketMask ; } newHashSet [ slot ] = state ; } } this . hashSet = newHashSet ; } | 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 ] = activePath [ i ] = allocateState ( MAX_LABELS ) ; } } } | 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 ( ) ) ; while ( index != - 1 ) { sb . replace ( index , index + key . length ( ) , e . getValue ( ) ) ; index = sb . indexOf ( key , index + key . length ( ) ) ; } } return sb . toString ( ) ; } | 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 ] ++ ; return true ; } } ) ; Comparator < IntIntHolder > comparator = new Comparator < IntIntHolder > ( ) { public int compare ( IntIntHolder o1 , IntIntHolder o2 ) { int countDiff = o2 . b - o1 . b ; if ( countDiff == 0 ) { countDiff = o1 . a - o2 . a ; } return countDiff ; } } ; TreeSet < IntIntHolder > labelAndCount = new TreeSet < IntIntHolder > ( comparator ) ; for ( int label = 0 ; label < countByValue . length ; label ++ ) { if ( countByValue [ label ] > 0 ) { labelAndCount . add ( new IntIntHolder ( label , countByValue [ label ] ) ) ; } } labelsIndex = new byte [ 1 + Math . min ( labelAndCount . size ( ) , CFSA2 . LABEL_INDEX_SIZE ) ] ; labelsInvIndex = new int [ 256 ] ; for ( int i = labelsIndex . length - 1 ; i > 0 && ! labelAndCount . isEmpty ( ) ; i -- ) { IntIntHolder p = labelAndCount . first ( ) ; labelAndCount . remove ( p ) ; labelsInvIndex [ p . a ] = i ; labelsIndex [ i ] = ( byte ) p . a ; } } | 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 = fsa . getEndNode ( arc ) ; if ( ! visited . get ( target ) ) nodes . push ( 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 ; } } ; PriorityQueue < IntIntHolder > stateInlink = new PriorityQueue < IntIntHolder > ( 1 , comparator ) ; IntIntHolder scratch = new IntIntHolder ( ) ; for ( IntIntCursor c : inlinkCount ) { if ( c . value > minInlinkCount ) { scratch . a = c . value ; scratch . b = c . key ; if ( stateInlink . size ( ) < maxStates || comparator . compare ( scratch , stateInlink . peek ( ) ) > 0 ) { stateInlink . add ( new IntIntHolder ( c . value , c . key ) ) ; if ( stateInlink . size ( ) > maxStates ) { stateInlink . remove ( ) ; } } } } int [ ] states = new int [ stateInlink . size ( ) ] ; for ( int position = states . length ; ! stateInlink . isEmpty ( ) ; ) { IntIntHolder i = stateInlink . remove ( ) ; states [ -- position ] = i . b ; } return states ; } | 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 ) ) continue ; visited . set ( node ) ; for ( int arc = fsa . getFirstArc ( node ) ; arc != 0 ; arc = fsa . getNextArc ( arc ) ) { if ( ! fsa . isArcTerminal ( arc ) ) { final int target = fsa . getEndNode ( arc ) ; inlinkCount . putOrAdd ( target , 1 , 1 ) ; if ( ! visited . get ( target ) ) nodes . push ( target ) ; } } } return inlinkCount ; } | 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 ; targetOffset = 0 ; } else { target = fsa . getEndNode ( arc ) ; targetOffset = offsets . get ( target ) ; } int flags = 0 ; if ( fsa . isArcFinal ( arc ) ) { flags |= BIT_FINAL_ARC ; } if ( fsa . getNextArc ( arc ) == 0 ) { flags |= BIT_LAST_ARC ; } if ( targetOffset != 0 && target == nextState ) { flags |= BIT_TARGET_NEXT ; targetOffset = 0 ; } offset += emitArc ( os , flags , fsa . getArcLabel ( arc ) , targetOffset ) ; } return offset ; } | 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 ( arc ) ) { thisNodeNumber += ( fsa . isArcFinal ( arc ) ? 1 : 0 ) + ( fsa . isArcTerminal ( arc ) ? 0 : numbers . get ( fsa . getEndNode ( arc ) ) ) ; } numbers . put ( state , thisNodeNumber ) ; return true ; } } ) ; return numbers ; } | 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 , metadataStream ) ; } } | Attempts to load a dictionary using the path to the FSA file and the expected metadata extension . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.