idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
143,200
public Value get ( Object key ) { /* If the length is under and we are asking for the key, then just look for the key. Don't build the map. */ if ( map == null && items . length < 20 ) { for ( Object item : items ) { MapItemValue miv = ( MapItemValue ) item ; if ( key . equals ( miv . name . toValue ( ) ) ) { return miv . value ; } } return null ; } else { if ( map == null ) buildIfNeededMap ( ) ; return map . get ( key ) ; } }
Get the items for the key .
126
7
143,201
public static < T > Iterator < T > unique ( Iterator < T > self ) { return toList ( ( Iterable < T > ) unique ( toList ( self ) ) ) . listIterator ( ) ; }
Returns an iterator equivalent to this iterator with all duplicated items removed by using the default comparator . The original iterator will become exhausted of elements after determining the unique values . A new iterator for the unique values will be returned .
47
45
143,202
public static int numberAwareCompareTo ( Comparable self , Comparable other ) { NumberAwareComparator < Comparable > numberAwareComparator = new NumberAwareComparator < Comparable > ( ) ; return numberAwareComparator . compare ( self , other ) ; }
Provides a method that compares two comparables using Groovy s default number aware comparator .
61
19
143,203
public static boolean any ( Object self , Closure closure ) { BooleanClosureWrapper bcw = new BooleanClosureWrapper ( closure ) ; for ( Iterator iter = InvokerHelper . asIterator ( self ) ; iter . hasNext ( ) ; ) { if ( bcw . call ( iter . next ( ) ) ) return true ; } return false ; }
Iterates over the contents of an object or collection and checks whether a predicate is valid for at least one element .
76
23
143,204
public static Object findResult ( Object self , Object defaultResult , Closure closure ) { Object result = findResult ( self , closure ) ; if ( result == null ) return defaultResult ; return result ; }
Treats the object as iterable iterating through the values it represents and returns the first non - null result obtained from calling the closure otherwise returns the defaultResult .
43
34
143,205
protected static < K , T > void groupAnswer ( final Map < K , List < T > > answer , T element , K value ) { if ( answer . containsKey ( value ) ) { answer . get ( value ) . add ( element ) ; } else { List < T > groupedElements = new ArrayList < T > ( ) ; groupedElements . add ( element ) ; answer . put ( value , groupedElements ) ; } }
Groups the current element according to the value
95
9
143,206
public static < K , V > Map < K , V > asImmutable ( Map < ? extends K , ? extends V > self ) { return Collections . unmodifiableMap ( self ) ; }
A convenience method for creating an immutable map .
42
9
143,207
public static < K , V > SortedMap < K , V > asImmutable ( SortedMap < K , ? extends V > self ) { return Collections . unmodifiableSortedMap ( self ) ; }
A convenience method for creating an immutable sorted map .
46
10
143,208
public static < T > List < T > asImmutable ( List < ? extends T > self ) { return Collections . unmodifiableList ( self ) ; }
A convenience method for creating an immutable list
34
8
143,209
public static < T > Set < T > asImmutable ( Set < ? extends T > self ) { return Collections . unmodifiableSet ( self ) ; }
A convenience method for creating an immutable list .
34
9
143,210
public static < T > SortedSet < T > asImmutable ( SortedSet < T > self ) { return Collections . unmodifiableSortedSet ( self ) ; }
A convenience method for creating an immutable sorted set .
38
10
143,211
public static < T > T [ ] sort ( T [ ] self , Comparator < T > comparator ) { return sort ( self , true , comparator ) ; }
Sorts the given array into sorted order using the given comparator .
36
14
143,212
public static < T > boolean addAll ( Collection < T > self , Iterator < T > items ) { boolean changed = false ; while ( items . hasNext ( ) ) { T next = items . next ( ) ; if ( self . add ( next ) ) changed = true ; } return changed ; }
Adds all items from the iterator to the Collection .
65
10
143,213
public static < T > boolean addAll ( Collection < T > self , Iterable < T > items ) { boolean changed = false ; for ( T next : items ) { if ( self . add ( next ) ) changed = true ; } return changed ; }
Adds all items from the iterable to the Collection .
54
11
143,214
public static < K , V > Map < K , V > minus ( Map < K , V > self , Map removeMe ) { final Map < K , V > ansMap = createSimilarMap ( self ) ; ansMap . putAll ( self ) ; if ( removeMe != null && removeMe . size ( ) > 0 ) { for ( Map . Entry < K , V > e1 : self . entrySet ( ) ) { for ( Object e2 : removeMe . entrySet ( ) ) { if ( DefaultTypeTransformation . compareEqual ( e1 , e2 ) ) { ansMap . remove ( e1 . getKey ( ) ) ; } } } } return ansMap ; }
Create a Map composed of the entries of the first map minus the entries of the given map .
149
19
143,215
public static int findLastIndexOf ( Object self , int startIndex , Closure closure ) { int result = - 1 ; int i = 0 ; BooleanClosureWrapper bcw = new BooleanClosureWrapper ( closure ) ; for ( Iterator iter = InvokerHelper . asIterator ( self ) ; iter . hasNext ( ) ; i ++ ) { Object value = iter . next ( ) ; if ( i < startIndex ) { continue ; } if ( bcw . call ( value ) ) { result = i ; } } return result ; }
Iterates over the elements of an iterable collection of items starting from a specified startIndex and returns the index of the last item that matches the condition specified in the closure .
115
35
143,216
public static List < Number > findIndexValues ( Object self , Closure closure ) { return findIndexValues ( self , 0 , closure ) ; }
Iterates over the elements of an iterable collection of items and returns the index values of the items that match the condition specified in the closure .
31
29
143,217
public static List < Number > findIndexValues ( Object self , Number startIndex , Closure closure ) { List < Number > result = new ArrayList < Number > ( ) ; long count = 0 ; long startCount = startIndex . longValue ( ) ; BooleanClosureWrapper bcw = new BooleanClosureWrapper ( closure ) ; for ( Iterator iter = InvokerHelper . asIterator ( self ) ; iter . hasNext ( ) ; count ++ ) { Object value = iter . next ( ) ; if ( count < startCount ) { continue ; } if ( bcw . call ( value ) ) { result . add ( count ) ; } } return result ; }
Iterates over the elements of an iterable collection of items starting from a specified startIndex and returns the index values of the items that match the condition specified in the closure .
141
35
143,218
public Object getProperty ( String property ) { if ( ExpandoMetaClass . isValidExpandoProperty ( property ) ) { if ( property . equals ( ExpandoMetaClass . STATIC_QUALIFIER ) || property . equals ( ExpandoMetaClass . CONSTRUCTOR ) || myMetaClass . hasProperty ( this , property ) == null ) { return replaceDelegate ( ) . getProperty ( property ) ; } } return myMetaClass . getProperty ( this , property ) ; }
this method mimics EMC behavior
104
7
143,219
public static Message create ( String text , Object data , ProcessingUnit owner ) { return new SimpleMessage ( text , data , owner ) ; }
Creates a new Message from the specified text .
29
10
143,220
public Object invokeMethod ( String name , Object args ) { Object val = null ; if ( args != null && Object [ ] . class . isAssignableFrom ( args . getClass ( ) ) ) { Object [ ] arr = ( Object [ ] ) args ; if ( arr . length == 1 ) { val = arr [ 0 ] ; } else if ( arr . length == 2 && arr [ 0 ] instanceof Collection && arr [ 1 ] instanceof Closure ) { Closure < ? > closure = ( Closure < ? > ) arr [ 1 ] ; Iterator < ? > iterator = ( ( Collection ) arr [ 0 ] ) . iterator ( ) ; List < Object > list = new ArrayList < Object > ( ) ; while ( iterator . hasNext ( ) ) { list . add ( curryDelegateAndGetContent ( closure , iterator . next ( ) ) ) ; } val = list ; } else { val = Arrays . asList ( arr ) ; } } content . put ( name , val ) ; return val ; }
Intercepts calls for setting a key and value for a JSON object
220
14
143,221
public void setVariable ( String name , Object value ) { if ( variables == null ) variables = new LinkedHashMap ( ) ; variables . put ( name , value ) ; }
Sets the value of the given variable
38
8
143,222
public Object getProperty ( Object object ) { MetaMethod getter = getGetter ( ) ; if ( getter == null ) { if ( field != null ) return field . getProperty ( object ) ; //TODO: create a WriteOnlyException class? throw new GroovyRuntimeException ( "Cannot read write-only property: " + name ) ; } return getter . invoke ( object , MetaClassHelper . EMPTY_ARRAY ) ; }
Get the property of the given object .
97
8
143,223
public void setProperty ( Object object , Object newValue ) { MetaMethod setter = getSetter ( ) ; if ( setter == null ) { if ( field != null && ! Modifier . isFinal ( field . getModifiers ( ) ) ) { field . setProperty ( object , newValue ) ; return ; } throw new GroovyRuntimeException ( "Cannot set read-only property: " + name ) ; } newValue = DefaultTypeTransformation . castToType ( newValue , getType ( ) ) ; setter . invoke ( object , new Object [ ] { newValue } ) ; }
Set the property on the given object to the new value .
130
12
143,224
public int getModifiers ( ) { MetaMethod getter = getGetter ( ) ; MetaMethod setter = getSetter ( ) ; if ( setter != null && getter == null ) return setter . getModifiers ( ) ; if ( getter != null && setter == null ) return getter . getModifiers ( ) ; int modifiers = getter . getModifiers ( ) | setter . getModifiers ( ) ; int visibility = 0 ; if ( Modifier . isPublic ( modifiers ) ) visibility = Modifier . PUBLIC ; if ( Modifier . isProtected ( modifiers ) ) visibility = Modifier . PROTECTED ; if ( Modifier . isPrivate ( modifiers ) ) visibility = Modifier . PRIVATE ; int states = getter . getModifiers ( ) & setter . getModifiers ( ) ; states &= ~ ( Modifier . PUBLIC | Modifier . PROTECTED | Modifier . PRIVATE ) ; states |= visibility ; return states ; }
Gets the visibility modifiers for the property as defined by the getter and setter methods .
214
19
143,225
public static boolean isTrait ( final ClassNode cNode ) { return cNode != null && ( ( cNode . isInterface ( ) && ! cNode . getAnnotations ( TRAIT_CLASSNODE ) . isEmpty ( ) ) || isAnnotatedWithTrait ( cNode ) ) ; }
Returns true if the specified class node is a trait .
66
11
143,226
public static Method getBridgeMethodTarget ( Method someMethod ) { TraitBridge annotation = someMethod . getAnnotation ( TraitBridge . class ) ; if ( annotation == null ) { return null ; } Class aClass = annotation . traitClass ( ) ; String desc = annotation . desc ( ) ; for ( Method method : aClass . getDeclaredMethods ( ) ) { String methodDescriptor = BytecodeHelper . getMethodDescriptor ( method . getReturnType ( ) , method . getParameterTypes ( ) ) ; if ( desc . equals ( methodDescriptor ) ) { return method ; } } return null ; }
Reflection API to find the method corresponding to the default implementation of a trait given a bridge method .
134
20
143,227
private static int findNext ( boolean reverse , int pos ) { boolean backwards = IS_BACKWARDS_CHECKBOX . isSelected ( ) ; backwards = backwards ? ! reverse : reverse ; String pattern = ( String ) FIND_FIELD . getSelectedItem ( ) ; if ( pattern != null && pattern . length ( ) > 0 ) { try { Document doc = textComponent . getDocument ( ) ; doc . getText ( 0 , doc . getLength ( ) , SEGMENT ) ; } catch ( Exception e ) { // should NEVER reach here e . printStackTrace ( ) ; } pos += textComponent . getSelectedText ( ) == null ? ( backwards ? - 1 : 1 ) : 0 ; char first = backwards ? pattern . charAt ( pattern . length ( ) - 1 ) : pattern . charAt ( 0 ) ; char oppFirst = Character . isUpperCase ( first ) ? Character . toLowerCase ( first ) : Character . toUpperCase ( first ) ; int start = pos ; boolean wrapped = WRAP_SEARCH_CHECKBOX . isSelected ( ) ; int end = backwards ? 0 : SEGMENT . getEndIndex ( ) ; pos += backwards ? - 1 : 1 ; int length = textComponent . getDocument ( ) . getLength ( ) ; if ( pos > length ) { pos = wrapped ? 0 : length ; } boolean found = false ; while ( ! found && ( backwards ? pos > end : pos < end ) ) { found = ! MATCH_CASE_CHECKBOX . isSelected ( ) && SEGMENT . array [ pos ] == oppFirst ; found = found ? found : SEGMENT . array [ pos ] == first ; if ( found ) { pos += backwards ? - ( pattern . length ( ) - 1 ) : 0 ; for ( int i = 0 ; found && i < pattern . length ( ) ; i ++ ) { char c = pattern . charAt ( i ) ; found = SEGMENT . array [ pos + i ] == c ; if ( ! MATCH_CASE_CHECKBOX . isSelected ( ) && ! found ) { c = Character . isUpperCase ( c ) ? Character . toLowerCase ( c ) : Character . toUpperCase ( c ) ; found = SEGMENT . array [ pos + i ] == c ; } } } if ( ! found ) { pos += backwards ? - 1 : 1 ; if ( pos == end && wrapped ) { pos = backwards ? SEGMENT . getEndIndex ( ) : 0 ; end = start ; wrapped = false ; } } } pos = found ? pos : - 1 ; } return pos ; }
Find and select the next searchable matching text .
568
10
143,228
protected static void invalidateSwitchPoints ( ) { if ( LOG_ENABLED ) { LOG . info ( "invalidating switch point" ) ; } SwitchPoint old = switchPoint ; switchPoint = new SwitchPoint ( ) ; synchronized ( IndyInterface . class ) { SwitchPoint . invalidateAll ( new SwitchPoint [ ] { old } ) ; } }
Callback for constant meta class update change
76
7
143,229
public static CallSite bootstrapCurrent ( Lookup caller , String name , MethodType type ) { return realBootstrap ( caller , name , CALL_TYPES . METHOD . ordinal ( ) , type , false , true , false ) ; }
bootstrap method for method calls with this as receiver
53
10
143,230
private static CallSite realBootstrap ( Lookup caller , String name , int callID , MethodType type , boolean safe , boolean thisCall , boolean spreadCall ) { // since indy does not give us the runtime types // we produce first a dummy call site, which then changes the target to one, // that does the method selection including the the direct call to the // real method. MutableCallSite mc = new MutableCallSite ( type ) ; MethodHandle mh = makeFallBack ( mc , caller . lookupClass ( ) , name , callID , type , safe , thisCall , spreadCall ) ; mc . setTarget ( mh ) ; return mc ; }
backing bootstrap method with all parameters
142
8
143,231
public void addCell ( TableLayoutCell cell ) { GridBagConstraints constraints = cell . getConstraints ( ) ; constraints . insets = new Insets ( cellpadding , cellpadding , cellpadding , cellpadding ) ; add ( cell . getComponent ( ) , constraints ) ; }
Adds a new cell to the current grid
63
8
143,232
public void addClass ( ClassNode node ) { node = node . redirect ( ) ; String name = node . getName ( ) ; ClassNode stored = classes . get ( name ) ; if ( stored != null && stored != node ) { // we have a duplicate class! // One possibility for this is, that we declared a script and a // class in the same file and named the class like the file SourceUnit nodeSource = node . getModule ( ) . getContext ( ) ; SourceUnit storedSource = stored . getModule ( ) . getContext ( ) ; String txt = "Invalid duplicate class definition of class " + node . getName ( ) + " : " ; if ( nodeSource == storedSource ) { // same class in same source txt += "The source " + nodeSource . getName ( ) + " contains at least two definitions of the class " + node . getName ( ) + ".\n" ; if ( node . isScriptBody ( ) || stored . isScriptBody ( ) ) { txt += "One of the classes is an explicit generated class using the class statement, the other is a class generated from" + " the script body based on the file name. Solutions are to change the file name or to change the class name.\n" ; } } else { txt += "The sources " + nodeSource . getName ( ) + " and " + storedSource . getName ( ) + " each contain a class with the name " + node . getName ( ) + ".\n" ; } nodeSource . getErrorCollector ( ) . addErrorAndContinue ( new SyntaxErrorMessage ( new SyntaxException ( txt , node . getLineNumber ( ) , node . getColumnNumber ( ) , node . getLastLineNumber ( ) , node . getLastColumnNumber ( ) ) , nodeSource ) ) ; } classes . put ( name , node ) ; if ( classesToCompile . containsKey ( name ) ) { ClassNode cn = classesToCompile . get ( name ) ; cn . setRedirect ( node ) ; classesToCompile . remove ( name ) ; } }
Adds a class to the unit .
455
7
143,233
private String getSlashyPath ( final String path ) { String changedPath = path ; if ( File . separatorChar != ' ' ) changedPath = changedPath . replace ( File . separatorChar , ' ' ) ; return changedPath ; }
This solution is based on an absolute path
53
8
143,234
public static void write ( Path self , String text , String charset ) throws IOException { Writer writer = null ; try { writer = new OutputStreamWriter ( Files . newOutputStream ( self , CREATE , APPEND ) , Charset . forName ( charset ) ) ; writer . write ( text ) ; writer . flush ( ) ; Writer temp = writer ; writer = null ; temp . close ( ) ; } finally { closeWithWarning ( writer ) ; } }
Write the text to the Path using the specified encoding .
100
11
143,235
public static void append ( Path self , Object text ) throws IOException { Writer writer = null ; try { writer = new OutputStreamWriter ( Files . newOutputStream ( self , CREATE , APPEND ) , Charset . defaultCharset ( ) ) ; InvokerHelper . write ( writer , text ) ; writer . flush ( ) ; Writer temp = writer ; writer = null ; temp . close ( ) ; } finally { closeWithWarning ( writer ) ; } }
Append the text at the end of the Path .
100
11
143,236
public static int count ( CharSequence self , CharSequence text ) { int answer = 0 ; for ( int idx = 0 ; true ; idx ++ ) { idx = self . toString ( ) . indexOf ( text . toString ( ) , idx ) ; // break once idx goes to -1 or for case of empty string once // we get to the end to avoid JDK library bug (see GROOVY-5858) if ( idx < answer ) break ; ++ answer ; } return answer ; }
Count the number of occurrences of a sub CharSequence .
115
12
143,237
public static < T extends CharSequence > T eachMatch ( T self , CharSequence regex , @ ClosureParams ( value = FromString . class , options = { "List<String>" , "String[]" } ) Closure closure ) { eachMatch ( self . toString ( ) , regex . toString ( ) , closure ) ; return self ; }
Process each regex group matched substring of the given CharSequence . If the closure parameter takes one argument an array with all match groups is passed to it . If the closure takes as many arguments as there are match groups then each parameter will be one match group .
78
53
143,238
public static String eachMatch ( String self , String regex , @ ClosureParams ( value = FromString . class , options = { "List<String>" , "String[]" } ) Closure closure ) { return eachMatch ( self , Pattern . compile ( regex ) , closure ) ; }
Process each regex group matched substring of the given string . If the closure parameter takes one argument an array with all match groups is passed to it . If the closure takes as many arguments as there are match groups then each parameter will be one match group .
62
51
143,239
public static String expandLine ( CharSequence self , int tabStop ) { String s = self . toString ( ) ; int index ; while ( ( index = s . indexOf ( ' ' ) ) != - 1 ) { StringBuilder builder = new StringBuilder ( s ) ; int count = tabStop - index % tabStop ; builder . deleteCharAt ( index ) ; for ( int i = 0 ; i < count ; i ++ ) builder . insert ( index , " " ) ; s = builder . toString ( ) ; } return s ; }
Expands all tabs into spaces . Assumes the CharSequence represents a single line of text .
117
20
143,240
public static String find ( CharSequence self , CharSequence regex , @ ClosureParams ( value = SimpleType . class , options = "java.lang.String[]" ) Closure closure ) { return find ( self . toString ( ) , Pattern . compile ( regex . toString ( ) ) , closure ) ; }
Returns the result of calling a closure with the first occurrence of a regular expression found within a CharSequence . If the regex doesn t match the closure will not be called and find will return null .
70
40
143,241
public static String getAt ( CharSequence self , Collection indices ) { StringBuilder answer = new StringBuilder ( ) ; for ( Object value : indices ) { if ( value instanceof Range ) { answer . append ( getAt ( self , ( Range ) value ) ) ; } else if ( value instanceof Collection ) { answer . append ( getAt ( self , ( Collection ) value ) ) ; } else { int idx = DefaultTypeTransformation . intUnbox ( value ) ; answer . append ( getAt ( self , idx ) ) ; } } return answer . toString ( ) ; }
Select a List of characters from a CharSequence using a Collection to identify the indices to be selected .
127
21
143,242
public static CharSequence getAt ( CharSequence text , int index ) { index = normaliseIndex ( index , text . length ( ) ) ; return text . subSequence ( index , index + 1 ) ; }
Support the subscript operator for CharSequence .
47
9
143,243
public static String getAt ( GString text , int index ) { return ( String ) getAt ( text . toString ( ) , index ) ; }
Support the subscript operator for GString .
32
8
143,244
public static CharSequence getAt ( CharSequence text , IntRange range ) { return getAt ( text , ( Range ) range ) ; }
Support the range subscript operator for CharSequence with IntRange
31
12
143,245
public static CharSequence getAt ( CharSequence text , Range range ) { RangeInfo info = subListBorders ( text . length ( ) , range ) ; CharSequence sequence = text . subSequence ( info . from , info . to ) ; return info . reverse ? reverse ( sequence ) : sequence ; }
Support the range subscript operator for CharSequence
68
9
143,246
public static String getAt ( GString text , Range range ) { return getAt ( text . toString ( ) , range ) ; }
Support the range subscript operator for GString
29
8
143,247
public static List getAt ( Matcher self , Collection indices ) { List result = new ArrayList ( ) ; for ( Object value : indices ) { if ( value instanceof Range ) { result . addAll ( getAt ( self , ( Range ) value ) ) ; } else { int idx = DefaultTypeTransformation . intUnbox ( value ) ; result . add ( getAt ( self , idx ) ) ; } } return result ; }
Select a List of values from a Matcher using a Collection to identify the indices to be selected .
95
20
143,248
public static String getAt ( String text , int index ) { index = normaliseIndex ( index , text . length ( ) ) ; return text . substring ( index , index + 1 ) ; }
Support the subscript operator for String .
42
7
143,249
public static String getAt ( String text , IntRange range ) { return getAt ( text , ( Range ) range ) ; }
Support the range subscript operator for String with IntRange
27
10
143,250
public static String getAt ( String text , Range range ) { RangeInfo info = subListBorders ( text . length ( ) , range ) ; String answer = text . substring ( info . from , info . to ) ; if ( info . reverse ) { answer = reverse ( answer ) ; } return answer ; }
Support the range subscript operator for String
67
7
143,251
public static int getCount ( Matcher matcher ) { int counter = 0 ; matcher . reset ( ) ; while ( matcher . find ( ) ) { counter ++ ; } return counter ; }
Find the number of Strings matched to the given Matcher .
42
13
143,252
public static boolean isAllWhitespace ( CharSequence self ) { String s = self . toString ( ) ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( ! Character . isWhitespace ( s . charAt ( i ) ) ) return false ; } return true ; }
True if a CharSequence only contains whitespace characters .
71
12
143,253
public static boolean isBigDecimal ( CharSequence self ) { try { new BigDecimal ( self . toString ( ) . trim ( ) ) ; return true ; } catch ( NumberFormatException nfe ) { return false ; } }
Determine if a CharSequence can be parsed as a BigDecimal .
51
17
143,254
public static boolean isBigInteger ( CharSequence self ) { try { new BigInteger ( self . toString ( ) . trim ( ) ) ; return true ; } catch ( NumberFormatException nfe ) { return false ; } }
Determine if a CharSequence can be parsed as a BigInteger .
49
16
143,255
public static boolean isDouble ( CharSequence self ) { try { Double . valueOf ( self . toString ( ) . trim ( ) ) ; return true ; } catch ( NumberFormatException nfe ) { return false ; } }
Determine if a CharSequence can be parsed as a Double .
49
15
143,256
public static boolean isFloat ( CharSequence self ) { try { Float . valueOf ( self . toString ( ) . trim ( ) ) ; return true ; } catch ( NumberFormatException nfe ) { return false ; } }
Determine if a CharSequence can be parsed as a Float .
49
15
143,257
public static boolean isInteger ( CharSequence self ) { try { Integer . valueOf ( self . toString ( ) . trim ( ) ) ; return true ; } catch ( NumberFormatException nfe ) { return false ; } }
Determine if a CharSequence can be parsed as an Integer .
49
15
143,258
public static boolean isLong ( CharSequence self ) { try { Long . valueOf ( self . toString ( ) . trim ( ) ) ; return true ; } catch ( NumberFormatException nfe ) { return false ; } }
Determine if a CharSequence can be parsed as a Long .
49
15
143,259
public static StringBuffer leftShift ( String self , Object value ) { return new StringBuffer ( self ) . append ( value ) ; }
Overloads the left shift operator to provide an easy way to append multiple objects as string representations to a String .
28
22
143,260
public static StringBuilder leftShift ( StringBuilder self , Object value ) { self . append ( value ) ; return self ; }
Overloads the left shift operator to provide syntactic sugar for appending to a StringBuilder .
26
19
143,261
public static String minus ( CharSequence self , Object target ) { String s = self . toString ( ) ; String text = DefaultGroovyMethods . toString ( target ) ; int index = s . indexOf ( text ) ; if ( index == - 1 ) return s ; int end = index + text . length ( ) ; if ( s . length ( ) > end ) { return s . substring ( 0 , index ) + s . substring ( end ) ; } return s . substring ( 0 , index ) ; }
Remove a part of a CharSequence by replacing the first occurrence of target within self with and returns the result .
113
23
143,262
public static String minus ( CharSequence self , Pattern pattern ) { return pattern . matcher ( self ) . replaceFirst ( "" ) ; }
Remove a part of a CharSequence . This replaces the first occurrence of the pattern within self with and returns the result .
30
25
143,263
public static String multiply ( CharSequence self , Number factor ) { String s = self . toString ( ) ; int size = factor . intValue ( ) ; if ( size == 0 ) return "" ; else if ( size < 0 ) { throw new IllegalArgumentException ( "multiply() should be called with a number of 0 or greater not: " + size ) ; } StringBuilder answer = new StringBuilder ( s ) ; for ( int i = 1 ; i < size ; i ++ ) { answer . append ( s ) ; } return answer . toString ( ) ; }
Repeat a CharSequence a certain number of times .
124
11
143,264
public static String next ( CharSequence self ) { StringBuilder buffer = new StringBuilder ( self ) ; if ( buffer . length ( ) == 0 ) { buffer . append ( Character . MIN_VALUE ) ; } else { char last = buffer . charAt ( buffer . length ( ) - 1 ) ; if ( last == Character . MAX_VALUE ) { buffer . append ( Character . MIN_VALUE ) ; } else { char next = last ; next ++ ; buffer . setCharAt ( buffer . length ( ) - 1 , next ) ; } } return buffer . toString ( ) ; }
This method is called by the ++ operator for the class CharSequence . It increments the last character in the given CharSequence . If the last character in the CharSequence is Character . MAX_VALUE a Character . MIN_VALUE will be appended . The empty CharSequence is incremented to a string consisting of the character Character . MIN_VALUE .
125
74
143,265
public static String normalize ( final CharSequence self ) { final String s = self . toString ( ) ; int nx = s . indexOf ( ' ' ) ; if ( nx < 0 ) { return s ; } final int len = s . length ( ) ; final StringBuilder sb = new StringBuilder ( len ) ; int i = 0 ; do { sb . append ( s , i , nx ) ; sb . append ( ' ' ) ; if ( ( i = nx + 1 ) >= len ) break ; if ( s . charAt ( i ) == ' ' ) { // skip the LF in CR LF if ( ++ i >= len ) break ; } nx = s . indexOf ( ' ' , i ) ; } while ( nx > 0 ) ; sb . append ( s , i , len ) ; return sb . toString ( ) ; }
Return a String with linefeeds and carriage returns normalized to linefeeds .
192
16
143,266
public static String plus ( CharSequence left , Object value ) { return left + DefaultGroovyMethods . toString ( value ) ; }
Appends the String representation of the given operand to this CharSequence .
29
16
143,267
public static String plus ( Number value , String right ) { return DefaultGroovyMethods . toString ( value ) + right ; }
Appends a String to the string representation of this number .
27
12
143,268
public static List < String > readLines ( CharSequence self ) throws IOException { return IOGroovyMethods . readLines ( new StringReader ( self . toString ( ) ) ) ; }
Return the lines of a CharSequence as a List of String .
44
14
143,269
public static String replaceAll ( final CharSequence self , final CharSequence regex , final CharSequence replacement ) { return self . toString ( ) . replaceAll ( regex . toString ( ) , replacement . toString ( ) ) ; }
Replaces each substring of this CharSequence that matches the given regular expression with the given replacement .
52
21
143,270
public static String replaceFirst ( final CharSequence self , final CharSequence regex , final CharSequence replacement ) { return self . toString ( ) . replaceFirst ( regex . toString ( ) , replacement . toString ( ) ) ; }
Replaces the first substring of this CharSequence that matches the given regular expression with the given replacement .
52
22
143,271
public static void setIndex ( Matcher matcher , int idx ) { int count = getCount ( matcher ) ; if ( idx < - count || idx >= count ) { throw new IndexOutOfBoundsException ( "index is out of range " + ( - count ) + ".." + ( count - 1 ) + " (index = " + idx + ")" ) ; } if ( idx == 0 ) { matcher . reset ( ) ; } else if ( idx > 0 ) { matcher . reset ( ) ; for ( int i = 0 ; i < idx ; i ++ ) { matcher . find ( ) ; } } else if ( idx < 0 ) { matcher . reset ( ) ; idx += getCount ( matcher ) ; for ( int i = 0 ; i < idx ; i ++ ) { matcher . find ( ) ; } } }
Set the position of the given Matcher to the given index .
195
13
143,272
public static < T > T splitEachLine ( CharSequence self , CharSequence regex , @ ClosureParams ( value = FromString . class , options = "List<String>" ) Closure < T > closure ) throws IOException { return splitEachLine ( self , Pattern . compile ( regex . toString ( ) ) , closure ) ; }
Iterates through the given CharSequence line by line splitting each line using the given regex delimiter . The list of tokens for each line is then passed to the given closure .
75
36
143,273
public static < T > T splitEachLine ( CharSequence self , Pattern pattern , @ ClosureParams ( value = FromString . class , options = "List<String>" ) Closure < T > closure ) throws IOException { final List < String > list = readLines ( self ) ; T result = null ; for ( String line : list ) { List vals = Arrays . asList ( pattern . split ( line ) ) ; result = closure . call ( vals ) ; } return result ; }
Iterates through the given CharSequence line by line splitting each line using the given separator Pattern . The list of tokens for each line is then passed to the given closure .
110
36
143,274
public static String takeWhile ( GString self , @ ClosureParams ( value = SimpleType . class , options = "char" ) Closure condition ) { return ( String ) takeWhile ( self . toString ( ) , condition ) ; }
A GString variant of the equivalent GString method .
52
11
143,275
public static List < String > toList ( CharSequence self ) { String s = self . toString ( ) ; int size = s . length ( ) ; List < String > answer = new ArrayList < String > ( size ) ; for ( int i = 0 ; i < size ; i ++ ) { answer . add ( s . substring ( i , i + 1 ) ) ; } return answer ; }
Converts the given CharSequence into a List of Strings of one character .
87
17
143,276
public static String unexpand ( CharSequence self , int tabStop ) { String s = self . toString ( ) ; if ( s . length ( ) == 0 ) return s ; try { StringBuilder builder = new StringBuilder ( ) ; for ( String line : readLines ( ( CharSequence ) s ) ) { builder . append ( unexpandLine ( line , tabStop ) ) ; builder . append ( "\n" ) ; } // remove the normalized ending line ending if it was not present if ( ! s . endsWith ( "\n" ) ) { builder . deleteCharAt ( builder . length ( ) - 1 ) ; } return builder . toString ( ) ; } catch ( IOException e ) { /* ignore */ } return s ; }
Replaces sequences of whitespaces with tabs .
162
9
143,277
public static String unexpandLine ( CharSequence self , int tabStop ) { StringBuilder builder = new StringBuilder ( self . toString ( ) ) ; int index = 0 ; while ( index + tabStop < builder . length ( ) ) { // cut original string in tabstop-length pieces String piece = builder . substring ( index , index + tabStop ) ; // count trailing whitespace characters int count = 0 ; while ( ( count < tabStop ) && ( Character . isWhitespace ( piece . charAt ( tabStop - ( count + 1 ) ) ) ) ) count ++ ; // replace if whitespace was found if ( count > 0 ) { piece = piece . substring ( 0 , tabStop - count ) + ' ' ; builder . replace ( index , index + tabStop , piece ) ; index = index + tabStop - ( count - 1 ) ; } else index = index + tabStop ; } return builder . toString ( ) ; }
Replaces sequences of whitespaces with tabs within a line .
205
12
143,278
public boolean hasPossibleMethod ( String name , Expression arguments ) { int count = 0 ; if ( arguments instanceof TupleExpression ) { TupleExpression tuple = ( TupleExpression ) arguments ; // TODO this won't strictly be true when using list expansion in argument calls count = tuple . getExpressions ( ) . size ( ) ; } ClassNode node = this ; do { for ( MethodNode method : getMethods ( name ) ) { if ( method . getParameters ( ) . length == count && ! method . isStatic ( ) ) { return true ; } } node = node . getSuperClass ( ) ; } while ( node != null ) ; return false ; }
Returns true if the given method has a possibly matching instance method with the given name and arguments .
145
19
143,279
private void checkOrMarkPrivateAccess ( Expression source , FieldNode fn ) { if ( fn != null && Modifier . isPrivate ( fn . getModifiers ( ) ) && ( fn . getDeclaringClass ( ) != typeCheckingContext . getEnclosingClassNode ( ) || typeCheckingContext . getEnclosingClosure ( ) != null ) && fn . getDeclaringClass ( ) . getModule ( ) == typeCheckingContext . getEnclosingClassNode ( ) . getModule ( ) ) { addPrivateFieldOrMethodAccess ( source , fn . getDeclaringClass ( ) , StaticTypesMarker . PV_FIELDS_ACCESS , fn ) ; } }
Given a field node checks if we are calling a private field from an inner class .
148
17
143,280
private void checkOrMarkPrivateAccess ( Expression source , MethodNode mn ) { if ( mn == null ) { return ; } ClassNode declaringClass = mn . getDeclaringClass ( ) ; ClassNode enclosingClassNode = typeCheckingContext . getEnclosingClassNode ( ) ; if ( declaringClass != enclosingClassNode || typeCheckingContext . getEnclosingClosure ( ) != null ) { int mods = mn . getModifiers ( ) ; boolean sameModule = declaringClass . getModule ( ) == enclosingClassNode . getModule ( ) ; String packageName = declaringClass . getPackageName ( ) ; if ( packageName == null ) { packageName = "" ; } if ( ( Modifier . isPrivate ( mods ) && sameModule ) || ( Modifier . isProtected ( mods ) && ! packageName . equals ( enclosingClassNode . getPackageName ( ) ) ) ) { addPrivateFieldOrMethodAccess ( source , sameModule ? declaringClass : enclosingClassNode , StaticTypesMarker . PV_METHODS_ACCESS , mn ) ; } } }
Given a method node checks if we are calling a private method from an inner class .
238
17
143,281
private boolean ensureValidSetter ( final Expression expression , final Expression leftExpression , final Expression rightExpression , final SetterInfo setterInfo ) { // for expressions like foo = { ... } // we know that the RHS type is a closure // but we must check if the binary expression is an assignment // because we need to check if a setter uses @DelegatesTo VariableExpression ve = new VariableExpression ( "%" , setterInfo . receiverType ) ; MethodCallExpression call = new MethodCallExpression ( ve , setterInfo . name , rightExpression ) ; call . setImplicitThis ( false ) ; visitMethodCallExpression ( call ) ; MethodNode directSetterCandidate = call . getNodeMetaData ( StaticTypesMarker . DIRECT_METHOD_CALL_TARGET ) ; if ( directSetterCandidate == null ) { // this may happen if there's a setter of type boolean/String/Class, and that we are using the property // notation AND that the RHS is not a boolean/String/Class for ( MethodNode setter : setterInfo . setters ) { ClassNode type = getWrapper ( setter . getParameters ( ) [ 0 ] . getOriginType ( ) ) ; if ( Boolean_TYPE . equals ( type ) || STRING_TYPE . equals ( type ) || CLASS_Type . equals ( type ) ) { call = new MethodCallExpression ( ve , setterInfo . name , new CastExpression ( type , rightExpression ) ) ; call . setImplicitThis ( false ) ; visitMethodCallExpression ( call ) ; directSetterCandidate = call . getNodeMetaData ( StaticTypesMarker . DIRECT_METHOD_CALL_TARGET ) ; if ( directSetterCandidate != null ) { break ; } } } } if ( directSetterCandidate != null ) { for ( MethodNode setter : setterInfo . setters ) { if ( setter == directSetterCandidate ) { leftExpression . putNodeMetaData ( StaticTypesMarker . DIRECT_METHOD_CALL_TARGET , directSetterCandidate ) ; storeType ( leftExpression , getType ( rightExpression ) ) ; break ; } } } else { ClassNode firstSetterType = setterInfo . setters . iterator ( ) . next ( ) . getParameters ( ) [ 0 ] . getOriginType ( ) ; addAssignmentError ( firstSetterType , getType ( rightExpression ) , expression ) ; return true ; } return false ; }
Given a binary expression corresponding to an assignment will check that the type of the RHS matches one of the possible setters and if not throw a type checking error .
549
33
143,282
private void addArrayMethods ( List < MethodNode > methods , ClassNode receiver , String name , ClassNode [ ] args ) { if ( args . length != 1 ) return ; if ( ! receiver . isArray ( ) ) return ; if ( ! isIntCategory ( getUnwrapper ( args [ 0 ] ) ) ) return ; if ( "getAt" . equals ( name ) ) { MethodNode node = new MethodNode ( name , Opcodes . ACC_PUBLIC , receiver . getComponentType ( ) , new Parameter [ ] { new Parameter ( args [ 0 ] , "arg" ) } , null , null ) ; node . setDeclaringClass ( receiver . redirect ( ) ) ; methods . add ( node ) ; } else if ( "setAt" . equals ( name ) ) { MethodNode node = new MethodNode ( name , Opcodes . ACC_PUBLIC , VOID_TYPE , new Parameter [ ] { new Parameter ( args [ 0 ] , "arg" ) } , null , null ) ; node . setDeclaringClass ( receiver . redirect ( ) ) ; methods . add ( node ) ; } }
add various getAt and setAt methods for primitive arrays
242
11
143,283
private ClassNode getGenericsResolvedTypeOfFieldOrProperty ( AnnotatedNode an , ClassNode type ) { if ( ! type . isUsingGenerics ( ) ) return type ; Map < String , GenericsType > connections = new HashMap ( ) ; //TODO: inner classes mean a different this-type. This is ignored here! extractGenericsConnections ( connections , typeCheckingContext . getEnclosingClassNode ( ) , an . getDeclaringClass ( ) ) ; type = applyGenericsContext ( connections , type ) ; return type ; }
resolves a Field or Property node generics by using the current class and the declaring class to extract the right meaning of the generics symbols
123
28
143,284
public static byte [ ] decodeBase64 ( String value ) { int byteShift = 4 ; int tmp = 0 ; boolean done = false ; final StringBuilder buffer = new StringBuilder ( ) ; for ( int i = 0 ; i != value . length ( ) ; i ++ ) { final char c = value . charAt ( i ) ; final int sixBit = ( c < 123 ) ? EncodingGroovyMethodsSupport . TRANSLATE_TABLE [ c ] : 66 ; if ( sixBit < 64 ) { if ( done ) throw new RuntimeException ( "= character not at end of base64 value" ) ; // TODO: change this exception type tmp = ( tmp << 6 ) | sixBit ; if ( byteShift -- != 4 ) { buffer . append ( ( char ) ( ( tmp >> ( byteShift * 2 ) ) & 0XFF ) ) ; } } else if ( sixBit == 64 ) { byteShift -- ; done = true ; } else if ( sixBit == 66 ) { // RFC 2045 says that I'm allowed to take the presence of // these characters as evidence of data corruption // So I will throw new RuntimeException ( "bad character in base64 value" ) ; // TODO: change this exception type } if ( byteShift == 0 ) byteShift = 4 ; } try { return buffer . toString ( ) . getBytes ( "ISO-8859-1" ) ; } catch ( UnsupportedEncodingException e ) { throw new RuntimeException ( "Base 64 decode produced byte values > 255" ) ; // TODO: change this exception type } }
Decode the String from Base64 into a byte array .
336
12
143,285
protected void runStatements ( Reader reader , PrintStream out ) throws IOException { log . debug ( "runStatements()" ) ; StringBuilder txt = new StringBuilder ( ) ; String line = "" ; BufferedReader in = new BufferedReader ( reader ) ; while ( ( line = in . readLine ( ) ) != null ) { line = getProject ( ) . replaceProperties ( line ) ; if ( line . indexOf ( "--" ) >= 0 ) { txt . append ( "\n" ) ; } } // Catch any statements not followed by ; if ( ! txt . toString ( ) . equals ( "" ) ) { execGroovy ( txt . toString ( ) , out ) ; } }
Read in lines and execute them .
157
7
143,286
public static String toJson ( Date date ) { if ( date == null ) { return NULL_VALUE ; } CharBuf buffer = CharBuf . create ( 26 ) ; writeDate ( date , buffer ) ; return buffer . toString ( ) ; }
Format a date that is parseable from JavaScript according to ISO - 8601 .
55
16
143,287
public static String toJson ( Calendar cal ) { if ( cal == null ) { return NULL_VALUE ; } CharBuf buffer = CharBuf . create ( 26 ) ; writeDate ( cal . getTime ( ) , buffer ) ; return buffer . toString ( ) ; }
Format a calendar instance that is parseable from JavaScript according to ISO - 8601 .
60
17
143,288
private static void writeNumber ( Class < ? > numberClass , Number value , CharBuf buffer ) { if ( numberClass == Integer . class ) { buffer . addInt ( ( Integer ) value ) ; } else if ( numberClass == Long . class ) { buffer . addLong ( ( Long ) value ) ; } else if ( numberClass == BigInteger . class ) { buffer . addBigInteger ( ( BigInteger ) value ) ; } else if ( numberClass == BigDecimal . class ) { buffer . addBigDecimal ( ( BigDecimal ) value ) ; } else if ( numberClass == Double . class ) { Double doubleValue = ( Double ) value ; if ( doubleValue . isInfinite ( ) ) { throw new JsonException ( "Number " + value + " can't be serialized as JSON: infinite are not allowed in JSON." ) ; } if ( doubleValue . isNaN ( ) ) { throw new JsonException ( "Number " + value + " can't be serialized as JSON: NaN are not allowed in JSON." ) ; } buffer . addDouble ( doubleValue ) ; } else if ( numberClass == Float . class ) { Float floatValue = ( Float ) value ; if ( floatValue . isInfinite ( ) ) { throw new JsonException ( "Number " + value + " can't be serialized as JSON: infinite are not allowed in JSON." ) ; } if ( floatValue . isNaN ( ) ) { throw new JsonException ( "Number " + value + " can't be serialized as JSON: NaN are not allowed in JSON." ) ; } buffer . addFloat ( floatValue ) ; } else if ( numberClass == Byte . class ) { buffer . addByte ( ( Byte ) value ) ; } else if ( numberClass == Short . class ) { buffer . addShort ( ( Short ) value ) ; } else { // Handle other Number implementations buffer . addString ( value . toString ( ) ) ; } }
Serializes Number value and writes it into specified buffer .
424
11
143,289
private static void writeCharSequence ( CharSequence seq , CharBuf buffer ) { if ( seq . length ( ) > 0 ) { buffer . addJsonEscapedString ( seq . toString ( ) ) ; } else { buffer . addChars ( EMPTY_STRING_CHARS ) ; } }
Serializes any char sequence and writes it into specified buffer .
68
12
143,290
public static Enum castToEnum ( Object object , Class < ? extends Enum > type ) { if ( object == null ) return null ; if ( type . isInstance ( object ) ) return ( Enum ) object ; if ( object instanceof String || object instanceof GString ) { return Enum . valueOf ( type , object . toString ( ) ) ; } throw new GroovyCastException ( object , type ) ; }
this class requires that the supplied enum is not fitting a Collection case for casting
93
15
143,291
public void setTargetBytecode ( String version ) { if ( CompilerConfiguration . PRE_JDK5 . equals ( version ) || CompilerConfiguration . POST_JDK5 . equals ( version ) ) { this . targetBytecode = version ; } }
Sets the bytecode compatibility mode
54
7
143,292
public List depthFirst ( ) { List answer = new NodeList ( ) ; answer . add ( this ) ; answer . addAll ( depthFirstRest ( ) ) ; return answer ; }
Provides a collection of all the nodes in the tree using a depth first traversal .
39
18
143,293
public static String getGetterName ( String propertyName , Class type ) { String prefix = type == boolean . class || type == Boolean . class ? "is" : "get" ; return prefix + MetaClassHelper . capitalize ( propertyName ) ; }
Gets the name for the getter for this property
53
11
143,294
public static ProxyMetaClass getInstance ( Class theClass ) throws IntrospectionException { MetaClassRegistry metaRegistry = GroovySystem . getMetaClassRegistry ( ) ; MetaClass meta = metaRegistry . getMetaClass ( theClass ) ; return new ProxyMetaClass ( metaRegistry , theClass , meta ) ; }
convenience factory method for the most usual case .
70
11
143,295
private Expression correctClassClassChain ( PropertyExpression pe ) { LinkedList < Expression > stack = new LinkedList < Expression > ( ) ; ClassExpression found = null ; for ( Expression it = pe ; it != null ; it = ( ( PropertyExpression ) it ) . getObjectExpression ( ) ) { if ( it instanceof ClassExpression ) { found = ( ClassExpression ) it ; break ; } else if ( ! ( it . getClass ( ) == PropertyExpression . class ) ) { return pe ; } stack . addFirst ( it ) ; } if ( found == null ) return pe ; if ( stack . isEmpty ( ) ) return pe ; Object stackElement = stack . removeFirst ( ) ; if ( ! ( stackElement . getClass ( ) == PropertyExpression . class ) ) return pe ; PropertyExpression classPropertyExpression = ( PropertyExpression ) stackElement ; String propertyNamePart = classPropertyExpression . getPropertyAsString ( ) ; if ( propertyNamePart == null || ! propertyNamePart . equals ( "class" ) ) return pe ; found . setSourcePosition ( classPropertyExpression ) ; if ( stack . isEmpty ( ) ) return found ; stackElement = stack . removeFirst ( ) ; if ( ! ( stackElement . getClass ( ) == PropertyExpression . class ) ) return pe ; PropertyExpression classPropertyExpressionContainer = ( PropertyExpression ) stackElement ; classPropertyExpressionContainer . setObjectExpression ( found ) ; return pe ; }
and class as property
324
4
143,296
public static void closeWithWarning ( Closeable c ) { if ( c != null ) { try { c . close ( ) ; } catch ( IOException e ) { LOG . warning ( "Caught exception during close(): " + e ) ; } } }
Close the Closeable . Logging a warning if any problems occur .
54
14
143,297
public V get ( K key ) { ManagedReference < V > ref = internalMap . get ( key ) ; if ( ref != null ) return ref . get ( ) ; return null ; }
Returns the value stored for the given key at the point of call .
41
14
143,298
public void put ( final K key , V value ) { ManagedReference < V > ref = new ManagedReference < V > ( bundle , value ) { @ Override public void finalizeReference ( ) { super . finalizeReference ( ) ; internalMap . remove ( key , get ( ) ) ; } } ; internalMap . put ( key , ref ) ; }
Sets a new value for a given key . an older value is overwritten .
78
17
143,299
public String getSample ( int line , int column , Janitor janitor ) { String sample = null ; String text = source . getLine ( line , janitor ) ; if ( text != null ) { if ( column > 0 ) { String marker = Utilities . repeatString ( " " , column - 1 ) + "^" ; if ( column > 40 ) { int start = column - 30 - 1 ; int end = ( column + 10 > text . length ( ) ? text . length ( ) : column + 10 - 1 ) ; sample = " " + text . substring ( start , end ) + Utilities . eol ( ) + " " + marker . substring ( start , marker . length ( ) ) ; } else { sample = " " + text + Utilities . eol ( ) + " " + marker ; } } else { sample = text ; } } return sample ; }
Returns a sampling of the source at the specified line and column of null if it is unavailable .
188
19