idx int64 0 41.2k | question stringlengths 74 4.04k | target stringlengths 7 750 |
|---|---|---|
24,700 | public static Type capture ( Type type ) { VarMap varMap = new VarMap ( ) ; List < CaptureTypeImpl > toInit = new ArrayList < > ( ) ; if ( type instanceof ParameterizedType ) { ParameterizedType pType = ( ParameterizedType ) type ; Class < ? > clazz = ( Class < ? > ) pType . getRawType ( ) ; Type [ ] arguments = pType . getActualTypeArguments ( ) ; TypeVariable < ? > [ ] vars = clazz . getTypeParameters ( ) ; Type [ ] capturedArguments = new Type [ arguments . length ] ; assert arguments . length == vars . length ; for ( int i = 0 ; i < arguments . length ; i ++ ) { Type argument = arguments [ i ] ; if ( argument instanceof WildcardType ) { CaptureTypeImpl captured = new CaptureTypeImpl ( ( WildcardType ) argument , vars [ i ] ) ; argument = captured ; toInit . add ( captured ) ; } capturedArguments [ i ] = argument ; varMap . add ( vars [ i ] , argument ) ; } for ( CaptureTypeImpl captured : toInit ) { captured . init ( varMap ) ; } Type ownerType = ( pType . getOwnerType ( ) == null ) ? null : capture ( pType . getOwnerType ( ) ) ; return new ParameterizedTypeImpl ( clazz , capturedArguments , ownerType ) ; } else { return type ; } } | Applies capture conversion to the given type . |
24,701 | public static String getTypeName ( Type type ) { if ( type instanceof Class ) { Class < ? > clazz = ( Class < ? > ) type ; return clazz . isArray ( ) ? ( getTypeName ( clazz . getComponentType ( ) ) + "[]" ) : clazz . getName ( ) ; } else { return type . toString ( ) ; } } | Returns the display name of a Type . |
24,702 | private static void buildUpperBoundClassAndInterfaces ( Type type , Set < Class < ? > > result ) { if ( type instanceof ParameterizedType || type instanceof Class < ? > ) { result . add ( erase ( type ) ) ; return ; } for ( Type superType : getExactDirectSuperTypes ( type ) ) { buildUpperBoundClassAndInterfaces ( superType , result ) ; } } | Helper method for getUpperBoundClassAndInterfaces adding the result to the given set . |
24,703 | public < T > T Mock ( @ NamedParams ( { @ NamedParam ( value = "name" , type = String . class ) , @ NamedParam ( value = "additionalInterfaces" , type = List . class ) , @ NamedParam ( value = "defaultResponse" , type = IDefaultResponse . class ) , @ NamedParam ( value = "verified" , type = Boolean . class ) , @ NamedParam ( value = "useObjenesis" , type = Boolean . class ) } ) Map < String , Object > options ) { invalidMockCreation ( ) ; return null ; } | Creates a mock with the specified options whose type and name are inferred from the left - hand side of the enclosing variable assignment . |
24,704 | public < T > T Mock ( Map < String , Object > options , Closure interactions ) { invalidMockCreation ( ) ; return null ; } | Creates a mock with the specified options and interactions whose type and name are inferred from the left - hand side of the enclosing assignment . |
24,705 | public < T > T Stub ( Class < T > type ) { invalidMockCreation ( ) ; return null ; } | Creates a stub with the specified type . If enclosed in a variable assignment the variable name will be used as the stub s name . |
24,706 | public < T > T Spy ( Class < T > type ) { invalidMockCreation ( ) ; return null ; } | Creates a spy with the specified type . If enclosed in a variable assignment the variable name will be used as the spy s name . |
24,707 | private boolean hasExpandableVarArgs ( IMockMethod method , List < Object > args ) { List < Class < ? > > paramTypes = method . getParameterTypes ( ) ; return ! paramTypes . isEmpty ( ) && CollectionUtil . getLastElement ( paramTypes ) . isArray ( ) && CollectionUtil . getLastElement ( args ) != null ; } | Tells if the given method call has expandable varargs . Note that Groovy supports vararg syntax for all methods whose last parameter is of array type . |
24,708 | public void load ( @ Language ( "Groovy" ) String sourceText ) throws CompilationFailedException { reset ( ) ; try { classLoader . parseClass ( sourceText ) ; } catch ( AstSuccessfullyCaptured e ) { indexAstNodes ( ) ; return ; } throw new AstInspectorException ( "internal error" ) ; } | Compiles the specified source text up to the configured compile phase and stores the resulting AST for subsequent inspection . |
24,709 | public void load ( File sourceFile ) throws CompilationFailedException { reset ( ) ; try { classLoader . parseClass ( sourceFile ) ; } catch ( IOException e ) { throw new AstInspectorException ( "cannot read source file" , e ) ; } catch ( AstSuccessfullyCaptured e ) { indexAstNodes ( ) ; return ; } throw new AstInspectorException ( "internal error" ) ; } | Compiles the source text in the specified file up to the configured compile phase and stores the resulting AST for subsequent inspection . |
24,710 | private int estimateNumIterations ( Object [ ] dataProviders ) { if ( runStatus != OK ) return - 1 ; if ( dataProviders . length == 0 ) return 1 ; int result = Integer . MAX_VALUE ; for ( Object prov : dataProviders ) { if ( prov instanceof Iterator ) continue ; Object rawSize = GroovyRuntimeUtil . invokeMethodQuietly ( prov , "size" ) ; if ( ! ( rawSize instanceof Number ) ) continue ; int size = ( ( Number ) rawSize ) . intValue ( ) ; if ( size < 0 || size >= result ) continue ; result = size ; } return result == Integer . MAX_VALUE ? - 1 : result ; } | - 1 = > unknown |
24,711 | private Object [ ] nextArgs ( Iterator [ ] iterators ) { if ( runStatus != OK ) return null ; Object [ ] next = new Object [ iterators . length ] ; for ( int i = 0 ; i < iterators . length ; i ++ ) try { next [ i ] = iterators [ i ] . next ( ) ; } catch ( Throwable t ) { runStatus = supervisor . error ( new ErrorInfo ( currentFeature . getDataProviders ( ) . get ( i ) . getDataProviderMethod ( ) , t ) ) ; return null ; } try { return ( Object [ ] ) invokeRaw ( sharedInstance , currentFeature . getDataProcessorMethod ( ) , next ) ; } catch ( Throwable t ) { runStatus = supervisor . error ( new ErrorInfo ( currentFeature . getDataProcessorMethod ( ) , t ) ) ; return null ; } } | advances iterators and computes args |
24,712 | public < T > T Mock ( Class < T > type ) { return createMock ( inferNameFromType ( type ) , type , MockNature . MOCK , Collections . < String , Object > emptyMap ( ) ) ; } | Creates a mock with the specified type . The mock name will be the types simple name . |
24,713 | public < T > T Mock ( Map < String , Object > options , Class < T > type ) { return createMock ( inferNameFromType ( type ) , type , MockNature . MOCK , options ) ; } | Creates a mock with the specified options and type . The mock name will be the types simple name . |
24,714 | public < T > T Stub ( Class < T > type ) { return createMock ( inferNameFromType ( type ) , type , MockNature . STUB , Collections . < String , Object > emptyMap ( ) ) ; } | Creates a stub with the specified type . The mock name will be the types simple name . |
24,715 | public < T > T Stub ( Map < String , Object > options , Class < T > type ) { return createMock ( inferNameFromType ( type ) , type , MockNature . STUB , options ) ; } | Creates a stub with the specified options and type . The mock name will be the types simple name . |
24,716 | public < T > T Spy ( Class < T > type ) { return createMock ( inferNameFromType ( type ) , type , MockNature . SPY , Collections . < String , Object > emptyMap ( ) ) ; } | Creates a spy with the specified type . The mock name will be the types simple name . |
24,717 | public < T > T Spy ( Map < String , Object > options , Class < T > type ) { return createMock ( inferNameFromType ( type ) , type , MockNature . SPY , options ) ; } | Creates a spy with the specified options and type . The mock name will be the types simple name . |
24,718 | public static int getFeatureCount ( Class < ? > spec ) { checkIsSpec ( spec ) ; int count = 0 ; do { for ( Method method : spec . getDeclaredMethods ( ) ) if ( method . isAnnotationPresent ( FeatureMetadata . class ) ) count ++ ; spec = spec . getSuperclass ( ) ; } while ( spec != null && isSpec ( spec ) ) ; return count ; } | Returns the number of features contained in the given specification . Because Spock allows for the dynamic creation of new features at specification run time this number is only an estimate . |
24,719 | public boolean hasBytecodeName ( String name ) { if ( featureMethod . hasBytecodeName ( name ) ) return true ; if ( dataProcessorMethod != null && dataProcessorMethod . hasBytecodeName ( name ) ) return true ; for ( DataProviderInfo provider : dataProviders ) if ( provider . getDataProviderMethod ( ) . hasBytecodeName ( name ) ) return true ; return false ; } | Tells if any of the methods associated with this feature has the specified name in bytecode . |
24,720 | @ SuppressWarnings ( "unchecked" ) public static List < Statement > getStatements ( MethodNode method ) { Statement code = method . getCode ( ) ; if ( ! ( code instanceof BlockStatement ) ) { BlockStatement block = new BlockStatement ( ) ; if ( code != null ) block . addStatement ( code ) ; method . setCode ( block ) ; } return ( ( BlockStatement ) method . getCode ( ) ) . getStatements ( ) ; } | Returns a list of statements of the given method . Modifications to the returned list will affect the method s statements . |
24,721 | public static void fixUpLocalVariables ( List < ? extends Variable > localVariables , VariableScope scope , boolean isClosureScope ) { for ( Variable localVar : localVariables ) { Variable scopeVar = scope . getReferencedClassVariable ( localVar . getName ( ) ) ; if ( scopeVar instanceof DynamicVariable ) { scope . removeReferencedClassVariable ( localVar . getName ( ) ) ; scope . putReferencedLocalVariable ( localVar ) ; if ( isClosureScope ) localVar . setClosureSharedVariable ( true ) ; } } } | Fixes up scope references to variables that used to be free or class variables and have been changed to local variables . |
24,722 | private void beforeKey ( ) throws JSONException { Scope context = peek ( ) ; if ( context == Scope . NONEMPTY_OBJECT ) { out . append ( ',' ) ; } else if ( context != Scope . EMPTY_OBJECT ) { throw new JSONException ( "Nesting problem" ) ; } newline ( ) ; replaceTop ( Scope . DANGLING_KEY ) ; } | Inserts any necessary separators and whitespace before a name . Also adjusts the stack to expect the key s value . |
24,723 | public String getAuthorizationHeader ( HttpRequest req ) { return generateAuthorizationHeader ( req . getMethod ( ) . name ( ) , req . getURL ( ) , req . getParameters ( ) , oauthToken ) ; } | implementations for Authorization |
24,724 | StatusStream getSampleStream ( ) throws TwitterException { ensureAuthorizationEnabled ( ) ; try { return new StatusStreamImpl ( getDispatcher ( ) , http . get ( conf . getStreamBaseURL ( ) + "statuses/sample.json?" + stallWarningsGetParam , null , auth , null ) , conf ) ; } catch ( IOException e ) { throw new TwitterException ( e ) ; } } | Returns a stream of random sample of all public statuses . The default access level provides a small proportion of the Firehose . The Gardenhose access level provides a proportion more suitable for data mining and research applications that desire a larger proportion to be statistically significant sample . |
24,725 | private void setHeaders ( HttpRequest req , HttpURLConnection connection ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Request: " ) ; logger . debug ( req . getMethod ( ) . name ( ) + " " , req . getURL ( ) ) ; } String authorizationHeader ; if ( req . getAuthorization ( ) != null && ( authorizationHeader = req . getAuthorization ( ) . getAuthorizationHeader ( req ) ) != null ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Authorization: " , authorizationHeader . replaceAll ( "." , "*" ) ) ; } connection . addRequestProperty ( "Authorization" , authorizationHeader ) ; } if ( req . getRequestHeaders ( ) != null ) { for ( String key : req . getRequestHeaders ( ) . keySet ( ) ) { connection . addRequestProperty ( key , req . getRequestHeaders ( ) . get ( key ) ) ; logger . debug ( key + ": " + req . getRequestHeaders ( ) . get ( key ) ) ; } } } | sets HTTP headers |
24,726 | public static List < HttpParameter > decodeParameters ( String queryParameters ) { List < HttpParameter > result = new ArrayList < HttpParameter > ( ) ; for ( String pair : queryParameters . split ( "&" ) ) { String [ ] parts = pair . split ( "=" , 2 ) ; if ( parts . length == 2 ) { String name = decode ( parts [ 0 ] ) ; String value = decode ( parts [ 1 ] ) ; if ( ! name . equals ( "" ) && ! value . equals ( "" ) ) result . add ( new HttpParameter ( name , value ) ) ; } } return result ; } | Parses a query string without the leading ? |
24,727 | public void getOAuthRequestTokenAsync ( ) { getDispatcher ( ) . invokeLater ( new AsyncTask ( OAUTH_REQUEST_TOKEN , listeners ) { public void invoke ( List < TwitterListener > listeners ) throws TwitterException { RequestToken token = twitter . getOAuthRequestToken ( ) ; for ( TwitterListener listener : listeners ) { try { listener . gotOAuthRequestToken ( token ) ; } catch ( Exception e ) { logger . warn ( "Exception at getOAuthRequestTokenAsync" , e ) ; } } } } ) ; } | implementation for AsyncOAuthSupport |
24,728 | public static Status createStatus ( String rawJSON ) throws TwitterException { try { return new StatusJSONImpl ( new JSONObject ( rawJSON ) ) ; } catch ( JSONException e ) { throw new TwitterException ( e ) ; } } | Constructs a Status object from rawJSON string . |
24,729 | public static User createUser ( String rawJSON ) throws TwitterException { try { return new UserJSONImpl ( new JSONObject ( rawJSON ) ) ; } catch ( JSONException e ) { throw new TwitterException ( e ) ; } } | Constructs a User object from rawJSON string . |
24,730 | public static AccountTotals createAccountTotals ( String rawJSON ) throws TwitterException { try { return new AccountTotalsJSONImpl ( new JSONObject ( rawJSON ) ) ; } catch ( JSONException e ) { throw new TwitterException ( e ) ; } } | Constructs an AccountTotals object from rawJSON string . |
24,731 | public static Relationship createRelationship ( String rawJSON ) throws TwitterException { try { return new RelationshipJSONImpl ( new JSONObject ( rawJSON ) ) ; } catch ( JSONException e ) { throw new TwitterException ( e ) ; } } | Constructs a Relationship object from rawJSON string . |
24,732 | public static Place createPlace ( String rawJSON ) throws TwitterException { try { return new PlaceJSONImpl ( new JSONObject ( rawJSON ) ) ; } catch ( JSONException e ) { throw new TwitterException ( e ) ; } } | Constructs a Place object from rawJSON string . |
24,733 | public static SavedSearch createSavedSearch ( String rawJSON ) throws TwitterException { try { return new SavedSearchJSONImpl ( new JSONObject ( rawJSON ) ) ; } catch ( JSONException e ) { throw new TwitterException ( e ) ; } } | Constructs a SavedSearch object from rawJSON string . |
24,734 | public static Trend createTrend ( String rawJSON ) throws TwitterException { try { return new TrendJSONImpl ( new JSONObject ( rawJSON ) ) ; } catch ( JSONException e ) { throw new TwitterException ( e ) ; } } | Constructs a Trend object from rawJSON string . |
24,735 | public static Map < String , RateLimitStatus > createRateLimitStatus ( String rawJSON ) throws TwitterException { try { return RateLimitStatusJSONImpl . createRateLimitStatuses ( new JSONObject ( rawJSON ) ) ; } catch ( JSONException e ) { throw new TwitterException ( e ) ; } } | Constructs a RateLimitStatus object from rawJSON string . |
24,736 | public static Category createCategory ( String rawJSON ) throws TwitterException { try { return new CategoryJSONImpl ( new JSONObject ( rawJSON ) ) ; } catch ( JSONException e ) { throw new TwitterException ( e ) ; } } | Constructs a Category object from rawJSON string . |
24,737 | public static DirectMessage createDirectMessage ( String rawJSON ) throws TwitterException { try { return new DirectMessageJSONImpl ( new JSONObject ( rawJSON ) ) ; } catch ( JSONException e ) { throw new TwitterException ( e ) ; } } | Constructs a DirectMessage object from rawJSON string . |
24,738 | public static Location createLocation ( String rawJSON ) throws TwitterException { try { return new LocationJSONImpl ( new JSONObject ( rawJSON ) ) ; } catch ( JSONException e ) { throw new TwitterException ( e ) ; } } | Constructs a Location object from rawJSON string . |
24,739 | public static UserList createUserList ( String rawJSON ) throws TwitterException { try { return new UserListJSONImpl ( new JSONObject ( rawJSON ) ) ; } catch ( JSONException e ) { throw new TwitterException ( e ) ; } } | Constructs a UserList object from rawJSON string . |
24,740 | public static OEmbed createOEmbed ( String rawJSON ) throws TwitterException { try { return new OEmbedJSONImpl ( new JSONObject ( rawJSON ) ) ; } catch ( JSONException e ) { throw new TwitterException ( e ) ; } } | Constructs an OEmbed object from rawJSON string . |
24,741 | protected final void setHttpProxyHost ( String proxyHost ) { httpConf = new MyHttpClientConfiguration ( proxyHost , httpConf . getHttpProxyUser ( ) , httpConf . getHttpProxyPassword ( ) , httpConf . getHttpProxyPort ( ) , httpConf . isHttpProxySocks ( ) , httpConf . getHttpConnectionTimeout ( ) , httpConf . getHttpReadTimeout ( ) , httpConf . isPrettyDebugEnabled ( ) , httpConf . isGZIPEnabled ( ) ) ; } | methods for HttpClientConfiguration |
24,742 | public Dispatcher getInstance ( ) { try { return ( Dispatcher ) Class . forName ( dispatcherImpl ) . getConstructor ( Configuration . class ) . newInstance ( conf ) ; } catch ( InstantiationException e ) { throw new AssertionError ( e ) ; } catch ( IllegalAccessException e ) { throw new AssertionError ( e ) ; } catch ( ClassNotFoundException e ) { throw new AssertionError ( e ) ; } catch ( ClassCastException e ) { throw new AssertionError ( e ) ; } catch ( NoSuchMethodException e ) { throw new AssertionError ( e ) ; } catch ( InvocationTargetException e ) { throw new AssertionError ( e ) ; } } | returns a Dispatcher instance . |
24,743 | static double checkDouble ( double d ) throws JSONException { if ( Double . isInfinite ( d ) || Double . isNaN ( d ) ) { throw new JSONException ( "Forbidden numeric value: " + d ) ; } return d ; } | Returns the input if it is a JSON - permissible value ; throws otherwise . |
24,744 | public Configuration getInstance ( String configTreePath ) { PropertyConfiguration conf = new PropertyConfiguration ( configTreePath ) ; conf . dumpConfiguration ( ) ; return conf ; } | It may be preferable to cache the config instance |
24,745 | private UploadedMedia uploadMediaChunkedFinalize ( long mediaId ) throws TwitterException { int tries = 0 ; int maxTries = 20 ; int lastProgressPercent = 0 ; int currentProgressPercent = 0 ; UploadedMedia uploadedMedia = uploadMediaChunkedFinalize0 ( mediaId ) ; while ( tries < maxTries ) { if ( lastProgressPercent == currentProgressPercent ) { tries ++ ; } lastProgressPercent = currentProgressPercent ; String state = uploadedMedia . getProcessingState ( ) ; if ( state . equals ( "failed" ) ) { throw new TwitterException ( "Failed to finalize the chuncked upload." ) ; } if ( state . equals ( "pending" ) || state . equals ( "in_progress" ) ) { currentProgressPercent = uploadedMedia . getProgressPercent ( ) ; int waitSec = Math . max ( uploadedMedia . getProcessingCheckAfterSecs ( ) , 1 ) ; logger . debug ( "Chunked finalize, wait for:" + waitSec + " sec" ) ; try { Thread . sleep ( waitSec * 1000 ) ; } catch ( InterruptedException e ) { throw new TwitterException ( "Failed to finalize the chuncked upload." , e ) ; } } if ( state . equals ( "succeeded" ) ) { return uploadedMedia ; } uploadedMedia = uploadMediaChunkedStatus ( mediaId ) ; } throw new TwitterException ( "Failed to finalize the chuncked upload, progress has stopped, tried " + tries + 1 + " times." ) ; } | command = FINALIZE&media_id = 601413451156586496 |
24,746 | private void checkFileValidity ( File image ) throws TwitterException { if ( ! image . exists ( ) ) { throw new TwitterException ( new FileNotFoundException ( image + " is not found." ) ) ; } if ( ! image . isFile ( ) ) { throw new TwitterException ( new IOException ( image + " is not a file." ) ) ; } } | Check the existence and the type of the specified file . |
24,747 | public synchronized void setOAuthConsumer ( String consumerKey , String consumerSecret ) { if ( null == consumerKey ) { throw new NullPointerException ( "consumer key is null" ) ; } if ( null == consumerSecret ) { throw new NullPointerException ( "consumer secret is null" ) ; } if ( auth instanceof NullAuthorization ) { if ( conf . isApplicationOnlyAuthEnabled ( ) ) { OAuth2Authorization oauth2 = new OAuth2Authorization ( conf ) ; oauth2 . setOAuthConsumer ( consumerKey , consumerSecret ) ; auth = oauth2 ; } else { OAuthAuthorization oauth = new OAuthAuthorization ( conf ) ; oauth . setOAuthConsumer ( consumerKey , consumerSecret ) ; auth = oauth ; } } else if ( auth instanceof BasicAuthorization ) { XAuthAuthorization xauth = new XAuthAuthorization ( ( BasicAuthorization ) auth ) ; xauth . setOAuthConsumer ( consumerKey , consumerSecret ) ; auth = xauth ; } else if ( auth instanceof OAuthAuthorization || auth instanceof OAuth2Authorization ) { throw new IllegalStateException ( "consumer key/secret pair already set." ) ; } } | methods declared in OAuthSupport interface |
24,748 | private static void autofit ( TextView view , TextPaint paint , float minTextSize , float maxTextSize , int maxLines , float precision ) { if ( maxLines <= 0 || maxLines == Integer . MAX_VALUE ) { return ; } int targetWidth = view . getWidth ( ) - view . getPaddingLeft ( ) - view . getPaddingRight ( ) ; if ( targetWidth <= 0 ) { return ; } CharSequence text = view . getText ( ) ; TransformationMethod method = view . getTransformationMethod ( ) ; if ( method != null ) { text = method . getTransformation ( text , view ) ; } Context context = view . getContext ( ) ; Resources r = Resources . getSystem ( ) ; DisplayMetrics displayMetrics ; float size = maxTextSize ; float high = size ; float low = 0 ; if ( context != null ) { r = context . getResources ( ) ; } displayMetrics = r . getDisplayMetrics ( ) ; paint . set ( view . getPaint ( ) ) ; paint . setTextSize ( size ) ; if ( ( maxLines == 1 && paint . measureText ( text , 0 , text . length ( ) ) > targetWidth ) || getLineCount ( text , paint , size , targetWidth , displayMetrics ) > maxLines ) { size = getAutofitTextSize ( text , paint , targetWidth , maxLines , low , high , precision , displayMetrics ) ; } if ( size < minTextSize ) { size = minTextSize ; } view . setTextSize ( TypedValue . COMPLEX_UNIT_PX , size ) ; } | Re - sizes the textSize of the TextView so that the text fits within the bounds of the View . |
24,749 | private static float getAutofitTextSize ( CharSequence text , TextPaint paint , float targetWidth , int maxLines , float low , float high , float precision , DisplayMetrics displayMetrics ) { float mid = ( low + high ) / 2.0f ; int lineCount = 1 ; StaticLayout layout = null ; paint . setTextSize ( TypedValue . applyDimension ( TypedValue . COMPLEX_UNIT_PX , mid , displayMetrics ) ) ; if ( maxLines != 1 ) { layout = new StaticLayout ( text , paint , ( int ) targetWidth , Layout . Alignment . ALIGN_NORMAL , 1.0f , 0.0f , true ) ; lineCount = layout . getLineCount ( ) ; } if ( SPEW ) Log . d ( TAG , "low=" + low + " high=" + high + " mid=" + mid + " target=" + targetWidth + " maxLines=" + maxLines + " lineCount=" + lineCount ) ; if ( lineCount > maxLines ) { if ( ( high - low ) < precision ) { return low ; } return getAutofitTextSize ( text , paint , targetWidth , maxLines , low , mid , precision , displayMetrics ) ; } else if ( lineCount < maxLines ) { return getAutofitTextSize ( text , paint , targetWidth , maxLines , mid , high , precision , displayMetrics ) ; } else { float maxLineWidth = 0 ; if ( maxLines == 1 ) { maxLineWidth = paint . measureText ( text , 0 , text . length ( ) ) ; } else { for ( int i = 0 ; i < lineCount ; i ++ ) { if ( layout . getLineWidth ( i ) > maxLineWidth ) { maxLineWidth = layout . getLineWidth ( i ) ; } } } if ( ( high - low ) < precision ) { return low ; } else if ( maxLineWidth > targetWidth ) { return getAutofitTextSize ( text , paint , targetWidth , maxLines , low , mid , precision , displayMetrics ) ; } else if ( maxLineWidth < targetWidth ) { return getAutofitTextSize ( text , paint , targetWidth , maxLines , mid , high , precision , displayMetrics ) ; } else { return mid ; } } } | Recursive binary search to find the best size for the text . |
24,750 | public AutofitHelper setMinTextSize ( int unit , float size ) { Context context = mTextView . getContext ( ) ; Resources r = Resources . getSystem ( ) ; if ( context != null ) { r = context . getResources ( ) ; } setRawMinTextSize ( TypedValue . applyDimension ( unit , size , r . getDisplayMetrics ( ) ) ) ; return this ; } | Set the minimum text size to a given unit and value . See TypedValue for the possible dimension units . |
24,751 | public AutofitHelper setMaxTextSize ( int unit , float size ) { Context context = mTextView . getContext ( ) ; Resources r = Resources . getSystem ( ) ; if ( context != null ) { r = context . getResources ( ) ; } setRawMaxTextSize ( TypedValue . applyDimension ( unit , size , r . getDisplayMetrics ( ) ) ) ; return this ; } | Set the maximum text size to a given unit and value . See TypedValue for the possible dimension units . |
24,752 | public AutofitHelper setEnabled ( boolean enabled ) { if ( mEnabled != enabled ) { mEnabled = enabled ; if ( enabled ) { mTextView . addTextChangedListener ( mTextWatcher ) ; mTextView . addOnLayoutChangeListener ( mOnLayoutChangeListener ) ; autofit ( ) ; } else { mTextView . removeTextChangedListener ( mTextWatcher ) ; mTextView . removeOnLayoutChangeListener ( mOnLayoutChangeListener ) ; mTextView . setTextSize ( TypedValue . COMPLEX_UNIT_PX , mTextSize ) ; } } return this ; } | Set the enabled state of automatically resizing text . |
24,753 | public static < T > List < Field > getDeclaredFields ( T type ) { return new ArrayList < > ( asList ( type . getClass ( ) . getDeclaredFields ( ) ) ) ; } | Get declared fields of a given type . |
24,754 | public static List < Field > getInheritedFields ( Class < ? > type ) { List < Field > inheritedFields = new ArrayList < > ( ) ; while ( type . getSuperclass ( ) != null ) { Class < ? > superclass = type . getSuperclass ( ) ; inheritedFields . addAll ( asList ( superclass . getDeclaredFields ( ) ) ) ; type = superclass ; } return inheritedFields ; } | Get inherited fields of a given type . |
24,755 | public Class < ? > getWrapperType ( Class < ? > primitiveType ) { for ( PrimitiveEnum p : PrimitiveEnum . values ( ) ) { if ( p . getType ( ) . equals ( primitiveType ) ) { return p . getClazz ( ) ; } } return primitiveType ; } | Get wrapper type of a primitive type . |
24,756 | public static boolean isPrimitiveFieldWithDefaultValue ( final Object object , final Field field ) throws IllegalAccessException { Class < ? > fieldType = field . getType ( ) ; if ( ! fieldType . isPrimitive ( ) ) { return false ; } Object fieldValue = getFieldValue ( object , field ) ; if ( fieldValue == null ) { return false ; } if ( fieldType . equals ( boolean . class ) && ( boolean ) fieldValue == false ) { return true ; } if ( fieldType . equals ( byte . class ) && ( byte ) fieldValue == ( byte ) 0 ) { return true ; } if ( fieldType . equals ( short . class ) && ( short ) fieldValue == ( short ) 0 ) { return true ; } if ( fieldType . equals ( int . class ) && ( int ) fieldValue == 0 ) { return true ; } if ( fieldType . equals ( long . class ) && ( long ) fieldValue == 0L ) { return true ; } if ( fieldType . equals ( float . class ) && ( float ) fieldValue == 0.0F ) { return true ; } if ( fieldType . equals ( double . class ) && ( double ) fieldValue == 0.0D ) { return true ; } if ( fieldType . equals ( char . class ) && ( char ) fieldValue == '\u0000' ) { return true ; } return false ; } | Check if a field has a primitive type and matching default value which is set by the compiler . |
24,757 | public static boolean isCollectionType ( final Type type ) { return isParameterizedType ( type ) && isCollectionType ( ( Class < ? > ) ( ( ParameterizedType ) type ) . getRawType ( ) ) ; } | Check if a type is a collection type . |
24,758 | public static boolean isPopulatable ( final Type type ) { return ! isWildcardType ( type ) && ! isTypeVariable ( type ) && ! isCollectionType ( type ) && ! isParameterizedType ( type ) ; } | Check if a type is populatable . |
24,759 | public static boolean isIntrospectable ( final Class < ? > type ) { return ! isEnumType ( type ) && ! isArrayType ( type ) && ! ( isCollectionType ( type ) && isJdkBuiltIn ( type ) ) && ! ( isMapType ( type ) && isJdkBuiltIn ( type ) ) ; } | Check if a type should be introspected for internal fields . |
24,760 | public static boolean isParameterizedType ( final Type type ) { return type != null && type instanceof ParameterizedType && ( ( ParameterizedType ) type ) . getActualTypeArguments ( ) . length > 0 ; } | Check if a type is a parameterized type |
24,761 | public static List < Class < ? > > filterSameParameterizedTypes ( final List < Class < ? > > types , final Type type ) { if ( type instanceof ParameterizedType ) { Type [ ] fieldArugmentTypes = ( ( ParameterizedType ) type ) . getActualTypeArguments ( ) ; List < Class < ? > > typesWithSameParameterizedTypes = new ArrayList < > ( ) ; for ( Class < ? > currentConcreteType : types ) { List < Type [ ] > actualTypeArguments = getActualTypeArgumentsOfGenericInterfaces ( currentConcreteType ) ; typesWithSameParameterizedTypes . addAll ( actualTypeArguments . stream ( ) . filter ( currentTypeArguments -> Arrays . equals ( fieldArugmentTypes , currentTypeArguments ) ) . map ( currentTypeArguments -> currentConcreteType ) . collect ( toList ( ) ) ) ; } return typesWithSameParameterizedTypes ; } return types ; } | Filters a list of types to keep only elements having the same parameterized types as the given type . |
24,762 | public static < T extends Annotation > T getAnnotation ( Field field , Class < T > annotationType ) { return field . getAnnotation ( annotationType ) == null ? getAnnotationFromReadMethod ( getReadMethod ( field ) . orElse ( null ) , annotationType ) : field . getAnnotation ( annotationType ) ; } | Looks for given annotationType on given field or read method for field . |
24,763 | public static boolean isAnnotationPresent ( Field field , Class < ? extends Annotation > annotationType ) { final Optional < Method > readMethod = getReadMethod ( field ) ; return field . isAnnotationPresent ( annotationType ) || readMethod . isPresent ( ) && readMethod . get ( ) . isAnnotationPresent ( annotationType ) ; } | Checks if field or corresponding read method is annotated with given annotationType . |
24,764 | public static Collection < ? > createEmptyCollectionForType ( Class < ? > fieldType , int initialSize ) { rejectUnsupportedTypes ( fieldType ) ; Collection < ? > collection ; try { collection = ( Collection < ? > ) fieldType . newInstance ( ) ; } catch ( InstantiationException | IllegalAccessException e ) { if ( fieldType . equals ( ArrayBlockingQueue . class ) ) { collection = new ArrayBlockingQueue < > ( initialSize ) ; } else { collection = ( Collection < ? > ) new ObjenesisStd ( ) . newInstance ( fieldType ) ; } } return collection ; } | Create an empty collection for the given type . |
24,765 | public static Optional < Method > getReadMethod ( Field field ) { String fieldName = field . getName ( ) ; Class < ? > fieldClass = field . getDeclaringClass ( ) ; String capitalizedFieldName = fieldName . substring ( 0 , 1 ) . toUpperCase ( ENGLISH ) + fieldName . substring ( 1 ) ; Optional < Method > getter = getPublicMethod ( "get" + capitalizedFieldName , fieldClass ) ; if ( getter . isPresent ( ) ) { return getter ; } return getPublicMethod ( "is" + capitalizedFieldName , fieldClass ) ; } | Get the read method for given field . |
24,766 | public Randomizer < ? > getRandomizer ( Field field ) { if ( field . isAnnotationPresent ( org . jeasy . random . annotation . Randomizer . class ) ) { org . jeasy . random . annotation . Randomizer randomizer = field . getAnnotation ( org . jeasy . random . annotation . Randomizer . class ) ; Class < ? > type = randomizer . value ( ) ; RandomizerArgument [ ] arguments = randomizer . args ( ) ; return ReflectionUtils . newInstance ( type , arguments ) ; } return null ; } | Retrieves a randomizer for the given field . |
24,767 | protected double nextDouble ( final double min , final double max ) { double value = min + ( random . nextDouble ( ) * ( max - min ) ) ; if ( value < min ) { return min ; } else if ( value > max ) { return max ; } else { return value ; } } | Return a random double in the given range . |
24,768 | public static Predicate < Class < ? > > named ( final String name ) { return clazz -> clazz . getName ( ) . equals ( name ) ; } | Create a predicate to check that a type has a given name . |
24,769 | public static Predicate < Class < ? > > inPackage ( final String packageNamePrefix ) { return clazz -> clazz . getPackage ( ) . getName ( ) . startsWith ( packageNamePrefix ) ; } | Create a predicate to check that a type is defined in a given package . |
24,770 | public static Predicate < Class < ? > > isAnnotatedWith ( Class < ? extends Annotation > ... annotations ) { return clazz -> { for ( Class < ? extends Annotation > annotation : annotations ) { if ( clazz . isAnnotationPresent ( annotation ) ) { return true ; } } return false ; } ; } | Create a predicate to check that a type is annotated with one of the given annotations . |
24,771 | public static Predicate < Class < ? > > hasModifiers ( final Integer modifiers ) { return clazz -> ( modifiers & clazz . getModifiers ( ) ) == modifiers ; } | Create a predicate to check that a type has a given set of modifiers . |
24,772 | public < T > EasyRandomParameters randomize ( Class < T > type , Randomizer < T > randomizer ) { Objects . requireNonNull ( type , "Type must not be null" ) ; Objects . requireNonNull ( randomizer , "Randomizer must not be null" ) ; customRandomizerRegistry . registerRandomizer ( type , randomizer ) ; return this ; } | Register a custom randomizer for a given type . |
24,773 | public EasyRandomParameters excludeField ( Predicate < Field > predicate ) { Objects . requireNonNull ( predicate , "Predicate must not be null" ) ; fieldExclusionPredicates . add ( predicate ) ; exclusionRandomizerRegistry . addFieldPredicate ( predicate ) ; return this ; } | Exclude a field from being randomized . |
24,774 | public EasyRandomParameters excludeType ( Predicate < Class < ? > > predicate ) { Objects . requireNonNull ( predicate , "Predicate must not be null" ) ; typeExclusionPredicates . add ( predicate ) ; exclusionRandomizerRegistry . addTypePredicate ( predicate ) ; return this ; } | Exclude a type from being randomized . |
24,775 | public EasyRandomParameters collectionSizeRange ( final int minCollectionSize , final int maxCollectionSize ) { if ( minCollectionSize < 0 ) { throw new IllegalArgumentException ( "minCollectionSize must be >= 0" ) ; } if ( minCollectionSize > maxCollectionSize ) { throw new IllegalArgumentException ( format ( "minCollectionSize (%s) must be <= than maxCollectionSize (%s)" , minCollectionSize , maxCollectionSize ) ) ; } setCollectionSizeRange ( new Range < > ( minCollectionSize , maxCollectionSize ) ) ; return this ; } | Set the collection size range . |
24,776 | public EasyRandomParameters stringLengthRange ( final int minStringLength , final int maxStringLength ) { if ( minStringLength < 0 ) { throw new IllegalArgumentException ( "minStringLength must be >= 0" ) ; } if ( minStringLength > maxStringLength ) { throw new IllegalArgumentException ( format ( "minStringLength (%s) must be <= than maxStringLength (%s)" , minStringLength , maxStringLength ) ) ; } setStringLengthRange ( new Range < > ( minStringLength , maxStringLength ) ) ; return this ; } | Set the string length range . |
24,777 | public EasyRandomParameters dateRange ( final LocalDate min , final LocalDate max ) { if ( min . isAfter ( max ) ) { throw new IllegalArgumentException ( "Min date should be before max date" ) ; } setDateRange ( new Range < > ( min , max ) ) ; return this ; } | Set the date range . |
24,778 | public EasyRandomParameters timeRange ( final LocalTime min , final LocalTime max ) { if ( min . isAfter ( max ) ) { throw new IllegalArgumentException ( "Min time should be before max time" ) ; } setTimeRange ( new Range < > ( min , max ) ) ; return this ; } | Set the time range . |
24,779 | public boolean shouldBeExcluded ( final Field field , final RandomizerContext context ) { if ( isStatic ( field ) ) { return true ; } Set < Predicate < Field > > fieldExclusionPredicates = context . getParameters ( ) . getFieldExclusionPredicates ( ) ; for ( Predicate < Field > fieldExclusionPredicate : fieldExclusionPredicates ) { if ( fieldExclusionPredicate . test ( field ) ) { return true ; } } return false ; } | Given the current randomization context should the field be excluded from being populated ? |
24,780 | public boolean shouldBeExcluded ( final Class < ? > type , final RandomizerContext context ) { Set < Predicate < Class < ? > > > typeExclusionPredicates = context . getParameters ( ) . getTypeExclusionPredicates ( ) ; for ( Predicate < Class < ? > > typeExclusionPredicate : typeExclusionPredicates ) { if ( typeExclusionPredicate . test ( type ) ) { return true ; } } return false ; } | Given the current randomization context should the type be excluded from being populated ? |
24,781 | public static List < Character > collectPrintableCharactersOf ( Charset charset ) { List < Character > chars = new ArrayList < > ( ) ; for ( int i = Character . MIN_VALUE ; i < Character . MAX_VALUE ; i ++ ) { char character = ( char ) i ; if ( isPrintable ( character ) ) { String characterAsString = Character . toString ( character ) ; byte [ ] encoded = characterAsString . getBytes ( charset ) ; String decoded = new String ( encoded , charset ) ; if ( characterAsString . equals ( decoded ) ) { chars . add ( character ) ; } } } return chars ; } | Returns a list of all printable charaters of the given charset . |
24,782 | public static List < Character > filterLetters ( List < Character > characters ) { return characters . stream ( ) . filter ( Character :: isLetter ) . collect ( toList ( ) ) ; } | Keep only letters from a list of characters . |
24,783 | public static Predicate < Field > named ( final String name ) { return field -> Pattern . compile ( name ) . matcher ( field . getName ( ) ) . matches ( ) ; } | Create a predicate to check that a field has a certain name pattern . |
24,784 | public static Predicate < Field > ofType ( Class < ? > type ) { return field -> field . getType ( ) . equals ( type ) ; } | Create a predicate to check that a field has a certain type . |
24,785 | public static Predicate < Field > inClass ( Class < ? > clazz ) { return field -> field . getDeclaringClass ( ) . equals ( clazz ) ; } | Create a predicate to check that a field is defined in a given class . |
24,786 | public static Predicate < Field > isAnnotatedWith ( Class < ? extends Annotation > ... annotations ) { return field -> { for ( Class < ? extends Annotation > annotation : annotations ) { if ( field . isAnnotationPresent ( annotation ) ) { return true ; } } return false ; } ; } | Create a predicate to check that a field is annotated with one of the given annotations . |
24,787 | public static Predicate < Field > hasModifiers ( final Integer modifiers ) { return field -> ( modifiers & field . getModifiers ( ) ) == modifiers ; } | Create a predicate to check that a field has a given set of modifiers . |
24,788 | public static < T > T randomElementOf ( final List < T > list ) { if ( list . isEmpty ( ) ) { return null ; } return list . get ( nextInt ( 0 , list . size ( ) ) ) ; } | Get a random element from the list . |
24,789 | public < T > T nextObject ( final Class < T > type ) { return doPopulateBean ( type , new RandomizationContext ( type , parameters ) ) ; } | Generate a random instance of the given type . |
24,790 | public < T > Stream < T > objects ( final Class < T > type , final int streamSize ) { if ( streamSize < 0 ) { throw new IllegalArgumentException ( "The stream size must be positive" ) ; } return Stream . generate ( ( ) -> nextObject ( type ) ) . limit ( streamSize ) ; } | Generate a stream of random instances of the given type . |
24,791 | private List < E > getFilteredList ( Class < E > enumeration , E ... excludedValues ) { List < E > filteredValues = new ArrayList < > ( ) ; Collections . addAll ( filteredValues , enumeration . getEnumConstants ( ) ) ; if ( excludedValues != null ) { for ( E element : excludedValues ) { filteredValues . remove ( element ) ; } } return filteredValues ; } | Get a subset of enumeration . |
24,792 | @ PublicAPI ( usage = ACCESS ) public void accept ( Predicate < ? super JavaClass > predicate , ClassVisitor visitor ) { for ( JavaClass javaClass : getClassesWith ( predicate ) ) { visitor . visit ( javaClass ) ; } for ( JavaPackage subPackage : getSubPackages ( ) ) { subPackage . accept ( predicate , visitor ) ; } } | Traverses the package tree visiting each matching class . |
24,793 | @ PublicAPI ( usage = ACCESS ) public void accept ( Predicate < ? super JavaPackage > predicate , PackageVisitor visitor ) { if ( predicate . apply ( this ) ) { visitor . visit ( this ) ; } for ( JavaPackage subPackage : getSubPackages ( ) ) { subPackage . accept ( predicate , visitor ) ; } } | Traverses the package tree visiting each matching package . |
24,794 | public void printToStandardStream ( ) throws FileNotFoundException { System . out . println ( "I'm gonna print to the command line" ) ; System . err . println ( "I'm gonna print to the command line" ) ; new SomeCustomException ( ) . printStackTrace ( ) ; new SomeCustomException ( ) . printStackTrace ( new PrintStream ( "/some/file" ) ) ; new SomeCustomException ( ) . printStackTrace ( new PrintWriter ( "/some/file" ) ) ; } | Violates rules not to use java . util . logging & that loggers should be private static final |
24,795 | public void back ( ) throws JSONException { if ( this . usePrevious || this . index <= 0 ) { throw new JSONException ( "Stepping back two steps is not supported" ) ; } this . decrementIndexes ( ) ; this . usePrevious = true ; this . eof = false ; } | Back up one character . This provides a sort of lookahead capability so that you can test for a digit or letter before attempting to parse the next number or identifier . |
24,796 | private void incrementIndexes ( int c ) { if ( c > 0 ) { this . index ++ ; if ( c == '\r' ) { this . line ++ ; this . characterPreviousLine = this . character ; this . character = 0 ; } else if ( c == '\n' ) { if ( this . previous != '\r' ) { this . line ++ ; this . characterPreviousLine = this . character ; } this . character = 0 ; } else { this . character ++ ; } } } | Increments the internal indexes according to the previous character read and the character passed as the current character . |
24,797 | public JSONException syntaxError ( String message , Throwable causedBy ) { return new JSONException ( message + this . toString ( ) , causedBy ) ; } | Make a JSONException to signal a syntax error . |
24,798 | private Object readByIndexToken ( Object current , String indexToken ) throws JSONPointerException { try { int index = Integer . parseInt ( indexToken ) ; JSONArray currentArr = ( JSONArray ) current ; if ( index >= currentArr . length ( ) ) { throw new JSONPointerException ( format ( "index %s is out of bounds - the array has %d elements" , indexToken , Integer . valueOf ( currentArr . length ( ) ) ) ) ; } try { return currentArr . get ( index ) ; } catch ( JSONException e ) { throw new JSONPointerException ( "Error reading value at index position " + index , e ) ; } } catch ( NumberFormatException e ) { throw new JSONPointerException ( format ( "%s is not an array index" , indexToken ) , e ) ; } } | Matches a JSONArray element by ordinal position |
24,799 | public String toURIFragment ( ) { try { StringBuilder rval = new StringBuilder ( "#" ) ; for ( String token : this . refTokens ) { rval . append ( '/' ) . append ( URLEncoder . encode ( token , ENCODING ) ) ; } return rval . toString ( ) ; } catch ( UnsupportedEncodingException e ) { throw new RuntimeException ( e ) ; } } | Returns a string representing the JSONPointer path value using URI fragment identifier representation |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.