idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
38,000
private String normlizeQuotes ( String str ) { if ( str . length ( ) > 1 && str . charAt ( 0 ) == '\'' && str . charAt ( str . length ( ) - 1 ) == '\'' ) { return '\"' + str . substring ( 1 , str . length ( ) - 1 ) + '\"' ; } return str ; }
Convert single quotes to double quotes .
38,001
private ArrayList < Unit > unit ( CssFormatter formatter , ArrayList < Unit > list ) { for ( int i = 0 ; i < operands . size ( ) ; i ++ ) { Expression exp = operands . get ( i ) ; if ( exp . getClass ( ) == Operation . class ) { Operation op = ( Operation ) exp ; switch ( op . operator ) { case '*' : case '/' : list = op . unit ( formatter , list ) ; break ; default : } } else { String unitStr = exp . unit ( formatter ) ; if ( ! unitStr . isEmpty ( ) ) { if ( list == null ) { list = new ArrayList < > ( ) ; } Unit unit = null ; for ( int j = 0 ; j < list . size ( ) ; j ++ ) { Unit unitLoop = list . get ( j ) ; if ( unitLoop . unit . equals ( unitStr ) ) { unit = unitLoop ; break ; } } if ( unit == null ) { unit = new Unit ( unitStr ) ; list . add ( unit ) ; } if ( i == 0 || operator == '*' ) { unit . numerator ++ ; } else { unit . denominator ++ ; } } } } return list ; }
Calculate the unit if there are different units . It use the numerator and denominator count .
38,002
void add ( K key , V value ) { List < V > rules = map . get ( key ) ; if ( rules == null ) { rules = new ArrayList < > ( ) ; map . put ( key , rules ) ; } rules . add ( value ) ; }
Add a value to this map . If the map previously contained a mapping for the key then there are two values now .
38,003
List < V > get ( K key ) { List < V > result = map . get ( key ) ; if ( parent != null ) { List < V > resultParent = parent . get ( key ) ; if ( result == null ) { return resultParent ; } else if ( resultParent == null ) { return result ; } else { for ( V value : resultParent ) { if ( ! result . contains ( value ) ) { result . add ( value ) ; } } } } return result ; }
Get all values for the given key . If no key exists then null is return .
38,004
void addAll ( HashMultimap < K , V > m ) { if ( m == this ) { return ; } for ( Entry < K , List < V > > entry : m . map . entrySet ( ) ) { K key = entry . getKey ( ) ; List < V > rules = map . get ( key ) ; if ( rules == null ) { rules = new ArrayList < > ( ) ; map . put ( key , rules ) ; } for ( V value : entry . getValue ( ) ) { if ( ! rules . contains ( value ) ) { rules . add ( value ) ; } } } }
Add all values of the mappings from the specified map to this map .
38,005
private int parseRewriteUrl ( ) { String rewrite = options . get ( Less . REWRITE_URLS ) ; if ( rewrite != null ) { switch ( rewrite . toLowerCase ( ) ) { case "off" : return 0 ; case "local" : return 1 ; case "all" : return 2 ; } } return 0 ; }
Parse the parameter rewrite URL
38,006
void addOutput ( ) { if ( output != null ) { outputs . addLast ( output ) ; } output = state . pool . get ( ) ; }
Add a new output buffer to the formatter .
38,007
void freeOutput ( ) { state . pool . free ( output ) ; output = outputs . size ( ) > 0 ? outputs . removeLast ( ) : null ; }
Release an output and delete it .
38,008
String releaseOutput ( ) { if ( output == null ) { return "" ; } String str = output . toString ( ) ; freeOutput ( ) ; return str ; }
Release an output buffer return the content and restore the previous output .
38,009
Expression getVariable ( String name ) { for ( int i = state . stackIdx - 1 ; i >= 0 ; i -- ) { Expression variable = state . stack . get ( i ) . getVariable ( name ) ; if ( variable != null ) { return variable ; } } if ( name . equals ( "@arguments" ) ) { for ( int i = state . stackIdx - 1 ; i >= 0 ; i -- ) { Scope scope = state . stack . get ( i ) ; if ( scope . parameters != null ) { Operation params = new Operation ( scope . mixin , ' ' ) ; for ( Expression expr : scope . parameters . values ( ) ) { if ( expr . getClass ( ) == Operation . class && scope . parameters . size ( ) == 1 ) { return expr ; } params . addOperand ( expr ) ; } return params ; } } } return null ; }
Get a variable expression from the current stack
38,010
void addMixin ( Rule mixin , Map < String , Expression > parameters , Map < String , Expression > variables ) { int idx = state . stackIdx ++ ; Scope scope ; if ( state . stack . size ( ) <= idx ) { scope = new Scope ( ) ; state . stack . add ( scope ) ; } else { scope = state . stack . get ( idx ) ; scope . returns . clear ( ) ; } scope . mixin = mixin ; scope . parameters = parameters ; scope . variables = variables ; }
Add the scope of a mixin to the stack .
38,011
void removeMixin ( ) { int idx = state . stackIdx - 1 ; Scope current = state . stack . get ( idx ) ; if ( idx > 0 ) { Scope previous = state . stack . get ( idx - 1 ) ; Map < String , Expression > currentReturn = previous . returns ; Map < String , Expression > vars = current . variables ; if ( vars != null ) { for ( Entry < String , Expression > entry : vars . entrySet ( ) ) { if ( previous . getVariable ( entry . getKey ( ) ) == null ) { currentReturn . put ( entry . getKey ( ) , ValueExpression . eval ( this , entry . getValue ( ) ) ) ; } } } vars = current . returns ; if ( vars != null ) { for ( Entry < String , Expression > entry : vars . entrySet ( ) ) { if ( previous . getVariable ( entry . getKey ( ) ) == null ) { currentReturn . put ( entry . getKey ( ) , ValueExpression . eval ( this , entry . getValue ( ) ) ) ; } } } } state . stackIdx -- ; state . rulesStackModCount ++ ; }
Remove the scope of a mixin .
38,012
void addGuardParameters ( Map < String , Expression > parameters , boolean isDefault ) { isGuard = true ; wasDefaultFunction = false ; guardDefault = isDefault ; if ( parameters != null ) { addMixin ( null , parameters , null ) ; } }
Add the parameters of a guard
38,013
void removeGuardParameters ( Map < String , Expression > parameters ) { if ( parameters != null ) { removeMixin ( ) ; } isGuard = false ; }
remove the parameters of a guard
38,014
boolean containsRule ( Rule rule ) { for ( int i = state . stackIdx - 1 ; i >= 0 ; i -- ) { if ( rule == state . stack . get ( i ) . mixin ) { return true ; } } return false ; }
A mixin inline never it self .
38,015
List < Rule > getMixin ( String name ) { for ( int i = state . stackIdx - 1 ; i >= 0 ; i -- ) { Rule mixin = state . stack . get ( i ) . mixin ; if ( mixin != null ) { List < Rule > rules = mixin . getMixin ( name ) ; if ( rules != null ) { for ( int r = 0 ; r < rules . size ( ) ; r ++ ) { if ( ! containsRule ( rules . get ( r ) ) ) { return rules ; } } } } } return null ; }
Get a nested mixin of a parent rule .
38,016
StringBuilder getOutput ( ) { if ( output == null ) { CssFormatter block = copy ( null ) ; state . results . add ( new CssPlainOutput ( block . output ) ) ; output = block . output ; } return output ; }
Get the current output of the formatter .
38,017
CssFormatter append ( String str ) { if ( inlineMode ) { str = UrlUtils . removeQuote ( str ) ; } output . append ( str ) ; return this ; }
Append a string to the output . In inline mode quotes are removed .
38,018
void appendHex ( int value , int digits ) { if ( digits > 1 ) { appendHex ( value >>> 4 , digits - 1 ) ; } output . append ( DIGITS [ value & 0xF ] ) ; }
Append an hex value to the output .
38,019
CssFormatter append ( double value ) { if ( value == ( int ) value ) { output . append ( Integer . toString ( ( int ) value ) ) ; } else { output . append ( decFormat . format ( value ) ) ; } return this ; }
Append a decimal number to the output .
38,020
CssFormatter startBlock ( String [ ] selectors ) { final List < CssOutput > results = state . results ; if ( blockDeep == 0 ) { output = null ; CssOutput nextOutput = null ; if ( results . size ( ) > 0 && ! "@font-face" . equals ( selectors [ 0 ] ) ) { CssOutput cssOutput = results . get ( results . size ( ) - 1 ) ; if ( Arrays . equals ( selectors , cssOutput . getSelectors ( ) ) ) { nextOutput = cssOutput ; } } CssFormatter block ; if ( nextOutput == null ) { block = copy ( null ) ; if ( selectors [ 0 ] . startsWith ( "@media" ) ) { block . lessExtends = new LessExtendMap ( state . lessExtends ) ; nextOutput = new CssMediaOutput ( selectors , block . output , state . isReference , block . lessExtends ) ; } else { nextOutput = new CssRuleOutput ( selectors , block . output , state . isReference ) ; } results . add ( nextOutput ) ; } else { block = copy ( nextOutput . getOutput ( ) ) ; } block . currentOutput = nextOutput ; block . incInsets ( ) ; block . blockDeep ++ ; return block ; } else { if ( selectors [ 0 ] . startsWith ( "@media" ) ) { CssFormatter block = copy ( null ) ; block . lessExtends = new LessExtendMap ( state . lessExtends ) ; String [ ] sel = new String [ ] { this . currentOutput . getSelectors ( ) [ 0 ] + " and " + selectors [ 0 ] . substring ( 6 ) . trim ( ) } ; block . currentOutput = new CssMediaOutput ( sel , block . output , state . isReference , block . lessExtends ) ; results . add ( block . currentOutput ) ; block . insets . setLength ( 2 ) ; block . blockDeep = 1 ; return block ; } else { if ( blockDeep == 1 && this . currentOutput . getClass ( ) == CssMediaOutput . class ) { CssFormatter block = copy ( null ) ; block . incInsets ( ) ; block . currentOutput = this . currentOutput ; ( ( CssMediaOutput ) this . currentOutput ) . startBlock ( selectors , block . output ) ; block . blockDeep ++ ; return block ; } else { blockDeep ++ ; startBlockImpl ( selectors ) ; return this ; } } } }
Start a new block with a list of selectors .
38,021
void startBlockImpl ( String [ ] selectors ) { for ( int i = 0 ; i < selectors . length ; i ++ ) { if ( i > 0 ) { output . append ( ',' ) ; newline ( ) ; } insets ( ) ; append ( selectors [ i ] ) ; } space ( ) ; output . append ( '{' ) ; newline ( ) ; incInsets ( ) ; }
Output a new block and increment the insets .
38,022
CssFormatter endBlock ( ) { blockDeep -- ; if ( blockDeep == 0 ) { state . pool . free ( insets ) ; insets = null ; inlineMode = false ; } else { if ( blockDeep == 1 && currentOutput . getClass ( ) == CssMediaOutput . class ) { state . pool . free ( insets ) ; insets = null ; inlineMode = false ; } else { endBlockImpl ( ) ; } } return this ; }
Terminate a CSS block .
38,023
CssFormatter comment ( String msg ) { getOutput ( ) . append ( insets ) . append ( msg ) . append ( '\n' ) ; return this ; }
Write a comment . The compress formatter do nothing .
38,024
char read ( ) { try { if ( cachePos < cache . length ( ) ) { return incLineColumn ( cache . charAt ( cachePos ++ ) ) ; } int ch = readCharBlockMarker ( ) ; if ( ch == - 1 ) { throw createException ( "Unexpected end of Less data" ) ; } return incLineColumn ( ch ) ; } catch ( IOException ex ) { throw new LessException ( ex ) ; } }
Read a single character from reader or from back buffer
38,025
void skipLine ( ) { int ch ; do { try { ch = reader . read ( ) ; } catch ( IOException ex ) { throw new LessException ( ex ) ; } incLineColumn ( ch ) ; } while ( ch != '\n' && ch != - 1 ) ; }
Skip all data until a newline occur or an EOF
38,026
static HSL toHSL ( double color ) { long argb = Double . doubleToRawLongBits ( color ) ; double a = alpha ( color ) ; double r = clamp ( ( ( argb >> 32 ) & 0xFFFF ) / ( double ) 0xFF00 ) ; double g = clamp ( ( ( argb >> 16 ) & 0xFFFF ) / ( double ) 0xFF00 ) ; double b = clamp ( ( ( argb >> 0 ) & 0xFFFF ) / ( double ) 0xFF00 ) ; double max = Math . max ( Math . max ( r , g ) , b ) ; double min = Math . min ( Math . min ( r , g ) , b ) ; double h , s , l = ( max + min ) / 2 , d = max - min ; if ( max == min ) { h = s = 0 ; } else { s = l > 0.5 ? d / ( 2 - max - min ) : d / ( max + min ) ; if ( max == r ) { h = ( g - b ) / d + ( g < b ? 6 : 0 ) ; } else if ( max == g ) { h = ( b - r ) / d + 2 ; } else { h = ( r - g ) / d + 4 ; } h /= 6 ; } return new HSL ( h * 360 , s , l , a ) ; }
Create a HSL color .
38,027
static double rgba ( double r , double g , double b , double a ) { return Double . longBitsToDouble ( Math . round ( a * 0xFFFF ) << 48 | ( colorLargeDigit ( r ) << 32 ) | ( colorLargeDigit ( g ) << 16 ) | colorLargeDigit ( b ) ) ; }
Create a color from rgba values
38,028
static double rgb ( int r , int g , int b ) { return Double . longBitsToDouble ( Expression . ALPHA_1 | ( colorLargeDigit ( r ) << 32 ) | ( colorLargeDigit ( g ) << 16 ) | colorLargeDigit ( b ) ) ; }
Create an color value .
38,029
static int argb ( double color ) { long value = Double . doubleToRawLongBits ( color ) ; int result = colorDigit ( ( ( value >>> 48 ) ) / 256.0 ) << 24 ; result |= colorDigit ( ( ( value >> 32 ) & 0xFFFF ) / 256.0 ) << 16 ; result |= colorDigit ( ( ( value >> 16 ) & 0xFFFF ) / 256.0 ) << 8 ; result |= colorDigit ( ( ( value ) & 0xFFFF ) / 256.0 ) ; return result ; }
Convert an color value as long into integer color value
38,030
private static double hslaHue ( double h , double m1 , double m2 ) { h = h < 0 ? h + 1 : ( h > 1 ? h - 1 : h ) ; if ( h * 6 < 1 ) { return m1 + ( m2 - m1 ) * h * 6 ; } else if ( h * 2 < 1 ) { return m2 ; } else if ( h * 3 < 2 ) { return m1 + ( m2 - m1 ) * ( 2F / 3 - h ) * 6 ; } else { return m1 ; } }
Calculate a single color channel of the HSLA function
38,031
static double luminance ( double color ) { long argb = Double . doubleToRawLongBits ( color ) ; double r = ( ( argb >> 32 ) & 0xFFFF ) / ( double ) 0xFF00 ; double g = ( ( argb >> 16 ) & 0xFFFF ) / ( double ) 0xFF00 ; double b = ( ( argb ) & 0xFFFF ) / ( double ) 0xFF00 ; return ( 0.2126 * r ) + ( 0.7152 * g ) + ( 0.0722 * b ) ; }
The less function luminance .
38,032
static double luma ( double color ) { long argb = Double . doubleToRawLongBits ( color ) ; double r = ( ( argb >> 32 ) & 0xFFFF ) / ( double ) 0xFF00 ; double g = ( ( argb >> 16 ) & 0xFFFF ) / ( double ) 0xFF00 ; double b = ( ( argb ) & 0xFFFF ) / ( double ) 0xFF00 ; r = ( r <= 0.03928 ) ? r / 12.92 : Math . pow ( ( ( r + 0.055 ) / 1.055 ) , 2.4 ) ; g = ( g <= 0.03928 ) ? g / 12.92 : Math . pow ( ( ( g + 0.055 ) / 1.055 ) , 2.4 ) ; b = ( b <= 0.03928 ) ? b / 12.92 : Math . pow ( ( ( b + 0.055 ) / 1.055 ) , 2.4 ) ; return 0.2126 * r + 0.7152 * g + 0.0722 * b ; }
The less function luma .
38,033
static double contrast ( double color , double dark , double light , double threshold ) { if ( luma ( dark ) > luma ( light ) ) { double t = light ; light = dark ; dark = t ; } if ( luma ( color ) < threshold ) { return light ; } else { return dark ; } }
The less function contrast .
38,034
static HSV toHSV ( double color ) { long argb = Double . doubleToRawLongBits ( color ) ; double a = alpha ( color ) ; double r = clamp ( ( ( argb >> 32 ) & 0xFFFF ) / ( double ) 0xFF00 ) ; double g = clamp ( ( ( argb >> 16 ) & 0xFFFF ) / ( double ) 0xFF00 ) ; double b = clamp ( ( ( argb >> 0 ) & 0xFFFF ) / ( double ) 0xFF00 ) ; double max = Math . max ( Math . max ( r , g ) , b ) ; double min = Math . min ( Math . min ( r , g ) , b ) ; double h , s , v = max ; double d = max - min ; if ( max == 0 ) { s = 0 ; } else { s = d / max ; } if ( max == min ) { h = 0 ; } else if ( max == r ) { h = ( g - b ) / d + ( g < b ? 6 : 0 ) ; } else if ( max == g ) { h = ( b - r ) / d + 2 ; } else { h = ( r - g ) / d + 4 ; } h /= 6 ; return new HSV ( h * 360 , s , v , a ) ; }
Create a HSV color .
38,035
static double mix ( double color1 , double color2 , double weight ) { long col1 = Double . doubleToRawLongBits ( color1 ) ; long col2 = Double . doubleToRawLongBits ( color2 ) ; int alpha1 = ( int ) ( col1 >>> 48 ) ; int red1 = ( int ) ( col1 >> 32 ) & 0xFFFF ; int green1 = ( int ) ( col1 >> 16 ) & 0xFFFF ; int blue1 = ( int ) ( col1 ) & 0xFFFF ; int alpha2 = ( int ) ( col2 >>> 48 ) ; int red2 = ( int ) ( col2 >> 32 ) & 0xFFFF ; int green2 = ( int ) ( col2 >> 16 ) & 0xFFFF ; int blue2 = ( int ) ( col2 ) & 0xFFFF ; double w = weight * 2 - 1 ; double a = ( alpha1 - alpha2 ) / ( double ) 0XFFFF ; double w1 = ( ( ( w * a == - 1 ) ? w : ( w + a ) / ( 1 + w * a ) ) + 1 ) / 2.0 ; double w2 = 1 - w1 ; long red = Math . round ( red1 * w1 + red2 * w2 ) ; long green = Math . round ( green1 * w1 + green2 * w2 ) ; long blue = Math . round ( blue1 * w1 + blue2 * w2 ) ; long alpha = Math . round ( alpha1 * weight + alpha2 * ( 1 - weight ) ) ; long color = ( alpha << 48 ) | ( red << 32 ) | ( green << 16 ) | ( blue ) ; return Double . longBitsToDouble ( color ) ; }
Calculate the mix color of 2 colors .
38,036
private static double colorBlending ( double color1 , double color2 , int op ) { long argb1 = Double . doubleToRawLongBits ( color1 ) ; long r1 = ( ( argb1 >> 32 ) & 0xFFFF ) ; long g1 = ( ( argb1 >> 16 ) & 0xFFFF ) ; long b1 = ( ( argb1 ) & 0xFFFF ) ; long argb2 = Double . doubleToRawLongBits ( color2 ) ; long r2 = ( ( argb2 >> 32 ) & 0xFFFF ) ; long g2 = ( ( argb2 >> 16 ) & 0xFFFF ) ; long b2 = ( ( argb2 ) & 0xFFFF ) ; r1 = colorBlendingDigit ( r1 , r2 , op ) ; g1 = colorBlendingDigit ( g1 , g2 , op ) ; b1 = colorBlendingDigit ( b1 , b2 , op ) ; argb1 = r1 << 32 | g1 << 16 | b1 ; return Double . longBitsToDouble ( argb1 ) ; }
Color blending operation
38,037
private static long colorBlendingDigit ( long longDigit1 , long longDigit2 , int op ) { switch ( op ) { case MULTIPLY : return longDigit1 * longDigit2 / 0xFF00 ; case SCREEN : return longDigit1 + longDigit2 - longDigit1 * longDigit2 / 0xFF00 ; case OVERLAY : longDigit1 *= 2 ; if ( longDigit1 <= 0xFF00 ) { return colorBlendingDigit ( longDigit1 , longDigit2 , MULTIPLY ) ; } else { return colorBlendingDigit ( longDigit1 - 0xFF00 , longDigit2 , SCREEN ) ; } case SOFTLIGHT : long d = 0xFF00 , e = longDigit1 ; if ( longDigit2 > 0x8000 ) { e = 0xFF00 ; d = ( longDigit1 > 0x4000 ) ? ( long ) ( Math . sqrt ( longDigit1 / ( double ) 0xFF00 ) * 0xFF00 ) : ( ( 16 * longDigit1 - 12 * 0xFF00 ) * longDigit1 / 0xFF00 + 4 * 0xFF00 ) * longDigit1 / 0xFF00 ; } return longDigit1 - ( 0xFF00 - 2 * longDigit2 ) * e * ( d - longDigit1 ) / 0xFF00 / 0xFF00 ; case HARDLIGHT : return colorBlendingDigit ( longDigit2 , longDigit1 , OVERLAY ) ; case DIFFERENCE : return Math . abs ( longDigit1 - longDigit2 ) ; case EXCLUSION : return longDigit1 + longDigit2 - 2 * longDigit1 * longDigit2 / 0xFF00 ; case AVERAGE : return ( longDigit1 + longDigit2 ) / 2 ; case NEGATION : return 0xFF00 - Math . abs ( longDigit1 + longDigit2 - 0xFF00 ) ; default : throw new IllegalArgumentException ( String . valueOf ( op ) ) ; } }
Color blending operation for a single color channel .
38,038
void add ( LessExtend lessExtend , String [ ] mainSelector ) { if ( mainSelector == null || mainSelector [ 0 ] . startsWith ( "@media" ) ) { mainSelector = lessExtend . getSelectors ( ) ; } else { mainSelector = SelectorUtils . merge ( mainSelector , lessExtend . getSelectors ( ) ) ; } String extendingSelector = lessExtend . getExtendingSelector ( ) ; if ( lessExtend . isAll ( ) ) { LessExtendResult extend = new LessExtendResult ( mainSelector , extendingSelector ) ; SelectorTokenizer tokenizer = tokenizers . pollLast ( ) . init ( extendingSelector ) ; do { String token = tokenizer . next ( ) ; if ( token == null ) { break ; } all . add ( token , extend ) ; } while ( true ) ; tokenizers . addLast ( tokenizer ) ; } else { exact . add ( extendingSelector , mainSelector ) ; } }
Is calling on formatting if an extends was include .
38,039
String [ ] concatenateExtends ( String [ ] selectors , boolean isReference ) { selectorList . clear ( ) ; for ( String selector : selectors ) { concatenateExtendsRecursive ( selector , isReference , selector ) ; } if ( isReference ) { return selectorList . toArray ( new String [ selectorList . size ( ) ] ) ; } if ( selectorList . size ( ) > 0 ) { for ( String selector : selectors ) { selectorList . remove ( selector ) ; } if ( selectorList . size ( ) > 0 ) { int off = selectors . length ; selectors = Arrays . copyOf ( selectors , off + selectorList . size ( ) ) ; for ( String str : selectorList ) { selectors [ off ++ ] = str ; } } } return selectors ; }
Add to the given selectors all possible extends and return the resulting selectors .
38,040
private void concatenateExtendsRecursive ( String selector , boolean isReference , String allSelector ) { List < String [ ] > list = exact . get ( selector ) ; if ( list != null ) { for ( String [ ] lessExtend : list ) { for ( String sel : lessExtend ) { boolean needRecursion = selectorList . add ( sel ) ; if ( needRecursion ) { concatenateExtendsRecursive ( sel , isReference , sel ) ; } } } } SelectorTokenizer tokenizer = tokenizers . pollLast ( ) . init ( allSelector ) ; do { String token = tokenizer . next ( ) ; if ( token == null ) { break ; } List < LessExtendResult > results = all . get ( token ) ; if ( results != null ) { for ( LessExtendResult lessExtend : results ) { String extendingSelector = lessExtend . getExtendingSelector ( ) ; if ( selector . contains ( extendingSelector ) ) { for ( String replace : lessExtend . getSelectors ( ) ) { String replacedSelector = selector . replace ( extendingSelector , replace ) ; boolean needRecursion = selectorList . add ( replacedSelector ) ; if ( needRecursion && ! replacedSelector . contains ( extendingSelector ) ) { concatenateExtendsRecursive ( replacedSelector , isReference , replace ) ; } } } } } } while ( true ) ; tokenizers . addLast ( tokenizer ) ; }
Add to the given selector all possible extends to the internal selectorList . This method is call recursive .
38,041
static String addLessExtendsTo ( FormattableContainer container , LessObject obj , String extendSelector ) { String baseSelectors = null ; do { int idx1 = extendSelector . indexOf ( ":extend(" ) ; int idx2 = extendSelector . indexOf ( ')' , idx1 ) ; int idx3 = extendSelector . lastIndexOf ( ',' , idx1 ) ; String selector = extendSelector . substring ( idx3 + 1 , idx1 ) . trim ( ) ; String [ ] baseSelector = new String [ ] { selector } ; if ( baseSelectors == null ) { baseSelectors = selector ; } else { baseSelectors = baseSelectors + ',' + selector ; } String params = extendSelector . substring ( idx1 + 8 , idx2 ) . trim ( ) ; for ( String param : params . split ( "," ) ) { boolean all = param . endsWith ( " all" ) ; if ( all ) { param = param . substring ( 0 , param . length ( ) - 4 ) . trim ( ) ; } container . add ( new LessExtend ( obj , baseSelector , param , all ) ) ; } idx2 ++ ; if ( idx2 < extendSelector . length ( ) ) { while ( idx2 < extendSelector . length ( ) ) { char ch = extendSelector . charAt ( idx2 ++ ) ; switch ( ch ) { case ',' : break ; case ' ' : continue ; default : throw obj . createException ( "Unrecognized input: '" + extendSelector + "'" ) ; } break ; } extendSelector = extendSelector . substring ( idx2 ) . trim ( ) ; if ( extendSelector . length ( ) > 0 ) { continue ; } } break ; } while ( true ) ; return baseSelectors ; }
Parse the extendSelector create the needed LessExtend objects and add it to the container .
38,042
String stringValue ( CssFormatter formatter ) { String str ; try { formatter . addOutput ( ) ; appendTo ( formatter ) ; } catch ( Exception ex ) { throw createException ( ex ) ; } finally { str = formatter . releaseOutput ( ) ; } return str ; }
Get the string value
38,043
public Operation listValue ( CssFormatter formatter ) { Expression expr = unpack ( formatter ) ; if ( expr == this ) { throw createException ( "Exprestion is not a list: " + this ) ; } return expr . listValue ( formatter ) ; }
Get the value as a list
38,044
Expression unpack ( CssFormatter formatter ) { Expression unpack = this ; do { if ( unpack . getClass ( ) == FunctionExpression . class && ( ( FunctionExpression ) unpack ) . toString ( ) . isEmpty ( ) ) { unpack = ( ( FunctionExpression ) unpack ) . get ( 0 ) ; continue ; } if ( unpack . getClass ( ) == VariableExpression . class ) { unpack = ( ( VariableExpression ) unpack ) . getValue ( formatter ) ; continue ; } break ; } while ( true ) ; return unpack ; }
Unpack this expression to return the core expression
38,045
static double getColor ( Expression param , CssFormatter formatter ) throws LessException { switch ( param . getDataType ( formatter ) ) { case Expression . COLOR : case Expression . RGBA : return param . doubleValue ( formatter ) ; } throw new LessException ( "Not a color: " + param ) ; }
Get the color value of the expression or fire an exception if not a color .
38,046
static void dataUri ( CssFormatter formatter , String relativeUrlStr , final String urlString , String type ) throws IOException { String urlStr = removeQuote ( urlString ) ; InputStream input ; try { input = formatter . getReaderFactory ( ) . openStream ( formatter . getBaseURL ( ) , urlStr , relativeUrlStr ) ; } catch ( Exception e ) { boolean quote = urlString != urlStr ; String rewrittenUrl ; if ( formatter . isRewriteUrl ( urlStr ) ) { URL relativeUrl = new URL ( relativeUrlStr ) ; relativeUrl = new URL ( relativeUrl , urlStr ) ; rewrittenUrl = relativeUrl . getPath ( ) ; rewrittenUrl = quote ? urlString . charAt ( 0 ) + rewrittenUrl + urlString . charAt ( 0 ) : rewrittenUrl ; } else { rewrittenUrl = urlString ; } formatter . append ( "url(" ) . append ( rewrittenUrl ) . append ( ')' ) ; return ; } ByteArrayOutputStream buffer = new ByteArrayOutputStream ( ) ; int count ; byte [ ] data = new byte [ 16384 ] ; while ( ( count = input . read ( data , 0 , data . length ) ) > 0 ) { buffer . write ( data , 0 , count ) ; } input . close ( ) ; byte [ ] bytes = buffer . toByteArray ( ) ; if ( bytes . length >= 32 * 1024 ) { formatter . append ( "url(" ) . append ( urlString ) . append ( ')' ) ; } else { dataUri ( formatter , bytes , urlStr , type ) ; } }
Implementation of the function data - uri .
38,047
static void dataUri ( CssFormatter formatter , byte [ ] bytes , String urlStr , String type ) { if ( type == null ) { switch ( urlStr . substring ( urlStr . lastIndexOf ( '.' ) + 1 ) ) { case "gif" : type = "image/gif;base64" ; break ; case "png" : type = "image/png;base64" ; break ; case "jpg" : case "jpeg" : type = "image/jpeg;base64" ; break ; default : type = "text/html" ; } } else { type = removeQuote ( type ) ; } if ( type . endsWith ( "base64" ) ) { formatter . append ( "url(\"data:" ) . append ( type ) . append ( ',' ) ; formatter . append ( toBase64 ( bytes ) ) ; formatter . append ( "\")" ) ; } else { formatter . append ( "url(\"data:" ) . append ( type ) . append ( ',' ) ; appendEncode ( formatter , bytes ) ; formatter . append ( "\")" ) ; } }
Write the bytes as inline url .
38,048
private static void appendEncode ( CssFormatter formatter , byte [ ] bytes ) { for ( byte b : bytes ) { if ( ( b >= 'a' && b <= 'z' ) || ( b >= 'A' && b <= 'Z' ) || ( b >= '0' && b <= '9' ) ) { formatter . append ( ( char ) b ) ; } else { switch ( b ) { case '-' : case '_' : case '*' : case '.' : formatter . append ( ( char ) b ) ; break ; default : formatter . append ( '%' ) ; formatter . append ( Character . toUpperCase ( Character . forDigit ( ( b >> 4 ) & 0xF , 16 ) ) ) ; formatter . append ( Character . toUpperCase ( Character . forDigit ( b & 0xF , 16 ) ) ) ; } } } }
Append the bytes URL encoded .
38,049
public InputStream openStream ( URL baseURL , String urlStr , String relativeUrlStr ) throws IOException { URL url = new URL ( baseURL , urlStr ) ; try { return openStream ( url ) ; } catch ( Exception e ) { url = new URL ( new URL ( baseURL , relativeUrlStr ) , urlStr ) ; return openStream ( url ) ; } }
Open an InputStream for the given URL . This is used for inlining images via data - uri .
38,050
public Reader create ( URL url ) throws IOException { return new InputStreamReader ( openStream ( url ) , StandardCharsets . UTF_8 ) ; }
Create a Reader for the given URL .
38,051
private void eval ( CssFormatter formatter ) { if ( type != UNKNOWN ) { return ; } try { ScriptEngineManager factory = new ScriptEngineManager ( getClass ( ) . getClassLoader ( ) ) ; ScriptEngine engine = factory . getEngineByName ( "JavaScript" ) ; engine . setContext ( new JavaScriptContext ( formatter , this ) ) ; String script = toString ( ) ; script = SelectorUtils . replacePlaceHolder ( formatter , script , this ) ; script = script . substring ( 1 , script . length ( ) - 1 ) ; result = engine . eval ( script ) ; if ( result instanceof Number ) { type = NUMBER ; } else if ( result instanceof Boolean ) { type = BOOLEAN ; } else if ( result instanceof Collection ) { type = LIST ; } else if ( result instanceof Map ) { result = ( ( Map ) result ) . values ( ) ; type = LIST ; } else { type = STRING ; } } catch ( Exception ex ) { throw createException ( ex ) ; } }
Execute the JavaScript
38,052
private void evalParam ( int idx , CssFormatter formatter ) { Expression expr = get ( idx ) ; type = expr . getDataType ( formatter ) ; switch ( type ) { case BOOLEAN : booleanValue = expr . booleanValue ( formatter ) ; break ; case STRING : break ; default : doubleValue = expr . doubleValue ( formatter ) ; } }
Evaluate a parameter as this function .
38,053
private void format ( CssFormatter formatter ) { String fmt = get ( 0 ) . stringValue ( formatter ) ; int idx = 1 ; for ( int i = 0 ; i < fmt . length ( ) ; i ++ ) { char ch = fmt . charAt ( i ) ; if ( ch == '%' ) { ch = fmt . charAt ( ++ i ) ; switch ( ch ) { case '%' : formatter . append ( ch ) ; break ; case 'a' : case 'd' : get ( idx ++ ) . appendTo ( formatter ) ; break ; case 'A' : case 'D' : String str = get ( idx ++ ) . stringValue ( formatter ) ; try { str = new URI ( null , null , str , null ) . getRawPath ( ) ; } catch ( URISyntaxException e ) { e . printStackTrace ( ) ; } formatter . append ( str ) ; break ; case 's' : formatter . setInlineMode ( true ) ; get ( idx ++ ) . appendTo ( formatter ) ; formatter . setInlineMode ( false ) ; break ; case 'S' : formatter . setInlineMode ( true ) ; str = get ( idx ++ ) . stringValue ( formatter ) ; try { str = new URI ( null , null , str , null ) . getRawPath ( ) ; } catch ( URISyntaxException e ) { e . printStackTrace ( ) ; } formatter . append ( str ) ; formatter . setInlineMode ( false ) ; break ; default : formatter . append ( ch ) ; } } else { formatter . append ( ch ) ; } } }
Implements the format function %
38,054
Expression get ( int idx ) { if ( parameters . size ( ) <= idx ) { throw new ParameterOutOfBoundsException ( ) ; } return parameters . get ( idx ) ; }
Get the idx parameter from the parameter list .
38,055
private int getColorDigit ( int idx , CssFormatter formatter ) { Expression expression = get ( idx ) ; double d = expression . doubleValue ( formatter ) ; if ( expression . getDataType ( formatter ) == PERCENT ) { d *= 2.55 ; } return colorDigit ( d ) ; }
Get the idx parameter from the parameter list as color digit .
38,056
private double getColor ( Expression exp , CssFormatter formatter ) { type = exp . getDataType ( formatter ) ; switch ( type ) { case COLOR : case RGBA : return exp . doubleValue ( formatter ) ; } throw new ParameterOutOfBoundsException ( ) ; }
Get a color value from the expression . And set the type variable .
38,057
double getRadians ( CssFormatter formatter ) { final Expression exp = get ( 0 ) ; String unit = exp . unit ( formatter ) ; return exp . doubleValue ( formatter ) * Operation . unitFactor ( unit , "rad" , false ) ; }
Get the value in radians .
38,058
private double getDouble ( int idx , double defaultValue , CssFormatter formatter ) { if ( parameters . size ( ) <= idx ) { return defaultValue ; } return parameters . get ( idx ) . doubleValue ( formatter ) ; }
Get the idx parameter from the parameter list as double .
38,059
private List < Expression > getParamList ( CssFormatter formatter ) { Expression ex0 = get ( 0 ) . unpack ( formatter ) ; if ( ex0 . getDataType ( formatter ) == LIST ) { Operation op = ex0 . listValue ( formatter ) ; List < Expression > operants = op . getOperands ( ) ; if ( operants . size ( ) == 1 ) { Expression ex0_0 = operants . get ( 0 ) ; if ( ex0_0 . getDataType ( formatter ) == LIST ) { return ex0_0 . listValue ( formatter ) . getOperands ( ) ; } } return operants ; } List < Expression > result = new ArrayList < Expression > ( ) ; result . add ( ex0 ) ; return result ; }
Get for extract and length the first parameter as parameter list .
38,060
private Expression extract ( CssFormatter formatter ) { List < Expression > exList = getParamList ( formatter ) ; int idx = getInt ( 1 , formatter ) ; if ( idx <= 0 || exList . size ( ) < idx ) { type = STRING ; return null ; } Expression ex = exList . get ( idx - 1 ) ; type = ex . getDataType ( formatter ) ; switch ( type ) { case STRING : case LIST : break ; default : doubleValue = ex . doubleValue ( formatter ) ; } return ex ; }
Function extract . Change the type and doubleValue
38,061
private Operation range ( CssFormatter formatter ) { type = LIST ; double start = get ( 0 ) . doubleValue ( formatter ) ; double end ; if ( parameters . size ( ) >= 2 ) { end = get ( 1 ) . doubleValue ( formatter ) ; } else { end = start ; start = 1 ; } double step ; if ( parameters . size ( ) >= 3 ) { step = get ( 2 ) . doubleValue ( formatter ) ; } else { step = 1 ; } String unit = get ( 0 ) . unit ( formatter ) ; Operation op = new Operation ( this , ' ' ) ; while ( start <= end ) { op . addOperand ( new ValueExpression ( this , start + unit ) ) ; start += step ; } return op ; }
Function range . Generate a list spanning a range of values
38,062
void startBlock ( String [ ] selectors , StringBuilder output ) { this . results . add ( new CssRuleOutput ( selectors , output , isReference ) ) ; }
Start a block inside the media
38,063
static String fastReplace ( String str , String target , String replacement ) { int targetLength = target . length ( ) ; if ( targetLength == 0 ) { return str ; } int idx2 = str . indexOf ( target ) ; if ( idx2 < 0 ) { return str ; } StringBuilder buffer = new StringBuilder ( targetLength > replacement . length ( ) ? str . length ( ) : str . length ( ) * 2 ) ; int idx1 = 0 ; do { buffer . append ( str , idx1 , idx2 ) ; buffer . append ( replacement ) ; idx1 = idx2 + targetLength ; idx2 = str . indexOf ( target , idx1 ) ; } while ( idx2 > 0 ) ; buffer . append ( str , idx1 , str . length ( ) ) ; return buffer . toString ( ) ; }
Fast string replace which work without regular expressions
38,064
static String replacePlaceHolder ( CssFormatter formatter , String str , LessObject caller ) { int pos = str . startsWith ( "@{" ) ? 0 : str . indexOf ( "@" , 1 ) ; if ( pos >= 0 ) { formatter . addOutput ( ) ; SelectorUtils . appendToWithPlaceHolder ( formatter , str , pos , false , caller ) ; return formatter . releaseOutput ( ) ; } return str ; }
Replace the possible variable place holder .
38,065
void parse ( URL baseURL , Reader input , ReaderFactory readerFactory ) throws MalformedURLException , LessException { this . baseURL = baseURL ; this . readerFactory = readerFactory ; this . relativeURL = new URL ( "file" , null , "" ) ; this . reader = new LessLookAheadReader ( input , null , false , false ) ; parse ( this ) ; }
Main method for parsing of main less file .
38,066
void parseLazy ( CssFormatter formatter ) { if ( lazyImports != null ) { HashMap < String , Expression > vars = variables ; formatter . addVariables ( vars ) ; for ( int i = 0 ; i < lazyImports . size ( ) ; i ++ ) { LazyImport lazyImport = lazyImports . get ( i ) ; String filename = lazyImport . stringValue ( formatter ) ; baseURL = lazyImport . getBaseUrl ( ) ; variables = lazyImport . getVariables ( ) ; rulesIdx = lazyImport . lastRuleBefore ( ) == null ? 0 : rules . indexOf ( lazyImport . lastRuleBefore ( ) ) + 1 ; importFile ( this , filename ) ; } formatter . removeVariables ( vars ) ; variables = vars ; } }
If there are some imports with variables then this will parse after a formatter if available .
38,067
private void parse ( FormattableContainer currentRule ) { try { for ( ; ; ) { int ch = reader . nextBlockMarker ( ) ; switch ( ch ) { case - 1 : return ; case ';' : parseSemicolon ( currentRule ) ; break ; case '{' : parseBlock ( currentRule ) ; break ; default : throw createException ( "Unrecognized input: '" + reader . getLookAhead ( ) + "'" ) ; } } } catch ( LessException ex ) { ex . addPosition ( reader . getFileName ( ) , reader . getLine ( ) , reader . getColumn ( ) ) ; throw ex ; } catch ( RuntimeException ex ) { LessException lessEx = new LessException ( ex ) ; lessEx . addPosition ( reader . getFileName ( ) , reader . getLine ( ) , reader . getColumn ( ) ) ; throw lessEx ; } }
Parse main and import less files .
38,068
private void parseSemicolon ( FormattableContainer currentRule ) { String selector = null ; Operation params = null ; StringBuilder builder = cachesBuilder ; LOOP : for ( ; ; ) { char ch ; try { ch = read ( ) ; } catch ( Exception e ) { ch = ';' ; } switch ( ch ) { case ':' : if ( isMixin ( builder ) ) { builder . append ( ch ) ; continue LOOP ; } String name = trim ( builder ) ; strictMath = "font" . equals ( name ) ; Expression value = parseExpression ( ( char ) 0 ) ; strictMath = false ; ch = read ( ) ; switch ( ch ) { case '}' : break ; case ';' : break ; default : throw createException ( "Unrecognized input: '" + ch + "'" ) ; } currentRule . add ( new RuleProperty ( name , value ) ) ; return ; case '@' : ch = read ( ) ; if ( ch == '{' ) { builder . append ( '@' ) ; builder . append ( ch ) ; do { ch = read ( ) ; builder . append ( ch ) ; } while ( ch != '}' ) ; break ; } else { back ( ch ) ; } throwUnrecognizedInputIfAny ( builder , ch ) ; variable ( currentRule . getVariables ( ) , currentRule ) ; return ; case '/' : if ( ! comment ( isWhitespace ( builder ) ? currentRule : null ) ) { builder . append ( ch ) ; } break ; case '(' : if ( ! reader . nextIsMixinParam ( false ) ) { builder . append ( ch ) ; break ; } selector = trim ( builder ) ; params = parseParameterList ( ) ; break ; case ';' : case '}' : String sel = trim ( builder ) ; if ( ! sel . isEmpty ( ) ) { if ( selector == null ) { selector = sel ; } else { selector += ' ' + sel ; } } if ( selector != null ) { if ( selector . contains ( ":extend(" ) ) { LessExtend . addLessExtendsTo ( currentRule , reader , selector ) ; } else { Mixin mixin = new Mixin ( reader , selector , params , currentRule . getMixins ( ) ) ; currentRule . add ( mixin ) ; } } return ; default : builder . append ( ch ) ; } } }
Parse an expression which ends with a semicolon . This can be a property assignment variable assignment a directive or other .
38,069
private Rule rule ( FormattableContainer parent , String selector , Operation params , Expression guard ) { Rule rule = new Rule ( reader , parent , selector , params , guard ) ; parseRule ( rule ) ; return rule ; }
Create a rule and parse the content of an block .
38,070
private void parseRule ( Rule rule ) { ruleStack . add ( rule ) ; for ( ; ; ) { int ch = reader . nextBlockMarker ( ) ; switch ( ch ) { case - 1 : throw createException ( "Unexpected end of Less data" ) ; case ';' : parseSemicolon ( rule ) ; break ; case '{' : parseBlock ( rule ) ; break ; case '}' : parseSemicolon ( rule ) ; ruleStack . removeLast ( ) ; return ; default : throw createException ( "Unrecognized input: '" + reader . getLookAhead ( ) + "'" ) ; } } }
Parse the content of an block .
38,071
private String readQuote ( char quote ) { StringBuilder builder = cachesBuilder ; builder . setLength ( 0 ) ; readQuote ( quote , builder ) ; String str = builder . toString ( ) ; builder . setLength ( 0 ) ; return str ; }
Read a quoted string .
38,072
private void readQuote ( char quote , StringBuilder builder ) { builder . append ( quote ) ; boolean isBackslash = false ; for ( ; ; ) { char ch = read ( ) ; builder . append ( ch ) ; if ( ch == quote && ! isBackslash ) { return ; } isBackslash = ch == '\\' ; } }
Read a quoted string and append it to the builder .
38,073
private Operation parseUrlParam ( ) { StringBuilder builder = cachesBuilder ; builder . setLength ( 0 ) ; Operation op = new Operation ( reader , new ValueExpression ( reader , relativeURL . getPath ( ) ) , ';' ) ; for ( ; ; ) { char ch = read ( ) ; switch ( ch ) { case '"' : case '\'' : String val = builder . toString ( ) ; String quote = readQuote ( ch ) ; builder . append ( val ) ; builder . append ( quote ) ; break ; case '\\' : builder . append ( ch ) ; builder . append ( read ( ) ) ; break ; case '@' : if ( builder . length ( ) == 0 ) { reader . back ( ch ) ; op . addOperand ( parseExpression ( ( char ) 0 ) ) ; read ( ) ; return op ; } builder . append ( ch ) ; break ; case ')' : val = trim ( builder ) ; op . addOperand ( new ValueExpression ( reader , val , Expression . STRING ) ) ; return op ; default : builder . append ( ch ) ; } } }
Parse the parameter of an url function which has some curious fallbacks .
38,074
private Expression concat ( Expression left , char operator , Expression right ) { if ( left == null ) { return right ; } Operation op ; if ( left . getClass ( ) == Operation . class && ( ( Operation ) left ) . getOperator ( ) == operator ) { op = ( Operation ) left ; } else if ( right != null && right . getClass ( ) == Operation . class && ( ( Operation ) right ) . getOperator ( ) == operator ) { op = ( Operation ) right ; op . addLeftOperand ( left ) ; return op ; } else { op = new Operation ( reader , left , operator ) ; } if ( right != null ) { op . addOperand ( right ) ; } return op ; }
Concatenate 2 expressions to one expression .
38,075
private Expression buildExpression ( String str ) { switch ( str . charAt ( 0 ) ) { case '@' : return new VariableExpression ( reader , str ) ; case '-' : if ( str . startsWith ( "-@" ) ) { return new FunctionExpression ( reader , "-" , new Operation ( reader , buildExpression ( str . substring ( 1 ) ) , ( char ) 0 ) ) ; } default : return new ValueExpression ( reader , str ) ; } }
Create an expression from the given atomic string .
38,076
private static String trim ( StringBuilder builder ) { String str = builder . toString ( ) . trim ( ) ; builder . setLength ( 0 ) ; return str ; }
Get a trim string from the builder and clear the builder .
38,077
private static boolean isWhitespace ( StringBuilder builder ) { for ( int i = 0 ; i < builder . length ( ) ; i ++ ) { if ( ! Character . isWhitespace ( builder . charAt ( i ) ) ) { return false ; } } return true ; }
If the builder is empty or contains only whitespaces
38,078
private static boolean isSelector ( StringBuilder builder ) { int length = builder . length ( ) ; if ( length == 0 ) { return false ; } switch ( builder . charAt ( 0 ) ) { case '.' : case '#' : break ; default : return true ; } for ( int i = 1 ; i < length ; i ++ ) { char ch = builder . charAt ( i ) ; switch ( ch ) { case '>' : case ':' : return true ; } } return false ; }
If the builder contains a selector and not a mixin .
38,079
private static boolean isVariableName ( StringBuilder builder ) { for ( int i = 1 ; i < builder . length ( ) ; ) { char ch = builder . charAt ( i ++ ) ; switch ( ch ) { case '(' : case '\"' : return false ; } } return true ; }
If the builder contains a valid variable name
38,080
private static char firstNonWhitespace ( StringBuilder builder ) { for ( int i = 0 ; i < builder . length ( ) ; i ++ ) { if ( ! Character . isWhitespace ( builder . charAt ( i ) ) ) { return builder . charAt ( i ) ; } } return ' ' ; }
The first character in the builder that is not a whitespace . Else there are only whitespaces
38,081
private void throwUnrecognizedInputIfAny ( StringBuilder builder , int ch ) { if ( ! isWhitespace ( builder ) ) { throw createException ( "Unrecognized input: '" + trim ( builder ) + ( char ) ch + "'" ) ; } builder . setLength ( 0 ) ; }
Throw an unrecognized input exception if there content in the StringBuilder .
38,082
public static boolean isRserveInstalled ( String Rcmd ) { Process p = doInR ( "is.element(set=installed.packages(lib.loc='" + RserveDaemon . app_dir ( ) + "'),el='Rserve')" , Rcmd , "--vanilla --silent" , false ) ; if ( p == null ) { Log . Err . println ( "Failed to ask if Rserve is installed" ) ; return false ; } try { StringBuffer result = new StringBuffer ( ) ; StreamHog error = new StreamHog ( p . getErrorStream ( ) , true ) ; StreamHog output = new StreamHog ( p . getInputStream ( ) , true ) ; error . join ( ) ; output . join ( ) ; if ( ! RserveDaemon . isWindows ( ) ) { p . waitFor ( ) ; } else { Thread . sleep ( 2000 ) ; } result . append ( output . getOutput ( ) ) ; result . append ( error . getOutput ( ) ) ; if ( result . toString ( ) . contains ( "[1] TRUE" ) ) { Log . Out . println ( "Rserve is already installed." ) ; return true ; } else if ( result . toString ( ) . contains ( "[1] FALSE" ) ) { Log . Out . println ( "Rserve is not yet installed." ) ; return false ; } else { Log . Err . println ( "Cannot check if Rserve is installed: " + result . toString ( ) ) ; return false ; } } catch ( InterruptedException e ) { return false ; } }
R batch to check Rserve is installed
38,083
public static void main ( String [ ] args ) { File dir = null ; System . out . println ( "checkLocalRserve: " + checkLocalRserve ( ) ) ; try { RConnection c = new RConnection ( ) ; dir = new File ( c . eval ( "getwd()" ) . asString ( ) ) ; System . err . println ( "wd: " + dir ) ; c . eval ( "download.file('https://www.r-project.org/',paste0(getwd(),'/log.txt'))" ) ; c . shutdown ( ) ; } catch ( Exception x ) { x . printStackTrace ( ) ; } if ( new File ( dir , "log.txt" ) . exists ( ) ) { System . err . println ( "OK: file exists" ) ; if ( new File ( dir , "log.txt" ) . length ( ) > 10 ) { System . err . println ( "OK: file not empty" ) ; } else { System . err . println ( "NO: file EMPTY" ) ; } } else { System . err . println ( "NO: file DOES NOT exist" ) ; } }
just a demo main method which starts Rserve and shuts it down again
38,084
public static boolean isPortAvailable ( int p ) { try { ServerSocket test = new ServerSocket ( p ) ; test . close ( ) ; } catch ( BindException e ) { return false ; } catch ( IOException e ) { return false ; } return true ; }
used for windows multi - session emulation . Incremented at each new Rscript instance .
38,085
public static RserverConf newLocalInstance ( Properties p ) { RserverConf server = null ; if ( RserveDaemon . isWindows ( ) || ! UNIX_OPTIMIZE ) { while ( ! isPortAvailable ( RserverPort ) ) { RserverPort ++ ; } server = new RserverConf ( null , RserverPort , null , null , p ) ; } else { server = new RserverConf ( null , - 1 , null , null , p ) ; } return server ; }
if we want to re - use older sessions . May wrongly fil if older session is already stucked ...
38,086
public static List < String > parse ( String expr ) { List < String > expressions = new ArrayList < > ( ) ; int parenthesis = 0 ; int brackets = 0 ; int brackets2 = 0 ; String [ ] lines = expr . split ( "\n" ) ; StringBuilder sb = new StringBuilder ( ) ; for ( String line : lines ) { line = line . trim ( ) ; if ( line . startsWith ( "#" ) ) { } else { char currentChar = 0 ; for ( int i = 0 ; i < line . length ( ) ; i ++ ) { currentChar = line . charAt ( i ) ; if ( currentChar == '#' ) { line = line . substring ( 0 , i ) ; break ; } else if ( currentChar == '(' ) { parenthesis ++ ; } else if ( currentChar == ')' ) { parenthesis -- ; } else if ( currentChar == '{' ) { brackets ++ ; } else if ( currentChar == '}' ) { brackets -- ; } else if ( currentChar == '[' ) { brackets2 ++ ; } else if ( currentChar == ']' ) { brackets2 -- ; } else if ( parenthesis == 0 && brackets == 0 && brackets2 == 0 ) { if ( currentChar == ';' ) { String firstLine = line . substring ( 0 , i + 1 ) ; sb . append ( firstLine ) ; expressions . add ( sb . toString ( ) ) ; sb = new StringBuilder ( ) ; String remainder = line . substring ( i + 1 ) ; line = remainder . trim ( ) + "\n" ; i = 0 ; } } } if ( line . trim ( ) . length ( ) > 0 ) { sb . append ( line ) ; if ( parenthesis == 0 && brackets == 0 && brackets2 == 0 ) { expressions . add ( sb . toString ( ) ) ; sb = new StringBuilder ( ) ; } else { if ( currentChar != ',' && currentChar != '+' && currentChar != '-' && currentChar != '*' && currentChar != '/' && currentChar != '=' ) sb . append ( ";\n" ) ; } } } } return expressions ; }
Parse an expression containing multiple lines functions or sub - expressions in a list of inline sub - expressions . This function also cleanup comments .
38,087
public void bindExternalFunction ( String funcName , ExternalFunction func ) throws Exception { ifAsyncWeCant ( "bind an external function" ) ; Assert ( ! externals . containsKey ( funcName ) , "Function '" + funcName + "' has already been bound." ) ; externals . put ( funcName , func ) ; }
Most general form of function binding that returns an Object and takes an array of Object parameters . The only way to bind a function with more than 3 arguments .
38,088
public void chooseChoiceIndex ( int choiceIdx ) throws Exception { List < Choice > choices = getCurrentChoices ( ) ; Assert ( choiceIdx >= 0 && choiceIdx < choices . size ( ) , "choice out of range" ) ; Choice choiceToChoose = choices . get ( choiceIdx ) ; state . getCallStack ( ) . setCurrentThread ( choiceToChoose . getThreadAtGeneration ( ) ) ; choosePath ( choiceToChoose . targetPath ) ; }
Chooses the Choice from the currentChoices list with the given index . Internally this sets the current content path to that pointed to by the Choice ready to continue story evaluation .
38,089
void error ( String message , boolean useEndLineNumber ) throws Exception { StoryException e = new StoryException ( message ) ; e . useEndLineNumber = useEndLineNumber ; throw e ; }
then exits the flow .
38,090
public void observeVariable ( String variableName , VariableObserver observer ) throws StoryException , Exception { ifAsyncWeCant ( "observe a new variable" ) ; if ( variableObservers == null ) variableObservers = new HashMap < String , List < VariableObserver > > ( ) ; if ( ! state . getVariablesState ( ) . globalVariableExistsWithName ( variableName ) ) throw new StoryException ( "Cannot observe variable '" + variableName + "' because it wasn't declared in the ink story." ) ; if ( variableObservers . containsKey ( variableName ) ) { variableObservers . get ( variableName ) . add ( observer ) ; } else { List < VariableObserver > l = new ArrayList < VariableObserver > ( ) ; l . add ( observer ) ; variableObservers . put ( variableName , l ) ; } }
When the named global variable changes it s value the observer will be called to notify it of the change . Note that if the value changes multiple times within the ink the observer will only be called once at the end of the ink s evaluation . If during the evaluation it changes and then changes back again to its original value it will still be called . Note that the observer will also be fired if the value of the variable is changed externally to the ink by directly setting a value in story . variablesState .
38,091
public void observeVariables ( List < String > variableNames , VariableObserver observer ) throws StoryException , Exception { for ( String varName : variableNames ) { observeVariable ( varName , observer ) ; } }
Convenience function to allow multiple variables to be observed with the same observer delegate function . See the singular ObserveVariable for details . The observer will get one call for every variable that has changed .
38,092
public String toJsonString ( ) throws Exception { List < ? > rootContainerJsonList = ( List < ? > ) Json . runtimeObjectToJToken ( mainContentContainer ) ; HashMap < String , Object > rootObject = new HashMap < String , Object > ( ) ; rootObject . put ( "inkVersion" , inkVersionCurrent ) ; rootObject . put ( "root" , rootContainerJsonList ) ; return SimpleJson . HashMapToText ( rootObject ) ; }
The Story itself in JSON representation .
38,093
public void unbindExternalFunction ( String funcName ) throws Exception { ifAsyncWeCant ( "unbind an external a function" ) ; Assert ( externals . containsKey ( funcName ) , "Function '" + funcName + "' has not been bound." ) ; externals . remove ( funcName ) ; }
Remove a binding for a named EXTERNAL ink function .
38,094
void visitContainer ( Container container , boolean atStart ) { if ( ! container . getCountingAtStartOnly ( ) || atStart ) { if ( container . getVisitsShouldBeCounted ( ) ) incrementVisitCountForContainer ( container ) ; if ( container . getTurnIndexShouldBeCounted ( ) ) recordTurnIndexVisitToContainer ( container ) ; } }
Mark a container as having been visited
38,095
public Object evaluateFunction ( String functionName , Object [ ] arguments ) throws Exception { return evaluateFunction ( functionName , null , arguments ) ; }
Evaluates a function defined in ink .
38,096
public Object evaluateFunction ( String functionName , StringBuilder textOutput , Object [ ] arguments ) throws Exception { ifAsyncWeCant ( "evaluate a function" ) ; if ( functionName == null ) { throw new Exception ( "Function is null" ) ; } else if ( functionName . trim ( ) . isEmpty ( ) ) { throw new Exception ( "Function is empty or white space." ) ; } Container funcContainer = knotContainerWithName ( functionName ) ; if ( funcContainer == null ) throw new Exception ( "Function doesn't exist: '" + functionName + "'" ) ; ArrayList < RTObject > outputStreamBefore = new ArrayList < RTObject > ( state . getOutputStream ( ) ) ; state . resetOutput ( ) ; state . startFunctionEvaluationFromGame ( funcContainer , arguments ) ; while ( canContinue ( ) ) { String text = Continue ( ) ; if ( textOutput != null ) textOutput . append ( text ) ; } state . resetOutput ( outputStreamBefore ) ; Object result = state . completeFunctionEvaluationFromGame ( ) ; return result ; }
Evaluates a function defined in ink and gathers the possibly multi - line text as generated by the function .
38,097
public long getElapsedTicks ( ) { long elapsed ; if ( running ) { elapsed = ( System . nanoTime ( ) - startTime ) ; } else { elapsed = ( stopTime - startTime ) ; } return elapsed / nsPerTick ; }
Gets the total elapsed time measured by the current instance in nanoseconds . 1 Tick = 100 nanoseconds
38,098
public HashMap < String , Object > getJsonToken ( ) throws Exception { HashMap < String , Object > jRTObject = new HashMap < String , Object > ( ) ; ArrayList < Object > jThreads = new ArrayList < Object > ( ) ; for ( CallStack . Thread thread : threads ) { jThreads . add ( thread . jsonToken ( ) ) ; } jRTObject . put ( "threads" , jThreads ) ; jRTObject . put ( "threadCounter" , threadCounter ) ; return jRTObject ; }
See above for why we can t implement jsonToken
38,099
public RTObject getTemporaryVariableWithName ( String name , int contextIndex ) { if ( contextIndex == - 1 ) contextIndex = getCurrentElementIndex ( ) + 1 ; Element contextElement = getCallStack ( ) . get ( contextIndex - 1 ) ; RTObject varValue = contextElement . temporaryVariables . get ( name ) ; return varValue ; }
Get variable value dereferencing a variable pointer if necessary