idx int64 0 41.2k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
26,900 | public static Polygon polygon ( final LineString exteriorBoundary , final LineString ... interiorBoundaries ) { ensurePolygonIsClosed ( exteriorBoundary ) ; for ( final LineString boundary : interiorBoundaries ) { ensurePolygonIsClosed ( boundary ) ; } return new Polygon ( exteriorBoundary , interiorBoundaries ) ; } | Lets you create a Polygon representing a GeoJSON Polygon type . This method is especially useful for defining polygons with inner rings . |
26,901 | public List < T > toList ( ) { final List < T > results = new ArrayList < T > ( ) ; try { while ( wrapped . hasNext ( ) ) { results . add ( next ( ) ) ; } } finally { wrapped . close ( ) ; } return results ; } | Converts this cursor to a List . Care should be taken on large datasets as OutOfMemoryErrors are a risk . |
26,902 | public DatastoreImpl copy ( final String database ) { return new DatastoreImpl ( morphia , mapper , mongoClient , database ) ; } | Creates a copy of this Datastore and all its configuration but with a new database |
26,903 | public < T , V > Query < T > find ( final String collection , final Class < T > clazz , final String property , final V value , final int offset , final int size , final boolean validate ) { final Query < T > query = find ( collection , clazz ) ; if ( ! validate ) { query . disableValidation ( ) ; } query . offset ( offset ) ; query . limit ( size ) ; return query . filter ( property , value ) . enableValidation ( ) ; } | Find all instances by type in a different collection than what is mapped on the class given skipping some documents and returning a fixed number of the remaining . |
26,904 | public < T > Iterable < Key < T > > insert ( final Iterable < T > entities ) { return insert ( entities , new InsertOptions ( ) . writeConcern ( defConcern ) ) ; } | Inserts entities in to the database |
26,905 | public < T > Key < T > insert ( final String collection , final T entity , final WriteConcern wc ) { return insert ( getCollection ( collection ) , ProxyHelper . unwrap ( entity ) , new InsertOptions ( ) . writeConcern ( wc ) ) ; } | Inserts an entity in to the database |
26,906 | private WriteConcern getWriteConcern ( final Object clazzOrEntity ) { WriteConcern wc = defConcern ; if ( clazzOrEntity != null ) { final Entity entityAnn = getMapper ( ) . getMappedClass ( clazzOrEntity ) . getEntityAnnotation ( ) ; if ( entityAnn != null && ! entityAnn . concern ( ) . isEmpty ( ) ) { wc = WriteConcern . valueOf ( entityAnn . concern ( ) ) ; } } return wc ; } | Gets the write concern for entity or returns the default write concern for this datastore |
26,907 | public static LazyProxyFactory createDefaultProxyFactory ( ) { if ( testDependencyFullFilled ( ) ) { final String factoryClassName = "dev.morphia.mapping.lazy.CGLibLazyProxyFactory" ; try { return ( LazyProxyFactory ) Class . forName ( factoryClassName ) . newInstance ( ) ; } catch ( Exception e ) { LOG . error ( "While instantiating " + factoryClassName , e ) ; } } return null ; } | Creates a LazyProxyFactory |
26,908 | public static void registerLogger ( final Class < ? extends LoggerFactory > factoryClass ) { if ( loggerFactory == null ) { FACTORIES . add ( 0 , factoryClass . getName ( ) ) ; } else { throw new IllegalStateException ( "LoggerImplFactory must be registered before logging is initialized." ) ; } } | Register a LoggerFactory ; last one registered is used . |
26,909 | public TypeConverter addConverter ( final Class < ? extends TypeConverter > clazz ) { return addConverter ( mapper . getOptions ( ) . getObjectFactory ( ) . createInstance ( clazz ) ) ; } | Adds a TypeConverter to this bundle . |
26,910 | public TypeConverter addConverter ( final TypeConverter tc ) { if ( tc . getSupportedTypes ( ) != null ) { for ( final Class c : tc . getSupportedTypes ( ) ) { addTypedConverter ( c , tc ) ; } } else { untypedTypeEncoders . add ( tc ) ; } registeredConverterClasses . add ( tc . getClass ( ) ) ; tc . setMapper ( mapper ) ; return tc ; } | Add a type converter . If it is a duplicate for an existing type it will override that type . |
26,911 | public void removeConverter ( final TypeConverter tc ) { if ( tc . getSupportedTypes ( ) == null ) { untypedTypeEncoders . remove ( tc ) ; registeredConverterClasses . remove ( tc . getClass ( ) ) ; } else { for ( final Entry < Class , List < TypeConverter > > entry : tcMap . entrySet ( ) ) { List < TypeConverter > list = entry . getValue ( ) ; if ( list . contains ( tc ) ) { list . remove ( tc ) ; } if ( list . isEmpty ( ) ) { tcMap . remove ( entry . getKey ( ) ) ; } } registeredConverterClasses . remove ( tc . getClass ( ) ) ; } } | Removes the type converter . |
26,912 | public void toDBObject ( final Object containingObject , final MappedField mf , final DBObject dbObj , final MapperOptions opts ) { final Object fieldValue = mf . getFieldValue ( containingObject ) ; final TypeConverter enc = getEncoder ( fieldValue , mf ) ; final Object encoded = enc . encode ( fieldValue , mf ) ; if ( encoded != null || opts . isStoreNulls ( ) ) { dbObj . put ( mf . getNameToStore ( ) , encoded ) ; } } | Converts an entity to a DBObject |
26,913 | public Object getFieldValue ( final Object instance ) { try { return field . get ( instance ) ; } catch ( IllegalAccessException e ) { throw new RuntimeException ( e ) ; } } | Gets the value of the field mapped on the instance given . |
26,914 | public String getFirstFieldName ( final DBObject dbObj ) { String fieldName = getNameToStore ( ) ; boolean foundField = false ; for ( final String n : getLoadNames ( ) ) { if ( dbObj . containsField ( n ) ) { if ( ! foundField ) { foundField = true ; fieldName = n ; } else { throw new MappingException ( format ( "Found more than one field from @AlsoLoad %s" , getLoadNames ( ) ) ) ; } } } return fieldName ; } | Gets the field name to use when converting from a DBObject |
26,915 | public void setFieldValue ( final Object instance , final Object value ) { try { field . set ( instance , value ) ; } catch ( IllegalAccessException e ) { throw new RuntimeException ( e ) ; } } | Sets the value for the java field |
26,916 | private static void verify ( final String name , final int type ) { if ( ( type < HARD ) || ( type > WEAK ) ) { throw new IllegalArgumentException ( name + " must be HARD, SOFT, WEAK." ) ; } } | used by constructor |
26,917 | public void clear ( ) { Arrays . fill ( table , null ) ; size = 0 ; while ( queue . poll ( ) != null ) { } } | Clears this map . |
26,918 | public Set keySet ( ) { if ( keySet != null ) { return keySet ; } keySet = new AbstractSet ( ) { public Iterator iterator ( ) { return new KeyIterator ( ) ; } public int size ( ) { return size ; } public boolean contains ( final Object o ) { return containsKey ( o ) ; } public boolean remove ( final Object o ) { final Object r = ReferenceMap . this . remove ( o ) ; return r != null ; } public void clear ( ) { ReferenceMap . this . clear ( ) ; } } ; return keySet ; } | Returns a set view of this map s keys . |
26,919 | public Set entrySet ( ) { if ( entrySet != null ) { return entrySet ; } entrySet = new AbstractSet ( ) { public int size ( ) { return ReferenceMap . this . size ( ) ; } public void clear ( ) { ReferenceMap . this . clear ( ) ; } public boolean contains ( final Object o ) { if ( o == null ) { return false ; } if ( ! ( o instanceof Map . Entry ) ) { return false ; } final Map . Entry e = ( Map . Entry ) o ; final Entry e2 = getEntry ( e . getKey ( ) ) ; return ( e2 != null ) && e . equals ( e2 ) ; } public boolean remove ( final Object o ) { final boolean r = contains ( o ) ; if ( r ) { final Map . Entry e = ( Map . Entry ) o ; ReferenceMap . this . remove ( e . getKey ( ) ) ; } return r ; } public Iterator iterator ( ) { return new EntryIterator ( ) ; } public Object [ ] toArray ( ) { return toArray ( new Object [ 0 ] ) ; } @ SuppressWarnings ( "unchecked" ) public Object [ ] toArray ( final Object [ ] arr ) { final List list = new ArrayList ( ) ; final Iterator iterator = iterator ( ) ; while ( iterator . hasNext ( ) ) { final Entry e = ( Entry ) iterator . next ( ) ; list . add ( new DefaultMapEntry ( e . getKey ( ) , e . getValue ( ) ) ) ; } return list . toArray ( arr ) ; } } ; return entrySet ; } | Returns a set view of this map s entries . |
26,920 | private void readObject ( final ObjectInputStream inp ) throws IOException , ClassNotFoundException { inp . defaultReadObject ( ) ; table = new Entry [ inp . readInt ( ) ] ; threshold = ( int ) ( table . length * loadFactor ) ; queue = new ReferenceQueue ( ) ; Object key = inp . readObject ( ) ; while ( key != null ) { final Object value = inp . readObject ( ) ; put ( key , value ) ; key = inp . readObject ( ) ; } } | Reads the contents of this object from the given input stream . |
26,921 | private void resize ( ) { final Entry [ ] old = table ; table = new Entry [ old . length * 2 ] ; for ( int i = 0 ; i < old . length ; i ++ ) { Entry next = old [ i ] ; while ( next != null ) { final Entry entry = next ; next = next . next ; final int index = indexFor ( entry . hash ) ; entry . next = table [ index ] ; table [ index ] = entry ; } old [ i ] = null ; } threshold = ( int ) ( table . length * loadFactor ) ; } | Resizes this hash table by doubling its capacity . This is an expensive operation as entries must be copied from the old smaller table to the new bigger table . |
26,922 | public DeleteOptions copy ( ) { DeleteOptions deleteOptions = new DeleteOptions ( ) . writeConcern ( getWriteConcern ( ) ) ; if ( getCollation ( ) != null ) { deleteOptions . collation ( Collation . builder ( getCollation ( ) ) . build ( ) ) ; } return deleteOptions ; } | Copies this instance to a new one . |
26,923 | public static BasicDBObject parseFieldsString ( final String str , final Class clazz , final Mapper mapper , final boolean validate ) { BasicDBObject ret = new BasicDBObject ( ) ; final String [ ] parts = str . split ( "," ) ; for ( String s : parts ) { s = s . trim ( ) ; int dir = 1 ; if ( s . startsWith ( "-" ) ) { dir = - 1 ; s = s . substring ( 1 ) . trim ( ) ; } if ( validate ) { s = new PathTarget ( mapper , clazz , s ) . translatedPath ( ) ; } ret . put ( s , dir ) ; } return ret ; } | Parses the string and validates each part |
26,924 | public static Projection projection ( final String field , final Projection projection , final Projection ... subsequent ) { return new Projection ( field , projection , subsequent ) ; } | Creates a projection on a field with subsequent projects applied . |
26,925 | public Iterator < T > iterator ( ) { return outputType == OutputType . INLINE ? getInlineResults ( ) : createQuery ( ) . fetch ( ) . iterator ( ) ; } | Creates an Iterator over the results of the operation . |
26,926 | public void setInlineRequiredOptions ( final Datastore datastore , final Class < T > clazz , final Mapper mapper , final EntityCache cache ) { this . mapper = mapper ; this . datastore = datastore ; this . clazz = clazz ; this . cache = cache ; } | Sets the required options when the operation type was INLINE |
26,927 | public static MorphiaReference < ? > decode ( final Datastore datastore , final Mapper mapper , final MappedField mappedField , final Class paramType , final DBObject dbObject ) { final MappedClass mappedClass = mapper . getMappedClass ( paramType ) ; Object id = dbObject . get ( mappedField . getMappedFieldName ( ) ) ; return new SingleReference ( datastore , mappedClass , id ) ; } | Decodes a document in to an entity |
26,928 | private static String readLine ( InputStream is ) throws IOException { StringBuilder builder = new StringBuilder ( ) ; while ( true ) { int ch = is . read ( ) ; if ( ch == '\r' ) { ch = is . read ( ) ; if ( ch == '\n' ) { break ; } else { throw new IOException ( "unexpected char after \\r: " + ch ) ; } } else if ( ch == - 1 ) { if ( builder . length ( ) > 0 ) { throw new IOException ( "unexpected end of stream" ) ; } break ; } builder . append ( ( char ) ch ) ; } return builder . toString ( ) ; } | Read a \ r \ n terminated line from an InputStream . |
26,929 | private static String mapXmlAclsToCannedPolicy ( AccessControlPolicy policy ) throws S3Exception { if ( ! policy . owner . id . equals ( FAKE_OWNER_ID ) ) { throw new S3Exception ( S3ErrorCode . NOT_IMPLEMENTED ) ; } boolean ownerFullControl = false ; boolean allUsersRead = false ; if ( policy . aclList != null ) { for ( AccessControlPolicy . AccessControlList . Grant grant : policy . aclList . grants ) { if ( grant . grantee . type . equals ( "CanonicalUser" ) && grant . grantee . id . equals ( FAKE_OWNER_ID ) && grant . permission . equals ( "FULL_CONTROL" ) ) { ownerFullControl = true ; } else if ( grant . grantee . type . equals ( "Group" ) && grant . grantee . uri . equals ( "http://acs.amazonaws.com/" + "groups/global/AllUsers" ) && grant . permission . equals ( "READ" ) ) { allUsersRead = true ; } else { throw new S3Exception ( S3ErrorCode . NOT_IMPLEMENTED ) ; } } } if ( ownerFullControl ) { if ( allUsersRead ) { return "public-read" ; } return "private" ; } else { throw new S3Exception ( S3ErrorCode . NOT_IMPLEMENTED ) ; } } | Map XML ACLs to a canned policy if an exact tranformation exists . |
26,930 | private static long parseIso8601 ( String date ) { SimpleDateFormat formatter = new SimpleDateFormat ( "yyyyMMdd'T'HHmmss'Z'" ) ; formatter . setTimeZone ( TimeZone . getTimeZone ( "UTC" ) ) ; logger . debug ( "8601date {}" , date ) ; try { return formatter . parse ( date ) . getTime ( ) / 1000 ; } catch ( ParseException pe ) { throw new IllegalArgumentException ( pe ) ; } } | Parse ISO 8601 timestamp into seconds since 1970 . |
26,931 | private static String formatDate ( Date date ) { SimpleDateFormat formatter = new SimpleDateFormat ( "yyyy-MM-dd'T'HH:mm:ss'Z'" ) ; formatter . setTimeZone ( TimeZone . getTimeZone ( "GMT" ) ) ; return formatter . format ( date ) ; } | it has unwanted millisecond precision |
26,932 | private static String encodeBlob ( String encodingType , String blobName ) { if ( encodingType != null && encodingType . equals ( "url" ) ) { return urlEscaper . escape ( blobName ) ; } else { return blobName ; } } | which XML 1 . 0 cannot represent . |
26,933 | public static String readAsciiString ( ByteBuffer buffer , int strLen ) { byte [ ] bytes = new byte [ strLen ] ; buffer . get ( bytes ) ; return new String ( bytes ) ; } | Read ascii string by len |
26,934 | public static String readString ( ByteBuffer buffer , int strLen ) { StringBuilder sb = new StringBuilder ( strLen ) ; for ( int i = 0 ; i < strLen ; i ++ ) { sb . append ( buffer . getChar ( ) ) ; } return sb . toString ( ) ; } | read utf16 strings use strLen not ending 0 char . |
26,935 | public static String readZeroTerminatedString ( ByteBuffer buffer , int strLen ) { StringBuilder sb = new StringBuilder ( strLen ) ; for ( int i = 0 ; i < strLen ; i ++ ) { char c = buffer . getChar ( ) ; if ( c == '\0' ) { skip ( buffer , ( strLen - i - 1 ) * 2 ) ; break ; } sb . append ( c ) ; } return sb . toString ( ) ; } | read utf16 strings ending with 0 char . |
26,936 | public static ByteBuffer sliceAndSkip ( ByteBuffer buffer , int size ) { ByteBuffer buf = buffer . slice ( ) . order ( ByteOrder . LITTLE_ENDIAN ) ; ByteBuffer slice = ( ByteBuffer ) ( ( Buffer ) buf ) . limit ( buf . position ( ) + size ) ; skip ( buffer , size ) ; return slice ; } | Return one new ByteBuffer from current position with size the byte order of new buffer will be set to little endian ; And advance the original buffer with size . |
26,937 | public List < Resource > getResourcesById ( long resourceId ) { short packageId = ( short ) ( resourceId >> 24 & 0xff ) ; short typeId = ( short ) ( ( resourceId >> 16 ) & 0xff ) ; int entryIndex = ( int ) ( resourceId & 0xffff ) ; ResourcePackage resourcePackage = this . getPackage ( packageId ) ; if ( resourcePackage == null ) { return Collections . emptyList ( ) ; } TypeSpec typeSpec = resourcePackage . getTypeSpec ( typeId ) ; List < Type > types = resourcePackage . getTypes ( typeId ) ; if ( typeSpec == null || types == null ) { return Collections . emptyList ( ) ; } if ( ! typeSpec . exists ( entryIndex ) ) { return Collections . emptyList ( ) ; } List < Resource > result = new ArrayList < > ( ) ; for ( Type type : types ) { ResourceEntry resourceEntry = type . getResourceEntry ( entryIndex ) ; if ( resourceEntry == null ) { continue ; } ResourceValue currentResourceValue = resourceEntry . getValue ( ) ; if ( currentResourceValue == null ) { continue ; } if ( currentResourceValue instanceof ResourceValue . ReferenceResourceValue ) { if ( resourceId == ( ( ResourceValue . ReferenceResourceValue ) currentResourceValue ) . getReferenceResourceId ( ) ) { continue ; } } result . add ( new Resource ( typeSpec , type , resourceEntry ) ) ; } return result ; } | Get resources match the given resource id . |
26,938 | public void parse ( ) { ResourceTableHeader resourceTableHeader = ( ResourceTableHeader ) readChunkHeader ( ) ; stringPool = ParseUtils . readStringPool ( buffer , ( StringPoolHeader ) readChunkHeader ( ) ) ; resourceTable = new ResourceTable ( ) ; resourceTable . setStringPool ( stringPool ) ; PackageHeader packageHeader = ( PackageHeader ) readChunkHeader ( ) ; for ( int i = 0 ; i < resourceTableHeader . getPackageCount ( ) ; i ++ ) { Pair < ResourcePackage , PackageHeader > pair = readPackage ( packageHeader ) ; resourceTable . addPackage ( pair . getLeft ( ) ) ; packageHeader = pair . getRight ( ) ; } } | parse resource table file . |
26,939 | public static Map < Integer , String > loadSystemAttrIds ( ) { try ( BufferedReader reader = toReader ( "/r_values.ini" ) ) { Map < Integer , String > map = new HashMap < > ( ) ; String line ; while ( ( line = reader . readLine ( ) ) != null ) { String [ ] items = line . trim ( ) . split ( "=" ) ; if ( items . length != 2 ) { continue ; } String name = items [ 0 ] . trim ( ) ; Integer id = Integer . valueOf ( items [ 1 ] . trim ( ) ) ; map . put ( id , name ) ; } return map ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } } | load system attr ids for parse binary xml . |
26,940 | public static String readString ( ByteBuffer buffer , boolean utf8 ) { if ( utf8 ) { int strLen = readLen ( buffer ) ; int bytesLen = readLen ( buffer ) ; byte [ ] bytes = Buffers . readBytes ( buffer , bytesLen ) ; String str = new String ( bytes , charsetUTF8 ) ; int trailling = Buffers . readUByte ( buffer ) ; return str ; } else { int strLen = readLen16 ( buffer ) ; String str = Buffers . readString ( buffer , strLen ) ; int trailling = Buffers . readUShort ( buffer ) ; return str ; } } | read string from input buffer . if get EOF before read enough data throw IOException . |
26,941 | public static String readStringUTF16 ( ByteBuffer buffer , int strLen ) { String str = Buffers . readString ( buffer , strLen ) ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { char c = str . charAt ( i ) ; if ( c == 0 ) { return str . substring ( 0 , i ) ; } } return str ; } | read utf - 16 encoding str use zero char to end str . |
26,942 | private static int readLen ( ByteBuffer buffer ) { int len = 0 ; int i = Buffers . readUByte ( buffer ) ; if ( ( i & 0x80 ) != 0 ) { len |= ( i & 0x7f ) << 8 ; len += Buffers . readUByte ( buffer ) ; } else { len = i ; } return len ; } | read encoding len . see StringPool . cpp ENCODE_LENGTH |
26,943 | private static int readLen16 ( ByteBuffer buffer ) { int len = 0 ; int i = Buffers . readUShort ( buffer ) ; if ( ( i & 0x8000 ) != 0 ) { len |= ( i & 0x7fff ) << 16 ; len += Buffers . readUShort ( buffer ) ; } else { len = i ; } return len ; } | read encoding len . see Stringpool . cpp ENCODE_LENGTH |
26,944 | public static StringPool readStringPool ( ByteBuffer buffer , StringPoolHeader stringPoolHeader ) { long beginPos = buffer . position ( ) ; int [ ] offsets = new int [ stringPoolHeader . getStringCount ( ) ] ; if ( stringPoolHeader . getStringCount ( ) > 0 ) { for ( int idx = 0 ; idx < stringPoolHeader . getStringCount ( ) ; idx ++ ) { offsets [ idx ] = Unsigned . toUInt ( Buffers . readUInt ( buffer ) ) ; } } boolean sorted = ( stringPoolHeader . getFlags ( ) & StringPoolHeader . SORTED_FLAG ) != 0 ; boolean utf8 = ( stringPoolHeader . getFlags ( ) & StringPoolHeader . UTF8_FLAG ) != 0 ; long stringPos = beginPos + stringPoolHeader . getStringsStart ( ) - stringPoolHeader . getHeaderSize ( ) ; Buffers . position ( buffer , stringPos ) ; StringPoolEntry [ ] entries = new StringPoolEntry [ offsets . length ] ; for ( int i = 0 ; i < offsets . length ; i ++ ) { entries [ i ] = new StringPoolEntry ( i , stringPos + Unsigned . toLong ( offsets [ i ] ) ) ; } String lastStr = null ; long lastOffset = - 1 ; StringPool stringPool = new StringPool ( stringPoolHeader . getStringCount ( ) ) ; for ( StringPoolEntry entry : entries ) { if ( entry . getOffset ( ) == lastOffset ) { stringPool . set ( entry . getIdx ( ) , lastStr ) ; continue ; } Buffers . position ( buffer , entry . getOffset ( ) ) ; lastOffset = entry . getOffset ( ) ; String str = ParseUtils . readString ( buffer , utf8 ) ; lastStr = str ; stringPool . set ( entry . getIdx ( ) , str ) ; } if ( stringPoolHeader . getStyleCount ( ) > 0 ) { } Buffers . position ( buffer , beginPos + stringPoolHeader . getBodySize ( ) ) ; return stringPool ; } | read String pool for apk binary xml file and resource table . |
26,945 | public static ResourceValue readResValue ( ByteBuffer buffer , StringPool stringPool ) { int size = Buffers . readUShort ( buffer ) ; short res0 = Buffers . readUByte ( buffer ) ; short dataType = Buffers . readUByte ( buffer ) ; switch ( dataType ) { case ResValue . ResType . INT_DEC : return ResourceValue . decimal ( buffer . getInt ( ) ) ; case ResValue . ResType . INT_HEX : return ResourceValue . hexadecimal ( buffer . getInt ( ) ) ; case ResValue . ResType . STRING : int strRef = buffer . getInt ( ) ; if ( strRef >= 0 ) { return ResourceValue . string ( strRef , stringPool ) ; } else { return null ; } case ResValue . ResType . REFERENCE : return ResourceValue . reference ( buffer . getInt ( ) ) ; case ResValue . ResType . INT_BOOLEAN : return ResourceValue . bool ( buffer . getInt ( ) ) ; case ResValue . ResType . NULL : return ResourceValue . nullValue ( ) ; case ResValue . ResType . INT_COLOR_RGB8 : case ResValue . ResType . INT_COLOR_RGB4 : return ResourceValue . rgb ( buffer . getInt ( ) , 6 ) ; case ResValue . ResType . INT_COLOR_ARGB8 : case ResValue . ResType . INT_COLOR_ARGB4 : return ResourceValue . rgb ( buffer . getInt ( ) , 8 ) ; case ResValue . ResType . DIMENSION : return ResourceValue . dimension ( buffer . getInt ( ) ) ; case ResValue . ResType . FRACTION : return ResourceValue . fraction ( buffer . getInt ( ) ) ; default : return ResourceValue . raw ( buffer . getInt ( ) , dataType ) ; } } | read res value convert from different types to string . |
26,946 | @ SuppressWarnings ( "unchecked" ) public List < CertificateMeta > parse ( ) throws CertificateException { CMSSignedData cmsSignedData ; try { cmsSignedData = new CMSSignedData ( data ) ; } catch ( CMSException e ) { throw new CertificateException ( e ) ; } Store < X509CertificateHolder > certStore = cmsSignedData . getCertificates ( ) ; SignerInformationStore signerInfos = cmsSignedData . getSignerInfos ( ) ; Collection < SignerInformation > signers = signerInfos . getSigners ( ) ; List < X509Certificate > certificates = new ArrayList < > ( ) ; for ( SignerInformation signer : signers ) { Collection < X509CertificateHolder > matches = certStore . getMatches ( signer . getSID ( ) ) ; for ( X509CertificateHolder holder : matches ) { certificates . add ( new JcaX509CertificateConverter ( ) . setProvider ( provider ) . getCertificate ( holder ) ) ; } } return CertificateMetas . from ( certificates ) ; } | get certificate info |
26,947 | public static int match ( Locale locale , Locale targetLocale ) { if ( locale == null ) { return - 1 ; } if ( locale . getLanguage ( ) . equals ( targetLocale . getLanguage ( ) ) ) { if ( locale . getCountry ( ) . equals ( targetLocale . getCountry ( ) ) ) { return 3 ; } else if ( targetLocale . getCountry ( ) . isEmpty ( ) ) { return 2 ; } else { return 0 ; } } else if ( targetLocale . getCountry ( ) . isEmpty ( ) || targetLocale . getLanguage ( ) . isEmpty ( ) ) { return 1 ; } else { return 0 ; } } | How much the given locale match the expected locale . |
26,948 | public String toStringValue ( ResourceTable resourceTable , Locale locale ) { if ( resourceTableMaps . length > 0 ) { return resourceTableMaps [ 0 ] . toString ( ) ; } else { return null ; } } | get value as string |
26,949 | public final CharSequenceTranslator with ( final CharSequenceTranslator ... translators ) { final CharSequenceTranslator [ ] newArray = new CharSequenceTranslator [ translators . length + 1 ] ; newArray [ 0 ] = this ; System . arraycopy ( translators , 0 , newArray , 1 , translators . length ) ; return new AggregateTranslator ( newArray ) ; } | Helper method to create a merger of this translator with another set of translators . Useful in customizing the standard functionality . |
26,950 | private DexClassStruct [ ] readClass ( long classDefsOff , int classDefsSize ) { Buffers . position ( buffer , classDefsOff ) ; DexClassStruct [ ] dexClassStructs = new DexClassStruct [ classDefsSize ] ; for ( int i = 0 ; i < classDefsSize ; i ++ ) { DexClassStruct dexClassStruct = new DexClassStruct ( ) ; dexClassStruct . setClassIdx ( buffer . getInt ( ) ) ; dexClassStruct . setAccessFlags ( buffer . getInt ( ) ) ; dexClassStruct . setSuperclassIdx ( buffer . getInt ( ) ) ; dexClassStruct . setInterfacesOff ( Buffers . readUInt ( buffer ) ) ; dexClassStruct . setSourceFileIdx ( buffer . getInt ( ) ) ; dexClassStruct . setAnnotationsOff ( Buffers . readUInt ( buffer ) ) ; dexClassStruct . setClassDataOff ( Buffers . readUInt ( buffer ) ) ; dexClassStruct . setStaticValuesOff ( Buffers . readUInt ( buffer ) ) ; dexClassStructs [ i ] = dexClassStruct ; } return dexClassStructs ; } | read class info . |
26,951 | private int [ ] readTypes ( long typeIdsOff , int typeIdsSize ) { Buffers . position ( buffer , typeIdsOff ) ; int [ ] typeIds = new int [ typeIdsSize ] ; for ( int i = 0 ; i < typeIdsSize ; i ++ ) { typeIds [ i ] = ( int ) Buffers . readUInt ( buffer ) ; } return typeIds ; } | read types . |
26,952 | private StringPool readStrings ( long [ ] offsets ) { StringPoolEntry [ ] entries = new StringPoolEntry [ offsets . length ] ; for ( int i = 0 ; i < offsets . length ; i ++ ) { entries [ i ] = new StringPoolEntry ( i , offsets [ i ] ) ; } String lastStr = null ; long lastOffset = - 1 ; StringPool stringpool = new StringPool ( offsets . length ) ; for ( StringPoolEntry entry : entries ) { if ( entry . getOffset ( ) == lastOffset ) { stringpool . set ( entry . getIdx ( ) , lastStr ) ; continue ; } Buffers . position ( buffer , entry . getOffset ( ) ) ; lastOffset = entry . getOffset ( ) ; String str = readString ( ) ; lastStr = str ; stringpool . set ( entry . getIdx ( ) , str ) ; } return stringpool ; } | read string pool for dex file . dex file string pool diff a bit with binary xml file or resource table . |
26,953 | private String readString ( int strLen ) { char [ ] chars = new char [ strLen ] ; for ( int i = 0 ; i < strLen ; i ++ ) { short a = Buffers . readUByte ( buffer ) ; if ( ( a & 0x80 ) == 0 ) { chars [ i ] = ( char ) a ; } else if ( ( a & 0xe0 ) == 0xc0 ) { short b = Buffers . readUByte ( buffer ) ; chars [ i ] = ( char ) ( ( ( a & 0x1F ) << 6 ) | ( b & 0x3F ) ) ; } else if ( ( a & 0xf0 ) == 0xe0 ) { short b = Buffers . readUByte ( buffer ) ; short c = Buffers . readUByte ( buffer ) ; chars [ i ] = ( char ) ( ( ( a & 0x0F ) << 12 ) | ( ( b & 0x3F ) << 6 ) | ( c & 0x3F ) ) ; } else if ( ( a & 0xf0 ) == 0xf0 ) { } else { } if ( chars [ i ] == 0 ) { } } return new String ( chars ) ; } | read Modified UTF - 8 encoding str . |
26,954 | private int readVarInts ( ) { int i = 0 ; int count = 0 ; short s ; do { if ( count > 4 ) { throw new ParserException ( "read varints error." ) ; } s = Buffers . readUByte ( buffer ) ; i |= ( s & 0x7f ) << ( count * 7 ) ; count ++ ; } while ( ( s & 0x80 ) != 0 ) ; return i ; } | read varints . |
26,955 | public List < CertificateMeta > getCertificateMetaList ( ) throws IOException , CertificateException { if ( apkSigners == null ) { parseCertificates ( ) ; } if ( apkSigners . isEmpty ( ) ) { throw new ParserException ( "ApkFile certificate not found" ) ; } return apkSigners . get ( 0 ) . getCertificateMetas ( ) ; } | Get the apk s certificate meta . If have multi signer return the certificate the first signer used . |
26,956 | public Map < String , List < CertificateMeta > > getAllCertificateMetas ( ) throws IOException , CertificateException { List < ApkSigner > apkSigners = getApkSingers ( ) ; Map < String , List < CertificateMeta > > map = new LinkedHashMap < > ( ) ; for ( ApkSigner apkSigner : apkSigners ) { map . put ( apkSigner . getPath ( ) , apkSigner . getCertificateMetas ( ) ) ; } return map ; } | Get the apk s all certificates . For each entry the key is certificate file path in apk file the value is the certificates info of the certificate file . |
26,957 | public String transBinaryXml ( String path ) throws IOException { byte [ ] data = getFileData ( path ) ; if ( data == null ) { return null ; } parseResourceTable ( ) ; XmlTranslator xmlTranslator = new XmlTranslator ( ) ; transBinaryXml ( data , xmlTranslator ) ; return xmlTranslator . getXml ( ) ; } | trans binary xml file to text xml file . |
26,958 | public List < IconFace > getAllIcons ( ) throws IOException { List < IconPath > iconPaths = getIconPaths ( ) ; if ( iconPaths . isEmpty ( ) ) { return Collections . emptyList ( ) ; } List < IconFace > iconFaces = new ArrayList < > ( iconPaths . size ( ) ) ; for ( IconPath iconPath : iconPaths ) { String filePath = iconPath . getPath ( ) ; if ( filePath . endsWith ( ".xml" ) ) { byte [ ] data = getFileData ( filePath ) ; if ( data == null ) { continue ; } parseResourceTable ( ) ; AdaptiveIconParser iconParser = new AdaptiveIconParser ( ) ; transBinaryXml ( data , iconParser ) ; Icon backgroundIcon = null ; if ( iconParser . getBackground ( ) != null ) { backgroundIcon = newFileIcon ( iconParser . getBackground ( ) , iconPath . getDensity ( ) ) ; } Icon foregroundIcon = null ; if ( iconParser . getForeground ( ) != null ) { foregroundIcon = newFileIcon ( iconParser . getForeground ( ) , iconPath . getDensity ( ) ) ; } AdaptiveIcon icon = new AdaptiveIcon ( foregroundIcon , backgroundIcon ) ; iconFaces . add ( icon ) ; } else { Icon icon = newFileIcon ( filePath , iconPath . getDensity ( ) ) ; iconFaces . add ( icon ) ; } } return iconFaces ; } | This method return icons specified in android manifest file application . The icons could be file icon color icon or adaptive icon etc . |
26,959 | public Icon getIconFile ( ) throws IOException { ApkMeta apkMeta = getApkMeta ( ) ; String iconPath = apkMeta . getIcon ( ) ; if ( iconPath == null ) { return null ; } return new Icon ( iconPath , Densities . DEFAULT , getFileData ( iconPath ) ) ; } | Get the default apk icon file . |
26,960 | public List < Icon > getIconFiles ( ) throws IOException { List < IconPath > iconPaths = getIconPaths ( ) ; List < Icon > icons = new ArrayList < > ( iconPaths . size ( ) ) ; for ( IconPath iconPath : iconPaths ) { Icon icon = newFileIcon ( iconPath . getPath ( ) , iconPath . getDensity ( ) ) ; icons . add ( icon ) ; } return icons ; } | Get all the icons for different densities . |
26,961 | private void parseResourceTable ( ) throws IOException { if ( resourceTableParsed ) { return ; } resourceTableParsed = true ; byte [ ] data = getFileData ( AndroidConstants . RESOURCE_FILE ) ; if ( data == null ) { this . resourceTable = new ResourceTable ( ) ; this . locales = Collections . emptySet ( ) ; return ; } ByteBuffer buffer = ByteBuffer . wrap ( data ) ; ResourceTableParser resourceTableParser = new ResourceTableParser ( buffer ) ; resourceTableParser . parse ( ) ; this . resourceTable = resourceTableParser . getResourceTable ( ) ; this . locales = resourceTableParser . getLocales ( ) ; } | parse resource table . |
26,962 | protected ByteBuffer findApkSignBlock ( ) throws IOException { ByteBuffer buffer = fileData ( ) . order ( ByteOrder . LITTLE_ENDIAN ) ; int len = buffer . limit ( ) ; if ( len < 22 ) { throw new RuntimeException ( "Not zip file" ) ; } int maxEOCDSize = 1024 * 100 ; EOCD eocd = null ; for ( int i = len - 22 ; i > Math . max ( 0 , len - maxEOCDSize ) ; i -- ) { int v = buffer . getInt ( i ) ; if ( v == EOCD . SIGNATURE ) { Buffers . position ( buffer , i + 4 ) ; eocd = new EOCD ( ) ; eocd . setDiskNum ( Buffers . readUShort ( buffer ) ) ; eocd . setCdStartDisk ( Buffers . readUShort ( buffer ) ) ; eocd . setCdRecordNum ( Buffers . readUShort ( buffer ) ) ; eocd . setTotalCDRecordNum ( Buffers . readUShort ( buffer ) ) ; eocd . setCdSize ( Buffers . readUInt ( buffer ) ) ; eocd . setCdStart ( Buffers . readUInt ( buffer ) ) ; eocd . setCommentLen ( Buffers . readUShort ( buffer ) ) ; } } if ( eocd == null ) { return null ; } int magicStrLen = 16 ; long cdStart = eocd . getCdStart ( ) ; Buffers . position ( buffer , cdStart - magicStrLen ) ; String magic = Buffers . readAsciiString ( buffer , magicStrLen ) ; if ( ! magic . equals ( ApkSigningBlock . MAGIC ) ) { return null ; } Buffers . position ( buffer , cdStart - 24 ) ; int blockSize = Unsigned . ensureUInt ( buffer . getLong ( ) ) ; Buffers . position ( buffer , cdStart - blockSize - 8 ) ; long size2 = Unsigned . ensureULong ( buffer . getLong ( ) ) ; if ( blockSize != size2 ) { return null ; } return Buffers . sliceAndSkip ( buffer , blockSize - magicStrLen ) ; } | Create ApkSignBlockParser for this apk file . |
26,963 | public void parse ( ) { ChunkHeader firstChunkHeader = readChunkHeader ( ) ; if ( firstChunkHeader == null ) { return ; } switch ( firstChunkHeader . getChunkType ( ) ) { case ChunkType . XML : case ChunkType . NULL : break ; case ChunkType . STRING_POOL : default : } ChunkHeader stringPoolChunkHeader = readChunkHeader ( ) ; if ( stringPoolChunkHeader == null ) { return ; } ParseUtils . checkChunkType ( ChunkType . STRING_POOL , stringPoolChunkHeader . getChunkType ( ) ) ; stringPool = ParseUtils . readStringPool ( buffer , ( StringPoolHeader ) stringPoolChunkHeader ) ; ChunkHeader chunkHeader = readChunkHeader ( ) ; if ( chunkHeader == null ) { return ; } if ( chunkHeader . getChunkType ( ) == ChunkType . XML_RESOURCE_MAP ) { long [ ] resourceIds = readXmlResourceMap ( ( XmlResourceMapHeader ) chunkHeader ) ; resourceMap = new String [ resourceIds . length ] ; for ( int i = 0 ; i < resourceIds . length ; i ++ ) { resourceMap [ i ] = Attribute . AttrIds . getString ( resourceIds [ i ] ) ; } chunkHeader = readChunkHeader ( ) ; } while ( chunkHeader != null ) { long beginPos = buffer . position ( ) ; switch ( chunkHeader . getChunkType ( ) ) { case ChunkType . XML_END_NAMESPACE : XmlNamespaceEndTag xmlNamespaceEndTag = readXmlNamespaceEndTag ( ) ; xmlStreamer . onNamespaceEnd ( xmlNamespaceEndTag ) ; break ; case ChunkType . XML_START_NAMESPACE : XmlNamespaceStartTag namespaceStartTag = readXmlNamespaceStartTag ( ) ; xmlStreamer . onNamespaceStart ( namespaceStartTag ) ; break ; case ChunkType . XML_START_ELEMENT : XmlNodeStartTag xmlNodeStartTag = readXmlNodeStartTag ( ) ; break ; case ChunkType . XML_END_ELEMENT : XmlNodeEndTag xmlNodeEndTag = readXmlNodeEndTag ( ) ; break ; case ChunkType . XML_CDATA : XmlCData xmlCData = readXmlCData ( ) ; break ; default : if ( chunkHeader . getChunkType ( ) >= ChunkType . XML_FIRST_CHUNK && chunkHeader . getChunkType ( ) <= ChunkType . XML_LAST_CHUNK ) { Buffers . skip ( buffer , chunkHeader . getBodySize ( ) ) ; } else { throw new ParserException ( "Unexpected chunk type:" + chunkHeader . getChunkType ( ) ) ; } } Buffers . position ( buffer , beginPos + chunkHeader . getBodySize ( ) ) ; chunkHeader = readChunkHeader ( ) ; } } | Parse binary xml . |
26,964 | private String getFinalValueAsString ( String attributeName , String str ) { int value = Integer . parseInt ( str ) ; switch ( attributeName ) { case "screenOrientation" : return AttributeValues . getScreenOrientation ( value ) ; case "configChanges" : return AttributeValues . getConfigChanges ( value ) ; case "windowSoftInputMode" : return AttributeValues . getWindowSoftInputMode ( value ) ; case "launchMode" : return AttributeValues . getLaunchMode ( value ) ; case "installLocation" : return AttributeValues . getInstallLocation ( value ) ; case "protectionLevel" : return AttributeValues . getProtectionLevel ( value ) ; default : return str ; } } | trans int attr value to string |
26,965 | public static < T > T parse ( ByteBuffer encoded , Class < T > containerClass ) throws Asn1DecodingException { BerDataValue containerDataValue ; try { containerDataValue = new ByteBufferBerDataValueReader ( encoded ) . readDataValue ( ) ; } catch ( BerDataValueFormatException e ) { throw new Asn1DecodingException ( "Failed to decode top-level data value" , e ) ; } if ( containerDataValue == null ) { throw new Asn1DecodingException ( "Empty input" ) ; } return parse ( containerDataValue , containerClass ) ; } | Returns the ASN . 1 structure contained in the BER encoded input . |
26,966 | public String getString ( String name ) { Attribute attribute = get ( name ) ; if ( attribute == null ) { return null ; } return attribute . getValue ( ) ; } | Get attribute with name return value as string |
26,967 | public static ApkMeta getMetaInfo ( String apkFilePath , Locale locale ) throws IOException { try ( ApkFile apkFile = new ApkFile ( apkFilePath ) ) { apkFile . setPreferredLocale ( locale ) ; return apkFile . getApkMeta ( ) ; } } | Get apk meta info for apk file with locale |
26,968 | public static float restrict ( float value , float minValue , float maxValue ) { return Math . max ( minValue , Math . min ( value , maxValue ) ) ; } | Keeps value within provided bounds . |
26,969 | private void initDecorMargins ( ) { if ( DecorUtils . isCanHaveTransparentDecor ( ) ) { Views . getParams ( views . appBar ) . height += DecorUtils . getStatusBarHeight ( this ) ; } DecorUtils . paddingForStatusBar ( views . toolbar , true ) ; DecorUtils . paddingForStatusBar ( views . pagerToolbar , true ) ; DecorUtils . paddingForStatusBar ( views . fullImageToolbar , true ) ; DecorUtils . paddingForNavBar ( views . grid ) ; DecorUtils . marginForNavBar ( views . pagerTitle ) ; } | Adjusting margins and paddings to fit translucent decor . |
26,970 | private void initTopImage ( ) { views . fullImageToolbar . setNavigationIcon ( R . drawable . ic_arrow_back_white_24dp ) ; views . fullImageToolbar . setNavigationOnClickListener ( view -> onBackPressed ( ) ) ; imageAnimator = GestureTransitions . from ( views . appBarImage ) . into ( views . fullImage ) ; imageAnimator . addPositionUpdateListener ( this :: applyFullImageState ) ; views . appBarImage . setOnClickListener ( view -> { getSettingsController ( ) . apply ( views . fullImage ) ; imageAnimator . enterSingle ( true ) ; } ) ; } | Initializing top image expanding animation . |
26,971 | private void initPager ( ) { pagerAdapter = new PhotoPagerAdapter ( views . pager , getSettingsController ( ) ) ; pagerListener = new ViewPager . SimpleOnPageChangeListener ( ) { public void onPageSelected ( int position ) { onPhotoInPagerSelected ( position ) ; } } ; views . pager . setAdapter ( pagerAdapter ) ; views . pager . addOnPageChangeListener ( pagerListener ) ; views . pager . setPageTransformer ( true , new DepthPageTransformer ( ) ) ; views . pagerToolbar . setNavigationIcon ( R . drawable . ic_arrow_back_white_24dp ) ; views . pagerToolbar . setNavigationOnClickListener ( view -> onBackPressed ( ) ) ; pagerAdapter . setImageClickListener ( ( ) -> { if ( ! listAnimator . isLeaving ( ) ) { showSystemUi ( ! isSystemUiShown ( ) ) ; } } ) ; getWindow ( ) . getDecorView ( ) . setOnSystemUiVisibilityChangeListener ( visibility -> views . pagerToolbar . animate ( ) . alpha ( isSystemUiShown ( ) ? 1f : 0f ) ) ; } | Initializing pager and fullscreen mode . |
26,972 | private void onPhotoInPagerSelected ( int position ) { Photo photo = pagerAdapter . getPhoto ( position ) ; if ( photo == null ) { views . pagerTitle . setText ( null ) ; } else { SpannableBuilder title = new SpannableBuilder ( DemoActivity . this ) ; title . append ( photo . getTitle ( ) ) . append ( "\n" ) . createStyle ( ) . setColorResId ( R . color . text_secondary_light ) . apply ( ) . append ( R . string . demo_photo_by ) . append ( " " ) . append ( photo . getOwner ( ) . getUsername ( ) ) ; views . pagerTitle . setText ( title . build ( ) ) ; } } | Setting up photo title for current pager position . |
26,973 | private void initPagerAnimator ( ) { final SimpleTracker gridTracker = new SimpleTracker ( ) { public View getViewAt ( int pos ) { RecyclerView . ViewHolder holder = views . grid . findViewHolderForLayoutPosition ( pos ) ; return holder == null ? null : PhotoListAdapter . getImage ( holder ) ; } } ; final SimpleTracker pagerTracker = new SimpleTracker ( ) { public View getViewAt ( int pos ) { RecyclePagerAdapter . ViewHolder holder = pagerAdapter . getViewHolder ( pos ) ; return holder == null ? null : PhotoPagerAdapter . getImage ( holder ) ; } } ; listAnimator = GestureTransitions . from ( views . grid , gridTracker ) . into ( views . pager , pagerTracker ) ; listAnimator . addPositionUpdateListener ( this :: applyFullPagerState ) ; } | Initializing grid - to - pager animation . |
26,974 | @ Result ( FlickrApi . LOAD_IMAGES_EVENT ) private void onPhotosLoaded ( List < Photo > photos , boolean hasMore ) { final boolean onBottom = views . grid . findViewHolderForAdapterPosition ( gridAdapter . getCount ( ) - 1 ) != null ; if ( onBottom ) { views . grid . stopScroll ( ) ; } gridAdapter . setPhotos ( photos , hasMore ) ; pagerAdapter . setPhotos ( photos ) ; gridAdapter . onNextItemsLoaded ( ) ; pagerListener . onPageSelected ( views . pager . getCurrentItem ( ) ) ; if ( savedPagerPosition != NO_POSITION && savedPagerPosition < photos . size ( ) ) { pagerAdapter . setActivated ( true ) ; listAnimator . enter ( savedPagerPosition , false ) ; } if ( savedGridPosition != NO_POSITION && savedGridPosition < photos . size ( ) ) { ( ( GridLayoutManager ) views . grid . getLayoutManager ( ) ) . scrollToPositionWithOffset ( savedGridPosition , savedGridPositionFromTop ) ; } clearScreenState ( ) ; } | Photos loading results callback . |
26,975 | @ Failure ( FlickrApi . LOAD_IMAGES_EVENT ) private void onPhotosLoadFail ( ) { gridAdapter . onNextItemsError ( ) ; if ( savedPagerPosition != NO_POSITION ) { applyFullPagerState ( 0f , true ) ; } clearScreenState ( ) ; } | Photos loading failure callback . |
26,976 | public String pack ( ) { String viewStr = view . flattenToString ( ) ; String viewportStr = viewport . flattenToString ( ) ; String visibleStr = visible . flattenToString ( ) ; String imageStr = image . flattenToString ( ) ; return TextUtils . join ( DELIMITER , new String [ ] { viewStr , viewportStr , visibleStr , imageStr } ) ; } | Packs this ViewPosition into string which can be passed i . e . between activities . |
26,977 | private void warmUpScaleDetector ( ) { long time = System . currentTimeMillis ( ) ; MotionEvent event = MotionEvent . obtain ( time , time , MotionEvent . ACTION_CANCEL , 0f , 0f , 0 ) ; onTouchEvent ( event ) ; event . recycle ( ) ; } | Scale detector is a little buggy when first time scale is occurred . So we will feed it with fake motion event to warm it up . |
26,978 | public static void getMovementAreaPosition ( Settings settings , Rect out ) { tmpRect1 . set ( 0 , 0 , settings . getViewportW ( ) , settings . getViewportH ( ) ) ; Gravity . apply ( settings . getGravity ( ) , settings . getMovementAreaW ( ) , settings . getMovementAreaH ( ) , tmpRect1 , out ) ; } | Calculates movement area position within viewport area with gravity applied . |
26,979 | public static void getDefaultPivot ( Settings settings , Point out ) { getMovementAreaPosition ( settings , tmpRect2 ) ; Gravity . apply ( settings . getGravity ( ) , 0 , 0 , tmpRect2 , tmpRect1 ) ; out . set ( tmpRect1 . left , tmpRect1 . top ) ; } | Calculates default pivot point for scale and rotation . |
26,980 | public void startScroll ( float startValue , float finalValue ) { finished = false ; startRtc = SystemClock . elapsedRealtime ( ) ; this . startValue = startValue ; this . finalValue = finalValue ; currValue = startValue ; } | Starts an animation from startValue to finalValue . |
26,981 | public boolean computeScroll ( ) { if ( finished ) { return false ; } long elapsed = SystemClock . elapsedRealtime ( ) - startRtc ; if ( elapsed >= duration ) { finished = true ; currValue = finalValue ; return false ; } float time = interpolator . getInterpolation ( ( float ) elapsed / duration ) ; currValue = interpolate ( startValue , finalValue , time ) ; return true ; } | Computes the current value returning true if the animation is still active and false if the animation has finished . |
26,982 | public static void loadThumb ( ImageView image , int thumbId ) { final RequestOptions options = new RequestOptions ( ) . diskCacheStrategy ( DiskCacheStrategy . NONE ) . override ( Target . SIZE_ORIGINAL ) . dontTransform ( ) ; Glide . with ( image ) . load ( thumbId ) . apply ( options ) . into ( image ) ; } | Loads thumbnail . |
26,983 | public static void loadFull ( ImageView image , int imageId , int thumbId ) { final RequestOptions options = new RequestOptions ( ) . diskCacheStrategy ( DiskCacheStrategy . NONE ) . override ( Target . SIZE_ORIGINAL ) . dontTransform ( ) ; final RequestBuilder < Drawable > thumbRequest = Glide . with ( image ) . load ( thumbId ) . apply ( options ) ; Glide . with ( image ) . load ( imageId ) . apply ( options ) . thumbnail ( thumbRequest ) . into ( image ) ; } | Loads thumbnail and then replaces it with full image . |
26,984 | State toggleMinMaxZoom ( State state , float pivotX , float pivotY ) { zoomBounds . set ( state ) ; final float minZoom = zoomBounds . getFitZoom ( ) ; final float maxZoom = settings . getDoubleTapZoom ( ) > 0f ? settings . getDoubleTapZoom ( ) : zoomBounds . getMaxZoom ( ) ; final float middleZoom = 0.5f * ( minZoom + maxZoom ) ; final float targetZoom = state . getZoom ( ) < middleZoom ? maxZoom : minZoom ; final State end = state . copy ( ) ; end . zoomTo ( targetZoom , pivotX , pivotY ) ; return end ; } | Maximizes zoom if it closer to min zoom or minimizes it if it closer to max zoom . |
26,985 | @ SuppressWarnings ( "SameParameterValue" ) State restrictStateBoundsCopy ( State state , State prevState , float pivotX , float pivotY , boolean allowOverscroll , boolean allowOverzoom , boolean restrictRotation ) { tmpState . set ( state ) ; boolean changed = restrictStateBounds ( tmpState , prevState , pivotX , pivotY , allowOverscroll , allowOverzoom , restrictRotation ) ; return changed ? tmpState . copy ( ) : null ; } | Restricts state s translation and zoom bounds . |
26,986 | static void applyScaleType ( ImageView . ScaleType type , int dwidth , int dheight , int vwidth , int vheight , Matrix imageMatrix , Matrix outMatrix ) { if ( ImageView . ScaleType . CENTER == type ) { outMatrix . setTranslate ( ( vwidth - dwidth ) * 0.5f , ( vheight - dheight ) * 0.5f ) ; } else if ( ImageView . ScaleType . CENTER_CROP == type ) { float scale ; float dx = 0 ; float dy = 0 ; if ( dwidth * vheight > vwidth * dheight ) { scale = ( float ) vheight / ( float ) dheight ; dx = ( vwidth - dwidth * scale ) * 0.5f ; } else { scale = ( float ) vwidth / ( float ) dwidth ; dy = ( vheight - dheight * scale ) * 0.5f ; } outMatrix . setScale ( scale , scale ) ; outMatrix . postTranslate ( dx , dy ) ; } else if ( ImageView . ScaleType . CENTER_INSIDE == type ) { float scale ; float dx ; float dy ; if ( dwidth <= vwidth && dheight <= vheight ) { scale = 1.0f ; } else { scale = Math . min ( ( float ) vwidth / ( float ) dwidth , ( float ) vheight / ( float ) dheight ) ; } dx = ( vwidth - dwidth * scale ) * 0.5f ; dy = ( vheight - dheight * scale ) * 0.5f ; outMatrix . setScale ( scale , scale ) ; outMatrix . postTranslate ( dx , dy ) ; } else { Matrix . ScaleToFit scaleToFit = scaleTypeToScaleToFit ( type ) ; if ( scaleToFit == null ) { outMatrix . set ( imageMatrix ) ; } else { tmpSrc . set ( 0 , 0 , dwidth , dheight ) ; tmpDst . set ( 0 , 0 , vwidth , vheight ) ; outMatrix . setRectToRect ( tmpSrc , tmpDst , scaleToFit ) ; } } } | Helper method to calculate drawing matrix . Based on ImageView source code . |
26,987 | private void swapAnimator ( ViewPositionAnimator old , ViewPositionAnimator next ) { final float position = old . getPosition ( ) ; final boolean isLeaving = old . isLeaving ( ) ; final boolean isAnimating = old . isAnimating ( ) ; if ( GestureDebug . isDebugAnimator ( ) ) { Log . d ( TAG , "Swapping animator for " + getRequestedId ( ) ) ; } cleanupAnimator ( old ) ; if ( getFromView ( ) != null ) { next . enter ( getFromView ( ) , false ) ; } else if ( getFromPos ( ) != null ) { next . enter ( getFromPos ( ) , false ) ; } initAnimator ( next ) ; next . setState ( position , isLeaving , isAnimating ) ; } | Replaces old animator with new one preserving state . |
26,988 | public ZoomBounds set ( State state ) { float imageWidth = settings . getImageW ( ) ; float imageHeight = settings . getImageH ( ) ; float areaWidth = settings . getMovementAreaW ( ) ; float areaHeight = settings . getMovementAreaH ( ) ; if ( imageWidth == 0f || imageHeight == 0f || areaWidth == 0f || areaHeight == 0f ) { minZoom = maxZoom = fitZoom = 1f ; return this ; } minZoom = settings . getMinZoom ( ) ; maxZoom = settings . getMaxZoom ( ) ; final float rotation = state . getRotation ( ) ; if ( ! State . equals ( rotation , 0f ) ) { if ( settings . getFitMethod ( ) == Settings . Fit . OUTSIDE ) { tmpMatrix . setRotate ( - rotation ) ; tmpRectF . set ( 0 , 0 , areaWidth , areaHeight ) ; tmpMatrix . mapRect ( tmpRectF ) ; areaWidth = tmpRectF . width ( ) ; areaHeight = tmpRectF . height ( ) ; } else { tmpMatrix . setRotate ( rotation ) ; tmpRectF . set ( 0 , 0 , imageWidth , imageHeight ) ; tmpMatrix . mapRect ( tmpRectF ) ; imageWidth = tmpRectF . width ( ) ; imageHeight = tmpRectF . height ( ) ; } } switch ( settings . getFitMethod ( ) ) { case HORIZONTAL : fitZoom = areaWidth / imageWidth ; break ; case VERTICAL : fitZoom = areaHeight / imageHeight ; break ; case INSIDE : fitZoom = Math . min ( areaWidth / imageWidth , areaHeight / imageHeight ) ; break ; case OUTSIDE : fitZoom = Math . max ( areaWidth / imageWidth , areaHeight / imageHeight ) ; break ; case NONE : default : fitZoom = minZoom > 0f ? minZoom : 1f ; } if ( minZoom <= 0f ) { minZoom = fitZoom ; } if ( maxZoom <= 0f ) { maxZoom = fitZoom ; } if ( fitZoom > maxZoom ) { if ( settings . isFillViewport ( ) ) { maxZoom = fitZoom ; } else { fitZoom = maxZoom ; } } if ( minZoom > maxZoom ) { minZoom = maxZoom ; } if ( fitZoom < minZoom ) { if ( settings . isFillViewport ( ) ) { minZoom = fitZoom ; } else { fitZoom = minZoom ; } } return this ; } | Calculates min max and fit zoom levels for given state and according to current settings . |
26,989 | public Settings setMovementArea ( int width , int height ) { isMovementAreaSpecified = true ; movementAreaW = width ; movementAreaH = height ; return this ; } | Setting movement area size . Viewport area will be used instead if no movement area is specified . |
26,990 | private void runAfterImageDraw ( final Runnable action ) { image . getViewTreeObserver ( ) . addOnPreDrawListener ( new OnPreDrawListener ( ) { public boolean onPreDraw ( ) { image . getViewTreeObserver ( ) . removeOnPreDrawListener ( this ) ; runOnNextFrame ( action ) ; return true ; } } ) ; image . invalidate ( ) ; } | Runs provided action after image is drawn for the first time . |
26,991 | public void update ( boolean animate ) { final Settings settings = imageView == null ? null : imageView . getController ( ) . getSettings ( ) ; if ( settings != null && getWidth ( ) > 0 && getHeight ( ) > 0 ) { if ( aspect > 0f || aspect == ORIGINAL_ASPECT ) { final int width = getWidth ( ) - getPaddingLeft ( ) - getPaddingRight ( ) ; final int height = getHeight ( ) - getPaddingTop ( ) - getPaddingBottom ( ) ; final float realAspect = aspect == ORIGINAL_ASPECT ? settings . getImageW ( ) / ( float ) settings . getImageH ( ) : aspect ; if ( realAspect > ( float ) width / ( float ) height ) { settings . setMovementArea ( width , ( int ) ( width / realAspect ) ) ; } else { settings . setMovementArea ( ( int ) ( height * realAspect ) , height ) ; } if ( animate ) { imageView . getController ( ) . animateKeepInBounds ( ) ; } else { imageView . getController ( ) . updateState ( ) ; } } startRect . set ( areaRect ) ; GravityUtils . getMovementAreaPosition ( settings , tmpRect ) ; endRect . set ( tmpRect ) ; stateScroller . forceFinished ( ) ; if ( animate ) { stateScroller . setDuration ( settings . getAnimationsDuration ( ) ) ; stateScroller . startScroll ( 0f , 1f ) ; animationEngine . start ( ) ; } else { setBounds ( endRect , endRounding ) ; } } } | Applies area size area position and corners rounding with optional animation . |
26,992 | private void drawRectHole ( Canvas canvas ) { paint . setStyle ( Paint . Style . FILL ) ; paint . setColor ( backColor ) ; tmpRectF . set ( 0f , 0f , canvas . getWidth ( ) , areaRect . top ) ; canvas . drawRect ( tmpRectF , paint ) ; tmpRectF . set ( 0f , areaRect . bottom , canvas . getWidth ( ) , canvas . getHeight ( ) ) ; canvas . drawRect ( tmpRectF , paint ) ; tmpRectF . set ( 0f , areaRect . top , areaRect . left , areaRect . bottom ) ; canvas . drawRect ( tmpRectF , paint ) ; tmpRectF . set ( areaRect . right , areaRect . top , canvas . getWidth ( ) , areaRect . bottom ) ; canvas . drawRect ( tmpRectF , paint ) ; } | If cropping area is not rounded we can draw it much faster |
26,993 | @ SuppressWarnings ( "deprecation" ) private void drawRoundedHole ( Canvas canvas ) { paint . setStyle ( Paint . Style . FILL ) ; paint . setColor ( backColor ) ; if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . LOLLIPOP ) { canvas . saveLayer ( 0 , 0 , canvas . getWidth ( ) , canvas . getHeight ( ) , null ) ; } else { canvas . saveLayer ( 0 , 0 , canvas . getWidth ( ) , canvas . getHeight ( ) , null , 0 ) ; } canvas . drawPaint ( paint ) ; final float rx = rounding * 0.5f * areaRect . width ( ) ; final float ry = rounding * 0.5f * areaRect . height ( ) ; canvas . drawRoundRect ( areaRect , rx , ry , paintClear ) ; canvas . restore ( ) ; } | If cropping area is rounded we have to use off - screen buffer to punch a hole |
26,994 | public JSONObject parseToJson ( HTTPResponse response ) throws JSONException { this . response = response ; return new JSONObject ( response . body ) ; } | Parse HTTP response to JSONObject |
26,995 | public HTTPResponse handleError ( HTTPResponse response ) throws HTTPException { if ( response . statusCode < 200 || response . statusCode >= 300 ) { throw new HTTPException ( response . statusCode , response . reason ) ; } return response ; } | Handle http status error |
26,996 | public AssetPage addAsset ( AssetPage asset , boolean renderImmediately ) { final String assetKey = asset . getReference ( ) . toString ( ) ; if ( assets . containsKey ( assetKey ) ) { return assets . get ( assetKey ) ; } else { assets . put ( assetKey , asset ) ; if ( renderImmediately ) { context . get ( ) . renderAsset ( asset ) ; } return asset ; } } | this point . Inline resources are rendered directly into the page and should not be rendered as a proper resource |
26,997 | public static String getRelativeFilename ( String sourcePath , String baseDir ) { if ( sourcePath . contains ( baseDir ) ) { int indexOf = sourcePath . indexOf ( baseDir ) ; if ( indexOf + baseDir . length ( ) < sourcePath . length ( ) ) { String relative = sourcePath . substring ( ( indexOf + baseDir . length ( ) ) ) ; if ( relative . startsWith ( "/" ) ) { relative = relative . substring ( 1 ) ; } else if ( relative . startsWith ( "\\" ) ) { relative = relative . substring ( 1 ) ; } return relative ; } } return sourcePath ; } | Removes the base directory from a file path . Leading slashes are also removed from the resulting file path . |
26,998 | public static < T > T first ( List < T > items ) { if ( items != null && items . size ( ) > 0 ) { return items . get ( 0 ) ; } return null ; } | Returns the first item in a list if possible returning null otherwise . |
26,999 | List < String > findInPackage ( Test test , String packageName ) { List < String > localClsssOrPkgs = new ArrayList < String > ( ) ; packageName = packageName . replace ( '.' , '/' ) ; Enumeration < URL > urls ; try { urls = classloader . getResources ( packageName ) ; if ( ! urls . hasMoreElements ( ) ) { log . warn ( "Unable to find any resources for package '" + packageName + "'" ) ; } } catch ( IOException ioe ) { log . warn ( "Could not read package: " + packageName ) ; return localClsssOrPkgs ; } return findInPackageWithUrls ( test , packageName , urls ) ; } | Scans for classes starting at the package provided and descending into subpackages . Each class is offered up to the Test as it is discovered and if the Test returns true the class is retained . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.