Input: adds a param and value . [CODESPLIT] public final void addParam ( String key , int value ) { //System.out.println(" adding " + key + " = " + value); paramInt . put ( key , new Integer ( value ) ) ; paramStr . put ( key , Integer . toString ( value ) ) ; }


Input: adds a param and value . [CODESPLIT] public final void addParam ( String key , float value ) { //System.out.println(" adding " + key + " = " + value); paramDbl . put ( key , new Double ( value ) ) ; paramStr . put ( key , Float . toString ( value ) ) ; }


Input: gets a param and value . [CODESPLIT] public final String getParam ( String key ) { String value = paramStr . get ( key ) ; if ( value == null ) { // check the dbl and int tables Double result = paramDbl . get ( key ) ; if ( result != null ) { value = result . toString ( ) ; } else { Integer intResult = paramInt . get ( key ) ; if ( intResult != null ) { value = intResult . toString ( ) ; } } // save it back off to the string table for next time if ( value != null ) { paramStr . put ( key , value ) ; } } if ( debug && value == null ) { System . out . println ( key + " value not found" ) ; } return value ; }


Input: Compare GridDefRecords the numerics will use nearlyEquals so values that differ in 3 or 4th decimal places will return equal . This is being coded because the NDFD model dx differ in the 3 decimal place otherwise equal . [CODESPLIT] public static boolean compare ( GridDefRecord local , GridDefRecord other ) { java . util . Set < String > keys = local . getKeys ( ) ; java . util . Set < String > okeys = other . getKeys ( ) ; if ( keys . size ( ) != okeys . size ( ) ) return false ; for ( String key : keys ) { if ( key . equals ( WIND_FLAG ) || key . equals ( RESOLUTION ) || key . equals ( VECTOR_COMPONENT_FLAG ) || key . equals ( GDS_KEY ) ) continue ; String val = local . getParam ( key ) ; String oval = other . getParam ( key ) ; // if ( val . matches ( "^[0-9]+\\.[0-9]*" ) ) { //double double d = local . getDouble ( key ) ; double od = other . getDouble ( key ) ; if ( ! Misc . nearlyEquals ( d , od ) ) return false ; } else if ( val . matches ( "^[0-9]+" ) ) { // int if ( ! val . equals ( oval ) ) return false ; } else { // String if ( ! val . equals ( oval ) ) return false ; } } return true ; }


Input: Step 1 - read and extract a Bufr Message [CODESPLIT] public void process ( InputStream is ) throws IOException { int pos = - 1 ; Buffer b = null ; while ( true ) { b = ( pos < 0 ) ? readBuffer ( is ) : readBuffer ( is , b , pos ) ; pos = process ( b , is ) ; if ( b . done ) break ; } }


Input: return where in the buffer we got to . [CODESPLIT] private int process ( Buffer b , InputStream is ) throws IOException { int start = 0 ; while ( start < b . have ) { int matchPos = matcher . indexOf ( b . buff , start , b . have - start ) ; // didnt find "BUFR" match if ( matchPos < 0 ) { if ( start == 0 ) // discard all but last 3 bytes return b . have - 3 ; else return start ; // indicates part of the buffer thats not processed } // do we have the length already read ?? if ( matchPos + 6 >= b . have ) { return start ; // this will save the end of the buffer and read more in. } // read BUFR message length int b1 = ( b . buff [ matchPos + 4 ] & 0xff ) ; int b2 = ( b . buff [ matchPos + 5 ] & 0xff ) ; int b3 = ( b . buff [ matchPos + 6 ] & 0xff ) ; int messLen = b1 << 16 | b2 << 8 | b3 ; // System.out.println("match at=" + matchPos + " len= " + messLen); // create a task for this message //int headerLen = matchPos - start; MessageTask task = new MessageTask ( messLen ) ; task . header = extractHeader ( start , matchPos , b ) ; // copy message bytes into it int last = matchPos + messLen ; if ( last > b . have ) { task . have = b . have - matchPos ; System . arraycopy ( b . buff , matchPos , task . mess , 0 , task . have ) ; // read the rest of the message if ( ! readBuffer ( is , task . mess , task . have , task . len - task . have ) ) { System . out . println ( "Failed to read remaining BUFR message" ) ; break ; } } else { task . have = task . len ; System . arraycopy ( b . buff , matchPos , task . mess , 0 , task . have ) ; } boolean ok = true ; // check on ending for ( int i = task . len - 4 ; i < task . len ; i ++ ) { int bb = task . mess [ i ] ; if ( bb != 55 ) { //System.out.println("Missing End of BUFR message at pos=" + i + " " + bb); ok = false ; bad_msgs ++ ; } } try { if ( ok ) messQ . put ( task ) ; total_msgs ++ ; //System.out.println(" added message " + task.id + " start=" + matchPos + " end= " + (matchPos + messLen)); } catch ( InterruptedException e ) { System . out . println ( " interrupted queue put - assume process exit" ) ; break ; } start = matchPos + messLen + 1 ; } return - 1 ; }


Input: / * message DataRow { string fullName = 1 ; DataType dataType = 2 ; Section section = 3 ; bool bigend = 4 ; uint32 version = 5 ; bool isVlen = 7 ; uint32 nelems = 9 ; [CODESPLIT] public NcStreamProto . DataRow encodeData3 ( String name , boolean isVlen , Section section , Array data ) { NcStreamProto . DataRow . Builder builder = NcStreamProto . DataRow . newBuilder ( ) ; encodeData3 ( builder , name , isVlen , section , data ) ; return builder . build ( ) ; }


Input:
/ * message Member { string shortName = 1 ; DataType dataType = 2 ; repeated uint32 shape = 3 ; // or section? bool isVlen = 4 ; } [CODESPLIT] NcStreamProto . ArrayStructureRow . Builder encodeStructureData ( String structName , Array data ) { assert data instanceof ArrayStructure ; ArrayStructure as = ( ArrayStructure ) data ; int nelems = ( int ) as . getSize ( ) ; List < MemberData > memberData = new ArrayList <> ( ) ; StructureMembers sm = as . getStructureMembers ( ) ; for ( StructureMembers . Member m : sm . getMembers ( ) ) { memberData . add ( new MemberData ( m , nelems ) ) ; } // use most efficient form of data extraction for ( int recno = 0 ; recno < nelems ; recno ++ ) { for ( MemberData md : memberData ) { if ( md . member . isVariableLength ( ) ) { md . vlenList . add ( as . getArray ( recno , md . member ) ) ; } else { extractData ( as , recno , md ) ; } } } NcStreamProto . ArrayStructureRow . Builder builder = NcStreamProto . ArrayStructureRow . newBuilder ( ) ; for ( MemberData md : memberData ) { NcStreamProto . Member . Builder member = NcStreamProto . Member . newBuilder ( ) ; member . setShortName ( md . member . getName ( ) ) ; member . setDataType ( NcStream . convertDataType ( md . member . getDataType ( ) ) ) ; /* LOOK
      member.setNelems(md.nelems);
      if (md.member.isVariableLength()) {
        md.completeVlens();
        nested.addAllVlens (md.vlens);
        nested.setPrimdata(ByteString.copyFrom(md.bb));

      } else if (md.member.getDataType() == DataType.STRING)
        nested.addAllStringdata(md.stringList);
      else if (md.member.getDataType() == DataType.OPAQUE)
        nested.addAllOpaquedata(md.opaqueList);
      else
        nested.setPrimdata(ByteString.copyFrom(md.bb)); */ builder . addMembers ( member ) ; } return builder ; }


Input: Invoked once on first request so that everything is available especially Spring stuff . [CODESPLIT] public void doonce ( HttpServletRequest req ) throws SendError { if ( once ) return ; super . initOnce ( req ) ; if ( this . uploaddir == null ) throw new SendError ( HttpStatus . SC_PRECONDITION_FAILED , "Upload disabled" ) ; this . uploaddirname = new File ( this . uploaddir ) . getName ( ) ; // Get the upload form File upform = null ; upform = tdsContext . getUploadForm ( ) ; if ( upform == null ) { // Look in WEB-INF directory File root = tdsContext . getServletRootDirectory ( ) ; upform = new File ( root , DEFAULTUPLOADFORM ) ; } try { this . uploadform = loadForm ( upform ) ; } catch ( IOException ioe ) { throw new SendError ( HttpStatus . SC_PRECONDITION_FAILED , ioe ) ; } }


Input: Controller entry point ( s ) [CODESPLIT] @ RequestMapping ( value = "**" , method = RequestMethod . GET ) public void doGet ( HttpServletRequest req , HttpServletResponse res ) throws ServletException { try { setup ( req , res ) ; switch ( this . params . command ) { case NONE : case UPLOAD : // Send back the upload form sendForm ( "No files uploaded" ) ; break ; case INQUIRE : String result = inquire ( ) ; // Send back the inquiry answers sendOK ( result ) ; break ; default : throw new SendError ( res . SC_BAD_REQUEST , "Unknown command: " + this . params . command ) ; } } catch ( SendError se ) { sendError ( se ) ; } catch ( Exception e ) { String msg = getStackTrace ( e ) ; sendError ( HttpServletResponse . SC_INTERNAL_SERVER_ERROR , msg , e ) ; } }


Input: / * Parser core [CODESPLIT] void projections ( Ceparse state , Object list0 ) throws ParseException { ast . projections = ( List < ASTprojection > ) list0 ; }


Input: / * Selection Procedures [CODESPLIT] Object clauselist ( Ceparse state , Object list0 , Object decl ) throws ParseException { List < ASTclause > list = ( List < ASTclause > ) list0 ; if ( list == null ) list = new ArrayList < ASTclause > ( ) ; list . add ( ( ASTclause ) decl ) ; return list ; }


Input: Remove double quotes from around a string . If there s not both start and ending quotes does nothing . [CODESPLIT] String removeQuotes ( String s ) { if ( s . startsWith ( "\"" ) && s . endsWith ( "\"" ) ) return s . substring ( 1 , s . length ( ) - 1 ) ; else return s ; }


Input:
Given a stack of BaseType variables mark these as part of the current projection . This function assumes that if the TOS contains a Ctor type variable all of its members are to be projected . Also assume all variables under the TOS are Ctor variables and only the ctor itself is to be projected ; the member within the Ctor that is part of the projection will be on the stack too . [CODESPLIT] void markStackedVariables ( Stack s ) { // Reverse the stack.
 Stack bts = new Stack ( ) ; // LogStream.err.println("Variables to be marked:");
 while ( ! s . empty ( ) ) { // LogStream.err.println(((BaseType)s.peek()).getName());
 bts . push ( s . pop ( ) ) ; } // For each but the last stack element, set the projection.
 // setProject(true, false) for a ctor type sets the projection for
 // the ctor itself but *does not* set the projection for all its
 // children. Thus, if a user wants the variable S.X, and S contains Y
 // and Z too, S's projection will be set (so serialize will descend
 // into S) but X, Y and Z's projection remain clear. In this example,
 // X's projection is set by the code that follows the while loop.
 // 1/28/2000 jhrg
 while ( bts . size ( ) > 1 ) { ServerMethods ct = ( ServerMethods ) bts . pop ( ) ; ct . setProject ( true , false ) ; } // For the last element, project the entire variable.
 ServerMethods bt = ( ServerMethods ) bts . pop ( ) ; bt . setProject ( true , true ) ; }


Input: This parses then fills in the evaluator from the AST [CODESPLIT] public boolean constraint_expression ( CEEvaluator ceEval , BaseTypeFactory factory , ClauseFactory clauseFactory ) throws DAP2Exception , ParseException { ServerDDS sdds = ceEval . getDDS ( ) ; if ( ! parse ( ) ) return false ; ast . init ( ceEval , factory , clauseFactory , sdds , getASTnodeset ( ) ) ; ast . walkConstraint ( ) ; return true ; }


Input: write ncml from given dataset [CODESPLIT] boolean writeNcml ( String location ) { boolean err = false ; closeOpenFiles ( ) ; try { final String result ; ds = openDataset ( location , addCoords , null ) ; if ( ds == null ) { editor . setText ( "Failed to open <" + location + ">" ) ; } else { final NcMLWriter ncmlWriter = new NcMLWriter ( ) ; final Element netcdfElem = ncmlWriter . makeNetcdfElement ( ds , null ) ; result = ncmlWriter . writeToString ( netcdfElem ) ; editor . setText ( result ) ; editor . setCaretPosition ( 0 ) ; } } catch ( Exception e ) { final StringWriter sw = new StringWriter ( 10000 ) ; e . printStackTrace ( ) ; e . printStackTrace ( new PrintWriter ( sw ) ) ; editor . setText ( sw . toString ( ) ) ; err = true ; } return ! err ; }


Input: Read text from textArea through NcMLReader then write it back out via resulting dataset [CODESPLIT] void doTransform ( String text ) { try { final StringReader reader = new StringReader ( text ) ; final NetcdfDataset ncd = NcMLReader . readNcML ( reader , null ) ; final StringWriter sw = new StringWriter ( 10000 ) ; ncd . writeNcML ( sw , null ) ; editor . setText ( sw . toString ( ) ) ; editor . setCaretPosition ( 0 ) ; JOptionPane . showMessageDialog ( this , "File successfully transformed" ) ; } catch ( IOException ioe ) { JOptionPane . showMessageDialog ( this , "ERROR: " + ioe . getMessage ( ) ) ; ioe . printStackTrace ( ) ; } }


Input: Read text from textArea through NcMLReader then write it back out via resulting dataset [CODESPLIT] private void checkNcml ( Formatter f ) { if ( ncmlLocation == null ) { return ; } try { NetcdfDataset ncd = NetcdfDataset . openDataset ( ncmlLocation ) ; ncd . check ( f ) ; } catch ( IOException ioe ) { JOptionPane . showMessageDialog ( this , "ERROR: " + ioe . getMessage ( ) ) ; ioe . printStackTrace ( ) ; } }


Input: static so can be called from static enum classes [CODESPLIT] private static String getValueFromThreddsConfig ( String key , String alternateKey , String defaultValue ) { String value = ThreddsConfig . get ( key , null ) ; if ( value == null && alternateKey != null ) value = ThreddsConfig . get ( alternateKey , null ) ; if ( value == null ) value = defaultValue ; return value ; }


Input: read in the index index raf already open ; return null on failure [CODESPLIT] @ Nullable static PartitionCollectionMutable openMutablePCFromIndex ( String name , RandomAccessFile raf , FeatureCollectionConfig config , org . slf4j . Logger logger ) { Grib2PartitionBuilderFromIndex builder = new Grib2PartitionBuilderFromIndex ( name , config , logger ) ; if ( builder . readIndex ( raf ) ) return builder . pc ; return null ; }


Input: / * extend GribCollection { repeated Partition partitions = 100 ; required bool isPartitionOfPartitions = 101 ; repeated uint32 run2part = 102 ; // masterRuntime index to partition index } [CODESPLIT] @ Override protected boolean readExtensions ( GribCollectionProto . GribCollection proto ) { pc . isPartitionOfPartitions = proto . getIsPartitionOfPartitions ( ) ; List < Integer > list = proto . getRun2PartList ( ) ; pc . run2part = new int [ list . size ( ) ] ; int count = 0 ; for ( int partno : list ) pc . run2part [ count ++ ] = partno ; List < ucar . nc2 . grib . collection . GribCollectionProto . Partition > partList = proto . getPartitionsList ( ) ; for ( ucar . nc2 . grib . collection . GribCollectionProto . Partition partProto : partList ) makePartition ( partProto ) ; return partList . size ( ) > 0 ; }


Input: / * private boolean IgnoreinRange ( int i ) { WARNING we do not have signed / unsigned info available if ( this . basetype == DataType . ENUM1 && ( i > = Byte . MIN_VALUE || i < = UBYTE_MAX )) return true ; else if ( this . basetype == DataType . ENUM2 && ( i > = Short . MIN_VALUE || i < = USHORT_MAX )) return true ; else if ( this . basetype == DataType . ENUM4 ) // always ok return true ; else return false ; } [CODESPLIT] public String lookupEnumString ( int e ) { String result = map . get ( e ) ; return ( result == null ) ? "Unknown enum value=" + e : result ; }


Input: String representation . [CODESPLIT] public String writeCDL ( boolean strict ) { Formatter out = new Formatter ( ) ; writeCDL ( out , new Indent ( 2 ) , strict ) ; return out . toString ( ) ; }


Input: initialize the stationHelper . [CODESPLIT] @ Override protected StationHelper createStationHelper ( ) throws IOException { // read in all the stations with the "stations" query StationHelper stationHelper = new StationHelper ( ) ; try ( InputStream in = CdmRemote . sendQuery ( null , uri , "req=stations" ) ) { PointStream . MessageType mtype = PointStream . readMagic ( in ) ; if ( mtype != PointStream . MessageType . StationList ) { throw new RuntimeException ( "Station Request: bad response" ) ; } int len = NcStream . readVInt ( in ) ; byte [ ] b = new byte [ len ] ; NcStream . readFully ( in , b ) ; PointStreamProto . StationList stationsp = PointStreamProto . StationList . parseFrom ( b ) ; for ( ucar . nc2 . ft . point . remote . PointStreamProto . Station sp : stationsp . getStationsList ( ) ) { //        Station s = new StationImpl(sp.getId(), sp.getDesc(), sp.getWmoId(), sp.getLat(), sp.getLon(), sp.getAlt()); stationHelper . addStation ( new StationFeatureStream ( null , null ) ) ; // LOOK WRONG } return stationHelper ; } }


Input: StationTimeSeriesFeatureCollection [CODESPLIT] @ Override public StationTimeSeriesFeatureCollection subset ( List < StationFeature > stations ) throws IOException { if ( stations == null ) return this ; //    List<StationFeature> subset = getStationHelper().getStationFeatures(stations); return new Subset ( this , null , null ) ; // LOOK WRONG }


Input: NestedPointFeatureCollection [CODESPLIT] @ Override public PointFeatureCollection flatten ( LatLonRect boundingBox , CalendarDateRange dateRange ) throws IOException { //boolean restrictedList = false; //QueryMaker queryMaker = restrictedList ? new QueryByStationList() : null; PointFeatureCollection pfc = new PointCollectionStreamRemote ( uri , getTimeUnit ( ) , getAltUnits ( ) , null ) ; return pfc . subset ( boundingBox , dateRange ) ; }


Input: Validate this ResultService object . Return true if valid false if invalid . [CODESPLIT] protected boolean validate ( StringBuilder out ) { this . isValid = true ; // If log from construction has content, append to validation output msg. if ( this . log . length ( ) > 0 ) { out . append ( this . log ) ; } // Check that 'accessPointHeader' attribute is not null. if ( this . getAccessPointHeader ( ) == null ) { this . isValid = false ; out . append ( " ** ResultService (1): a null 'accessPointHeader' is invalid." ) ; } return ( this . isValid ) ; }


Input: Convert a LatLonPoint to projection coordinates [CODESPLIT] public ProjectionPoint latLonToProj ( LatLonPoint latLon , ProjectionPointImpl result ) { double toX , toY ; double fromLat = latLon . getLatitude ( ) ; double fromLon = latLon . getLongitude ( ) ; fromLat = Math . toRadians ( fromLat ) ; double lonDiff = Math . toRadians ( LatLonPointImpl . lonNormal ( fromLon - lon0Degrees ) ) ; double g = sinLat0 * Math . sin ( fromLat ) + cosLat0 * Math . cos ( fromLat ) * Math . cos ( lonDiff ) ; double kPrime = Math . sqrt ( 2 / ( 1 + g ) ) ; toX = R * kPrime * Math . cos ( fromLat ) * Math . sin ( lonDiff ) + falseEasting ; toY = R * kPrime * ( cosLat0 * Math . sin ( fromLat ) - sinLat0 * Math . cos ( fromLat ) * Math . cos ( lonDiff ) ) + falseNorthing ; result . setLocation ( toX , toY ) ; return result ; }


Input: Convert lat / lon coordinates to projection coordinates . [CODESPLIT] public float [ ] [ ] latLonToProj ( float [ ] [ ] from , float [ ] [ ] to , int latIndex , int lonIndex ) { int cnt = from [ 0 ] . length ; float [ ] fromLatA = from [ latIndex ] ; float [ ] fromLonA = from [ lonIndex ] ; float [ ] resultXA = to [ INDEX_X ] ; float [ ] resultYA = to [ INDEX_Y ] ; double toX , toY ; for ( int i = 0 ; i < cnt ; i ++ ) { double fromLat = fromLatA [ i ] ; double fromLon = fromLonA [ i ] ; fromLat = Math . toRadians ( fromLat ) ; double lonDiff = Math . toRadians ( LatLonPointImpl . lonNormal ( fromLon - lon0Degrees ) ) ; double g = sinLat0 * Math . sin ( fromLat ) + cosLat0 * Math . cos ( fromLat ) * Math . cos ( lonDiff ) ; double kPrime = Math . sqrt ( 2 / ( 1 + g ) ) ; toX = R * kPrime * Math . cos ( fromLat ) * Math . sin ( lonDiff ) + falseEasting ; toY = R * kPrime * ( cosLat0 * Math . sin ( fromLat ) - sinLat0 * Math . cos ( fromLat ) * Math . cos ( lonDiff ) ) + falseNorthing ; resultXA [ i ] = ( float ) toX ; resultYA [ i ] = ( float ) toY ; } return to ; }


Input:
Convert lat / lon coordinates to projection coordinates . [CODESPLIT] public float [ ] [ ] projToLatLon ( float [ ] [ ] from , float [ ] [ ] to ) { int cnt = from [ 0 ] . length ; float [ ] fromXA = from [ INDEX_X ] ; float [ ] fromYA = from [ INDEX_Y ] ; float [ ] toLatA = to [ INDEX_LAT ] ; float [ ] toLonA = to [ INDEX_LON ] ; double toLat , toLon ; for ( int i = 0 ; i < cnt ; i ++ ) { double fromX = fromXA [ i ] ; double fromY = fromYA [ i ] ; fromX = fromX - falseEasting ; fromY = fromY - falseNorthing ; double rho = Math . sqrt ( fromX * fromX + fromY * fromY ) ; double c = 2 * Math . asin ( rho / ( 2 * R ) ) ; toLon = lon0 ; double temp = 0 ; if ( Math . abs ( rho ) > TOLERANCE ) { toLat = Math . asin ( Math . cos ( c ) * sinLat0 + ( fromY * Math . sin ( c ) * cosLat0 / rho ) ) ; if ( Math . abs ( lat0 - PI_OVER_4 ) > TOLERANCE ) { // not 90 or -90
 temp = rho * cosLat0 * Math . cos ( c ) - fromY * sinLat0 * Math . sin ( c ) ; toLon = lon0 + Math . atan ( fromX * Math . sin ( c ) / temp ) ; } else if ( Double . compare ( lat0 , PI_OVER_4 ) == 0 ) { toLon = lon0 + Math . atan ( fromX / - fromY ) ; temp = - fromY ; } else { toLon = lon0 + Math . atan ( fromX / fromY ) ; temp = fromY ; } } else { toLat = lat0 ; } toLat = Math . toDegrees ( toLat ) ; toLon = Math . toDegrees ( toLon ) ; if ( temp < 0 ) { toLon += 180 ; } toLon = LatLonPointImpl . lonNormal ( toLon ) ; toLatA [ i ] = ( float ) toLat ; toLonA [ i ] = ( float ) toLon ; } return to ; }


Input: Get the azimuth in degrees [CODESPLIT] public float getAzimuth ( ) { if ( message_type != 1 ) return - 1.0f ; if ( Cinrad2IOServiceProvider . isSC ) return 360.0f * azimuth_ang / 65536.0f ; else if ( Cinrad2IOServiceProvider . isCC ) return 360.0f * azimuth_ang / 512.0f ; else if ( Cinrad2IOServiceProvider . isCC20 ) return azimuth_ang * 0.01f ; return 180.0f * azimuth_ang / 32768.0f ; }


Input: Get the elevation angle in degrees [CODESPLIT] public float getElevation ( ) { if ( message_type != 1 ) return - 1.0f ; if ( Cinrad2IOServiceProvider . isSC ) return 120.0f * elevation_ang / 65536.0f ; else if ( Cinrad2IOServiceProvider . isCC ) return elevation_ang * 0.01f ; else if ( Cinrad2IOServiceProvider . isCC20 ) return elevation_ang * 0.01f ; return 180.0f * elevation_ang / 32768.0f ; }


Input: unidata added [CODESPLIT] public Date [ ] getTimes ( ) { if ( myRYIBs == null ) return null ; Date [ ] times = new Date [ nRays ] ; for ( int i = 0 ; i < nRays ; i ++ ) times [ i ] = myRYIBs [ i ] . getRayTime ( ) ; return times ; }


Input: Get the array of per - ray latitudes . If we do not have per - ray position information null is returned . [CODESPLIT] public float [ ] getLatitudes ( ) { if ( myASIBs == null ) return null ; float [ ] lats = new float [ nRays ] ; for ( int i = 0 ; i < nRays ; i ++ ) lats [ i ] = myASIBs [ i ] . getLatitude ( ) ; return lats ; }


Input: Get the array of per - ray longitudes . If we do not have per - ray position information null is returned . [CODESPLIT] public float [ ] getLongitudes ( ) { if ( myASIBs == null ) return null ; float [ ] lons = new float [ nRays ] ; for ( int i = 0 ; i < nRays ; i ++ ) lons [ i ] = myASIBs [ i ] . getLongitude ( ) ; return lons ; }


Input: Get the array of per - ray altitudes . If we do not have per - ray position information null is returned . [CODESPLIT] public float [ ] getAltitudes ( ) { if ( myASIBs == null ) return null ; float [ ] alts = new float [ nRays ] ; for ( int i = 0 ; i < nRays ; i ++ ) alts [ i ] = myASIBs [ i ] . getAltitude ( ) ; return alts ; }


Input: Get the array of azimuths for this sweep . [CODESPLIT] public float [ ] getAzimuths ( ) { if ( azimuths == null ) { azimuths = new float [ nRays ] ; for ( int r = 0 ; r < nRays ; r ++ ) { azimuths [ r ] = myRYIBs [ r ] . getAzimuth ( ) ; } } return azimuths ; }


Input: Get the array of elevations for this sweep . [CODESPLIT] public float [ ] getElevations ( ) { if ( elevations == null ) { elevations = new float [ nRays ] ; for ( int r = 0 ; r < nRays ; r ++ ) { elevations [ r ] = myRYIBs [ r ] . getElevation ( ) ; } } return elevations ; }


Input: Create a subset of the Structure consisting only of the given member variables [CODESPLIT] public Structure select ( List < String > memberNames ) { Structure result = ( Structure ) copy ( ) ; List < Variable > members = new ArrayList <> ( ) ; for ( String name : memberNames ) { Variable m = findVariable ( name ) ; if ( null != m ) members . add ( m ) ; } result . setMemberVariables ( members ) ; result . isSubset = true ; return result ; }


Input: Create a subset of the Structure consisting only of the one member variable [CODESPLIT] public Structure select ( String varName ) { List < String > memberNames = new ArrayList <> ( 1 ) ; memberNames . add ( varName ) ; return select ( memberNames ) ; }


Input: Add a member variable [CODESPLIT] public Variable addMemberVariable ( Variable v ) { if ( isImmutable ( ) ) throw new IllegalStateException ( "Cant modify" ) ; members . add ( v ) ; memberHash . put ( v . getShortName ( ) , v ) ; v . setParentStructure ( this ) ; return v ; }


Input: Set the list of member variables . [CODESPLIT] public void setMemberVariables ( List < Variable > vars ) { if ( isImmutable ( ) ) throw new IllegalStateException ( "Cant modify" ) ; members = new ArrayList <> ( ) ; memberHash = new HashMap <> ( 2 * vars . size ( ) ) ; for ( Variable v : vars ) { addMemberVariable ( v ) ; } }


Input: Remove a Variable : uses the Variable name to find it . [CODESPLIT] public boolean removeMemberVariable ( Variable v ) { if ( isImmutable ( ) ) throw new IllegalStateException ( "Cant modify" ) ; if ( v == null ) return false ; //smembers = null; java . util . Iterator < Variable > iter = members . iterator ( ) ; while ( iter . hasNext ( ) ) { Variable mv = iter . next ( ) ; if ( mv . getShortName ( ) . equals ( v . getShortName ( ) ) ) { iter . remove ( ) ; memberHash . remove ( v . getShortName ( ) ) ; return true ; } } return false ; }


Input: Replace a Variable with another that has the same name : uses the variable name to find it . If old Var is not found just add the new one [CODESPLIT] public boolean replaceMemberVariable ( Variable newVar ) { if ( isImmutable ( ) ) throw new IllegalStateException ( "Cant modify" ) ; //smembers = null; boolean found = false ; for ( int i = 0 ; i < members . size ( ) ; i ++ ) { Variable v = members . get ( i ) ; if ( v . getShortName ( ) == null ) System . out . println ( "BAD null short name" ) ; // E:/work/ghansham/iasi_20110513_045057_metopa_23676_eps_o.l1_bufr if ( v . getShortName ( ) . equals ( newVar . getShortName ( ) ) ) { members . set ( i , newVar ) ; found = true ; } } if ( ! found ) members . add ( newVar ) ; return found ; }


Input: Set the parent group of this Structure and all member variables . [CODESPLIT] @ Override public void setParentGroup ( Group group ) { if ( isImmutable ( ) ) throw new IllegalStateException ( "Cant modify" ) ; super . setParentGroup ( group ) ; if ( members != null ) { for ( Variable v : members ) { v . setParentGroup ( group ) ; } } }


Input: Find the Variable member with the specified ( short ) name . [CODESPLIT] public Variable findVariable ( String shortName ) { if ( shortName == null ) return null ; return memberHash . get ( shortName ) ; }


Input: Create a StructureMembers object that describes this Structure . CAUTION : Do not use for iterating over a StructureData or ArrayStructure - get the StructureMembers object directly from the StructureData or ArrayStructure . [CODESPLIT] public StructureMembers makeStructureMembers ( ) { StructureMembers smembers = new StructureMembers ( getShortName ( ) ) ; for ( Variable v2 : getVariables ( ) ) { StructureMembers . Member m = smembers . addMember ( v2 . getShortName ( ) , v2 . getDescription ( ) , v2 . getUnitsString ( ) , v2 . getDataType ( ) , v2 . getShape ( ) ) ; if ( v2 instanceof Structure ) m . setStructureMembers ( ( ( Structure ) v2 ) . makeStructureMembers ( ) ) ; } return smembers ; }


Input: Force recalculation of size of one element of this structure - equals the sum of sizes of its members . This is used only by low level classes like IOSPs . [CODESPLIT] public void calcElementSize ( ) { int total = 0 ; for ( Variable v : members ) { total += v . getElementSize ( ) * v . getSize ( ) ; } elementSize = total ; }


Input: Use this when this is a scalar Structure . Its the same as read () but it extracts the single StructureData out of the Array . [CODESPLIT] public StructureData readStructure ( ) throws IOException { if ( getRank ( ) != 0 ) throw new java . lang . UnsupportedOperationException ( "not a scalar structure" ) ; Array dataArray = read ( ) ; ArrayStructure data = ( ArrayStructure ) dataArray ; return data . getStructureData ( 0 ) ; }


Input: Use this when this is a one dimensional array of Structures or you are doing the index calculation yourself for a multidimension array . This will read only the ith structure and return the data as a StructureData object . [CODESPLIT] public StructureData readStructure ( int index ) throws IOException , ucar . ma2 . InvalidRangeException { Section section = null ; // works for scalars i think if ( getRank ( ) == 1 ) { section = new Section ( ) . appendRange ( index , index ) ; } else if ( getRank ( ) > 1 ) { Index ii = Index . factory ( shape ) ; // convert to nD index ii . setCurrentCounter ( index ) ; int [ ] origin = ii . getCurrentCounter ( ) ; section = new Section ( ) ; for ( int anOrigin : origin ) section . appendRange ( anOrigin , anOrigin ) ; } Array dataArray = read ( section ) ; ArrayStructure data = ( ArrayStructure ) dataArray ; return data . getStructureData ( 0 ) ; }


Input: For rank 1 array of Structures read count Structures and return the data as an ArrayStructure . Use only when this is a one dimensional array of Structures . [CODESPLIT] public ArrayStructure readStructure ( int start , int count ) throws IOException , ucar . ma2 . InvalidRangeException { if ( getRank ( ) != 1 ) throw new java . lang . UnsupportedOperationException ( "not a vector structure" ) ; int [ ] origin = new int [ ] { start } ; int [ ] shape = new int [ ] { count } ; if ( NetcdfFile . debugStructureIterator ) System . out . println ( "readStructure " + start + " " + count ) ; return ( ArrayStructure ) read ( origin , shape ) ; }


Input: Get an efficient iterator over all the data in the Structure . [CODESPLIT] public StructureDataIterator getStructureIterator ( int bufferSize ) throws java . io . IOException { return ( getRank ( ) < 2 ) ? new Structure . IteratorRank1 ( bufferSize ) : new Structure . Iterator ( bufferSize ) ; }


Input: Get String with name and attributes . Used in short descriptions like tooltips . [CODESPLIT] public String getNameAndAttributes ( ) { Formatter sbuff = new Formatter ( ) ; sbuff . format ( "Structure " ) ; getNameAndDimensions ( sbuff , false , true ) ; sbuff . format ( "%n" ) ; for ( Attribute att : attributes . getAttributes ( ) ) { sbuff . format ( "  %s:%s;%n" , getShortName ( ) , att . toString ( ) ) ; } return sbuff . toString ( ) ; }


Input: / * <BUFR_19_1_1_TableA_en > <No > 27< / No > <CodeFigure > 28< / CodeFigure > <Meaning_en > Precision orbit ( satellite ) < / Meaning_en > <Status > Operational< / Status > < / BUFR_19_1_1_TableA_en > [CODESPLIT] static private void init ( ) { String filename = BufrTables . RESOURCE_PATH + TABLEA_FILENAME ; try ( InputStream is = CodeFlagTables . class . getResourceAsStream ( filename ) ) { HashMap < Integer , String > map = new HashMap <> ( 100 ) ; SAXBuilder builder = new SAXBuilder ( ) ; org . jdom2 . Document tdoc = builder . build ( is ) ; org . jdom2 . Element root = tdoc . getRootElement ( ) ; List < Element > elems = root . getChildren ( ) ; for ( Element elem : elems ) { String line = elem . getChildText ( "No" ) ; String codeS = elem . getChildText ( "CodeFigure" ) ; String desc = elem . getChildText ( "Meaning_en" ) ; try { int code = Integer . parseInt ( codeS ) ; map . put ( code , desc ) ; } catch ( NumberFormatException e ) { log . debug ( "NumberFormatException on line " + line + " in " + codeS ) ; } } tableA = map ; } catch ( Exception e ) { log . error ( "Can't read BUFR code table " + filename , e ) ; } }


Input: data category name from table A [CODESPLIT] static public String getDataCategory ( int cat ) { if ( tableA == null ) init ( ) ; String result = tableA . get ( cat ) ; return result != null ? result : "Unknown category=" + cat ; }


Input: Get the name of the type of the projection . [CODESPLIT] public String getClassName ( ) { String className = getClass ( ) . getName ( ) ; int index = className . lastIndexOf ( "." ) ; if ( index >= 0 ) { className = className . substring ( index + 1 ) ; } return className ; }


Input: Add an attribute to this projection [CODESPLIT] protected void addParameter ( String name , String value ) { atts . add ( new Parameter ( name , value ) ) ; }


Input: Get a header for display . [CODESPLIT] public static String getHeader ( ) { StringBuilder headerB = new StringBuilder ( 60 ) ; headerB . append ( "Name" ) ; Format . tab ( headerB , 20 , true ) ; headerB . append ( "Class" ) ; Format . tab ( headerB , 40 , true ) ; headerB . append ( "Parameters" ) ; return headerB . toString ( ) ; }


Input: Convert projection coordinates to lat / lon coordinate . [CODESPLIT] public double [ ] [ ] projToLatLon ( double [ ] [ ] from , double [ ] [ ] to ) { if ( ( from == null ) || ( from . length != 2 ) ) { throw new IllegalArgumentException ( "ProjectionImpl.projToLatLon:" + "null array argument or wrong dimension (from)" ) ; } if ( ( to == null ) || ( to . length != 2 ) ) { throw new IllegalArgumentException ( "ProjectionImpl.projToLatLon:" + "null array argument or wrong dimension (to)" ) ; } if ( from [ 0 ] . length != to [ 0 ] . length ) { throw new IllegalArgumentException ( "ProjectionImpl.projToLatLon:" + "from array not same length as to array" ) ; } for ( int i = 0 ; i < from [ 0 ] . length ; i ++ ) { LatLonPoint endL = projToLatLon ( from [ 0 ] [ i ] , from [ 1 ] [ i ] ) ; to [ 0 ] [ i ] = endL . getLatitude ( ) ; to [ 1 ] [ i ] = endL . getLongitude ( ) ; } return to ; }


Input: Convert projection coordinates to lat / lon coordinate . [CODESPLIT] public float [ ] [ ] projToLatLon ( float [ ] [ ] from , float [ ] [ ] to ) { if ( ( from == null ) || ( from . length != 2 ) ) { throw new IllegalArgumentException ( "ProjectionImpl.projToLatLon:" + "null array argument or wrong dimension (from)" ) ; } if ( ( to == null ) || ( to . length != 2 ) ) { throw new IllegalArgumentException ( "ProjectionImpl.projToLatLon:" + "null array argument or wrong dimension (to)" ) ; } if ( from [ 0 ] . length != to [ 0 ] . length ) { throw new IllegalArgumentException ( "ProjectionImpl.projToLatLon:" + "from array not same length as to array" ) ; } ProjectionPointImpl ppi = new ProjectionPointImpl ( ) ; LatLonPointImpl llpi = new LatLonPointImpl ( ) ; for ( int i = 0 ; i < from [ 0 ] . length ; i ++ ) { ppi . setLocation ( ( double ) from [ 0 ] [ i ] , ( double ) from [ 1 ] [ i ] ) ; projToLatLon ( ppi , llpi ) ; to [ 0 ] [ i ] = ( float ) llpi . getLatitude ( ) ; to [ 1 ] [ i ] = ( float ) llpi . getLongitude ( ) ; } return to ; }


Input: Convert lat / lon coordinates to projection coordinates . [CODESPLIT] public float [ ] [ ] latLonToProj ( float [ ] [ ] from , int latIndex , int lonIndex ) { return latLonToProj ( from , new float [ 2 ] [ from [ 0 ] . length ] , latIndex , lonIndex ) ; }


Input:
Convert lat / lon coordinates to projection coordinates . [CODESPLIT] public float [ ] [ ] latLonToProj ( float [ ] [ ] from , float [ ] [ ] to , int latIndex , int lonIndex ) { //      ucar.unidata.util.Misc.printStack ("latLonToProj-" + this + " size=" + from[0].length, 4, null);
 if ( ( from == null ) || ( from . length != 2 ) ) { throw new IllegalArgumentException ( "ProjectionImpl.latLonToProj:" + "null array argument or wrong dimension (from)" ) ; } if ( ( to == null ) || ( to . length != 2 ) ) { throw new IllegalArgumentException ( "ProjectionImpl.latLonToProj:" + "null array argument or wrong dimension (to)" ) ; } if ( from [ 0 ] . length != to [ 0 ] . length ) { throw new IllegalArgumentException ( "ProjectionImpl.latLonToProj:" + "from array not same length as to array" ) ; } ProjectionPointImpl ppi = new ProjectionPointImpl ( ) ; LatLonPointImpl llpi = new LatLonPointImpl ( ) ; for ( int i = 0 ; i < from [ 0 ] . length ; i ++ ) { llpi . setLatitude ( from [ latIndex ] [ i ] ) ; llpi . setLongitude ( from [ lonIndex ] [ i ] ) ; latLonToProj ( llpi , ppi ) ; to [ 0 ] [ i ] = ( float ) ppi . getX ( ) ; to [ 1 ] [ i ] = ( float ) ppi . getY ( ) ; } return to ; }


Input: Alternate way to calculate latLonToProjBB originally in GridCoordSys . Difficult to do this in a general way . [CODESPLIT] ProjectionRect latLonToProjBB2 ( LatLonRect latlonRect ) { double minx , maxx , miny , maxy ; LatLonPointImpl llpt = latlonRect . getLowerLeftPoint ( ) ; LatLonPointImpl urpt = latlonRect . getUpperRightPoint ( ) ; LatLonPointImpl lrpt = latlonRect . getLowerRightPoint ( ) ; LatLonPointImpl ulpt = latlonRect . getUpperLeftPoint ( ) ; if ( isLatLon ( ) ) { minx = getMinOrMaxLon ( llpt . getLongitude ( ) , ulpt . getLongitude ( ) , true ) ; miny = Math . min ( llpt . getLatitude ( ) , lrpt . getLatitude ( ) ) ; maxx = getMinOrMaxLon ( urpt . getLongitude ( ) , lrpt . getLongitude ( ) , false ) ; maxy = Math . min ( ulpt . getLatitude ( ) , urpt . getLatitude ( ) ) ; } else { ProjectionPoint ll = latLonToProj ( llpt , new ProjectionPointImpl ( ) ) ; ProjectionPoint ur = latLonToProj ( urpt , new ProjectionPointImpl ( ) ) ; ProjectionPoint lr = latLonToProj ( lrpt , new ProjectionPointImpl ( ) ) ; ProjectionPoint ul = latLonToProj ( ulpt , new ProjectionPointImpl ( ) ) ; minx = Math . min ( ll . getX ( ) , ul . getX ( ) ) ; miny = Math . min ( ll . getY ( ) , lr . getY ( ) ) ; maxx = Math . max ( ur . getX ( ) , lr . getX ( ) ) ; maxy = Math . max ( ul . getY ( ) , ur . getY ( ) ) ; } return new ProjectionRect ( minx , miny , maxx , maxy ) ; }


Input:
Convert a lat / lon bounding box to a world coordinate bounding box by finding the minimum enclosing box . Handles lat / lon points that do not intersect the projection panel . [CODESPLIT] public ProjectionRect latLonToProjBB ( LatLonRect latlonRect ) { if ( isLatLon ) { LatLonProjection llp = ( LatLonProjection ) this ; llp . setCenterLon ( latlonRect . getCenterLon ( ) ) ; // LOOK side effect BAD !!
 } ProjectionPointImpl w1 = new ProjectionPointImpl ( ) ; ProjectionPointImpl w2 = new ProjectionPointImpl ( ) ; LatLonPoint ll = latlonRect . getLowerLeftPoint ( ) ; LatLonPoint ur = latlonRect . getUpperRightPoint ( ) ; latLonToProj ( ll , w1 ) ; latLonToProj ( ur , w2 ) ; //if (!isLatLon && crossSeam(w1, w2)) {
 //  log.warn("CROSS SEAM failure=" + w1 + " " + w2+" for "+this, new Throwable());
 //}
 // make bounding box out of those two corners
 ProjectionRect world = new ProjectionRect ( w1 . getX ( ) , w1 . getY ( ) , w2 . getX ( ) , w2 . getY ( ) ) ; LatLonPointImpl la = new LatLonPointImpl ( ) ; LatLonPointImpl lb = new LatLonPointImpl ( ) ; // now extend if needed to the other two corners
 la . setLatitude ( ur . getLatitude ( ) ) ; la . setLongitude ( ll . getLongitude ( ) ) ; latLonToProj ( la , w1 ) ; world . add ( w1 ) ; lb . setLatitude ( ll . getLatitude ( ) ) ; lb . setLongitude ( ur . getLongitude ( ) ) ; latLonToProj ( lb , w2 ) ; world . add ( w2 ) ; return world ; }


Input:
Convert a world coordinate bounding box to a lat / lon bounding box by finding the minimum enclosing box . [CODESPLIT] public LatLonRect projToLatLonBBold ( ProjectionRect world ) { //System.out.println("world = " + world);
 ProjectionPoint min = world . getMinPoint ( ) ; ProjectionPoint max = world . getMaxPoint ( ) ; //System.out.println("min = " + min);
 //System.out.println("max = " + max);
 LatLonRect llbb ; LatLonPointImpl llmin = new LatLonPointImpl ( ) ; LatLonPointImpl llmax = new LatLonPointImpl ( ) ; // make bounding box out of the min, max corners
 projToLatLon ( min , llmin ) ; projToLatLon ( max , llmax ) ; llbb = new LatLonRect ( llmin , llmax ) ; //System.out.println("llbb = " + llbb);
 /*
   double lona = la.getLongitude();
   double lonb = lb.getLongitude();

   if (((lona < lonb) && (lonb - lona <= 180.0))
           || ((lona > lonb) && (lona - lonb >= 180.0))) {
       llbb = new LatLonRect(la, lb);
   } else {
       llbb = new LatLonRect(lb, la);
   } */ ProjectionPointImpl w1 = new ProjectionPointImpl ( ) ; ProjectionPointImpl w2 = new ProjectionPointImpl ( ) ; // now extend if needed using the other two corners
 w1 . setLocation ( min . getX ( ) , max . getY ( ) ) ; projToLatLon ( w1 , llmin ) ; llbb . extend ( llmin ) ; w2 . setLocation ( max . getX ( ) , min . getY ( ) ) ; projToLatLon ( w2 , llmax ) ; llbb . extend ( llmax ) ; return llbb ; }


Input:
Compute lat / lon bounding box from projection bounding box by finding the minimum enclosing box . [CODESPLIT] public LatLonRect projToLatLonBB ( ProjectionRect bb ) { // look at all 4 corners of the bounding box
 LatLonPoint llpt = projToLatLon ( bb . getLowerLeftPoint ( ) , new LatLonPointImpl ( ) ) ; LatLonPoint lrpt = projToLatLon ( bb . getLowerRightPoint ( ) , new LatLonPointImpl ( ) ) ; LatLonPoint urpt = projToLatLon ( bb . getUpperRightPoint ( ) , new LatLonPointImpl ( ) ) ; LatLonPoint ulpt = projToLatLon ( bb . getUpperLeftPoint ( ) , new LatLonPointImpl ( ) ) ; // Check if grid contains poles.
 boolean includesNorthPole = false ; /* int[] resultNP;
    findXYindexFromLatLon(90.0, 0, resultNP);
    if (resultNP[0] != -1 && resultNP[1] != -1)
      includesNorthPole = true;      */ boolean includesSouthPole = false ; /* int[] resultSP = new int[2];
    findXYindexFromLatLon(-90.0, 0, resultSP);
    if (resultSP[0] != -1 && resultSP[1] != -1)
      includesSouthPole = true; */ LatLonRect llbb ; if ( includesNorthPole && ! includesSouthPole ) { llbb = new LatLonRect ( llpt , new LatLonPointImpl ( 90.0 , 0.0 ) ) ; // ??? lon=???
 llbb . extend ( lrpt ) ; llbb . extend ( urpt ) ; llbb . extend ( ulpt ) ; // OR
 //llbb.extend( new LatLonRect( llpt, lrpt ));
 //llbb.extend( new LatLonRect( lrpt, urpt ) );
 //llbb.extend( new LatLonRect( urpt, ulpt ) );
 //llbb.extend( new LatLonRect( ulpt, llpt ) );
 } else if ( includesSouthPole && ! includesNorthPole ) { llbb = new LatLonRect ( llpt , new LatLonPointImpl ( - 90.0 , - 180.0 ) ) ; // ??? lon=???
 llbb . extend ( lrpt ) ; llbb . extend ( urpt ) ; llbb . extend ( ulpt ) ; } else { double latMin = Math . min ( llpt . getLatitude ( ) , lrpt . getLatitude ( ) ) ; double latMax = Math . max ( ulpt . getLatitude ( ) , urpt . getLatitude ( ) ) ; // longitude is a bit tricky as usual
 double lonMin = getMinOrMaxLon ( llpt . getLongitude ( ) , ulpt . getLongitude ( ) , true ) ; double lonMax = getMinOrMaxLon ( lrpt . getLongitude ( ) , urpt . getLongitude ( ) , false ) ; LatLonPointImpl min = new LatLonPointImpl ( latMin , lonMin ) ; LatLonPointImpl max = new LatLonPointImpl ( latMax , lonMax ) ; llbb = new LatLonRect ( min , max ) ; } return llbb ; }


Input: For negative angles d should be negative m & s positive . [CODESPLIT] public static double dmsToRad ( double d , double m , double s ) { if ( d >= 0 ) return ( d + m / 60 + s / 3600 ) * Math . PI / 180.0 ; return ( d - m / 60 - s / 3600 ) * Math . PI / 180.0 ; }


Input: For negative angles d should be negative m & s positive . [CODESPLIT] public static double dmsToDeg ( double d , double m , double s ) { if ( d >= 0 ) return ( d + m / 60 + s / 3600 ) ; return ( d - m / 60 - s / 3600 ) ; }


Input: / * public static void latLongToXYZ ( ProjectionPoint ll Point3D xyz ) { double c = Math . cos ( ll . y ) ; xyz . x = c * Math . cos ( ll . x ) ; xyz . y = c * Math . sin ( ll . x ) ; xyz . z = Math . sin ( ll . y ) ; } [CODESPLIT] public static double greatCircleDistance ( double lon1 , double lat1 , double lon2 , double lat2 ) { double dlat = Math . sin ( ( lat2 - lat1 ) / 2 ) ; double dlon = Math . sin ( ( lon2 - lon1 ) / 2 ) ; double r = Math . sqrt ( dlat * dlat + Math . cos ( lat1 ) * Math . cos ( lat2 ) * dlon * dlon ) ; return 2.0 * Math . asin ( r ) ; }


Input: / * Java translation of Nice Numbers for Graph Labels by Paul Heckbert from Graphics Gems Academic Press 1990 [CODESPLIT] public static double niceNumber ( double x , boolean round ) { int expv ; /* exponent of x */ double f ; /* fractional part of x */ double nf ; /* nice, rounded fraction */ expv = ( int ) Math . floor ( Math . log ( x ) / Math . log ( 10 ) ) ; f = x / Math . pow ( 10. , expv ) ; /* between 1 and 10 */ if ( round ) { if ( f < 1.5 ) nf = 1. ; else if ( f < 3. ) nf = 2. ; else if ( f < 7. ) nf = 5. ; else nf = 10. ; } else if ( f <= 1. ) nf = 1. ; else if ( f <= 2. ) nf = 2. ; else if ( f <= 5. ) nf = 5. ; else nf = 10. ; return nf * Math . pow ( 10. , expv ) ; }


Input: shared by all instances [CODESPLIT] protected VertCoordType getLevelType ( int code ) { VertCoordType result = wmoTable3 . get ( code ) ; if ( result == null ) result = new VertCoordType ( code , "unknownLayer" + code , null , "unknownLayer" + code , null , false , false ) ; return result ; }


Input: Get which CF version this is ie CF - 1 . x [CODESPLIT] public static int getVersion ( String hasConvName ) { int result = extractVersion ( hasConvName ) ; if ( result >= 0 ) return result ; List < String > names = breakupConventionNames ( hasConvName ) ; for ( String name : names ) { result = extractVersion ( name ) ; if ( result >= 0 ) return result ; } return - 1 ; }


Input:
Guess the value of ZisPositive based on z axis name and units [CODESPLIT] public static String getZisPositive ( String zaxisName , String vertCoordUnits ) { if ( vertCoordUnits == null ) return CF . POSITIVE_UP ; if ( vertCoordUnits . isEmpty ( ) ) return CF . POSITIVE_UP ; if ( SimpleUnit . isCompatible ( "millibar" , vertCoordUnits ) ) return CF . POSITIVE_DOWN ; if ( SimpleUnit . isCompatible ( "m" , vertCoordUnits ) ) return CF . POSITIVE_UP ; // dunno - make it up
 return CF . POSITIVE_UP ; }


Input:
this is here because it doesnt fit into the 3D array thing . [CODESPLIT] private void makeAtmLnCoordinate ( NetcdfDataset ds , Variable v ) { // get the formula attribute
 String formula = ds . findAttValueIgnoreCase ( v , CF . formula_terms , null ) ; if ( null == formula ) { String msg = " Need attribute 'formula_terms' on Variable " + v . getFullName ( ) + "\n" ; parseInfo . format ( msg ) ; userAdvice . format ( msg ) ; return ; } // parse the formula string
 Variable p0Var = null , levelVar = null ; StringTokenizer stoke = new StringTokenizer ( formula , " :" ) ; while ( stoke . hasMoreTokens ( ) ) { String toke = stoke . nextToken ( ) ; if ( toke . equalsIgnoreCase ( "p0" ) ) { String name = stoke . nextToken ( ) ; p0Var = ds . findVariable ( name ) ; } else if ( toke . equalsIgnoreCase ( "lev" ) ) { String name = stoke . nextToken ( ) ; levelVar = ds . findVariable ( name ) ; } } if ( null == p0Var ) { String msg = " Need p0:varName on Variable " + v . getFullName ( ) + " formula_terms\n" ; parseInfo . format ( msg ) ; userAdvice . format ( msg ) ; return ; } if ( null == levelVar ) { String msg = " Need lev:varName on Variable " + v . getFullName ( ) + " formula_terms\n" ; parseInfo . format ( msg ) ; userAdvice . format ( msg ) ; return ; } String units = ds . findAttValueIgnoreCase ( p0Var , CDM . UNITS , "hPa" ) ; // create the data and the variable
 try { // p(k) = p0 * exp(-lev(k))
 double p0 = p0Var . readScalarDouble ( ) ; Array levelData = levelVar . read ( ) ; Array pressureData = Array . factory ( DataType . DOUBLE , levelData . getShape ( ) ) ; IndexIterator ii = levelData . getIndexIterator ( ) ; IndexIterator iip = pressureData . getIndexIterator ( ) ; while ( ii . hasNext ( ) ) { double val = p0 * Math . exp ( - 1.0 * ii . getDoubleNext ( ) ) ; iip . setDoubleNext ( val ) ; } CoordinateAxis1D p = new CoordinateAxis1D ( ds , null , v . getShortName ( ) + "_pressure" , DataType . DOUBLE , levelVar . getDimensionsString ( ) , units , "Vertical Pressure coordinate synthesized from atmosphere_ln_pressure_coordinate formula" ) ; p . setCachedData ( pressureData , false ) ; p . addAttribute ( new Attribute ( _Coordinate . AxisType , AxisType . Pressure . toString ( ) ) ) ; p . addAttribute ( new Attribute ( _Coordinate . AliasForDimension , p . getDimensionsString ( ) ) ) ; ds . addVariable ( null , p ) ; parseInfo . format ( " added Vertical Pressure coordinate %s from CF-1 %s%n" , p . getFullName ( ) , CF . atmosphere_ln_pressure_coordinate ) ; } catch ( IOException e ) { String msg = " Unable to read variables from " + v . getFullName ( ) + " formula_terms\n" ; parseInfo . format ( msg ) ; userAdvice . format ( msg ) ; } }


Input:
Augment COARDS axis type identification with Standard names ( including dimensionless vertical coordinates ) and CF . AXIS attributes [CODESPLIT] protected AxisType getAxisType ( NetcdfDataset ncDataset , VariableEnhanced v ) { // standard names for unitless vertical coords
 String sname = ncDataset . findAttValueIgnoreCase ( ( Variable ) v , CF . STANDARD_NAME , null ) ; if ( sname != null ) { sname = sname . trim ( ) ; for ( String vertical_coord : vertical_coords ) if ( sname . equalsIgnoreCase ( vertical_coord ) ) return AxisType . GeoZ ; } // COARDS - check units
 AxisType at = super . getAxisType ( ncDataset , v ) ; if ( at != null ) return at ; // standard names for X, Y : bug in CDO putting wrong standard name, so check units first (!)
 if ( sname != null ) { if ( sname . equalsIgnoreCase ( CF . ENSEMBLE ) ) return AxisType . Ensemble ; if ( sname . equalsIgnoreCase ( CF . LATITUDE ) ) return AxisType . Lat ; if ( sname . equalsIgnoreCase ( CF . LONGITUDE ) ) return AxisType . Lon ; if ( sname . equalsIgnoreCase ( CF . PROJECTION_X_COORDINATE ) || sname . equalsIgnoreCase ( CF . GRID_LONGITUDE ) || sname . equalsIgnoreCase ( "rotated_longitude" ) ) return AxisType . GeoX ; if ( sname . equalsIgnoreCase ( CF . PROJECTION_Y_COORDINATE ) || sname . equalsIgnoreCase ( CF . GRID_LATITUDE ) || sname . equalsIgnoreCase ( "rotated_latitude" ) ) return AxisType . GeoY ; if ( sname . equalsIgnoreCase ( CF . TIME_REFERENCE ) ) return AxisType . RunTime ; if ( sname . equalsIgnoreCase ( CF . TIME_OFFSET ) ) return AxisType . TimeOffset ; } // check axis attribute - only for X, Y, Z
 String axis = ncDataset . findAttValueIgnoreCase ( ( Variable ) v , CF . AXIS , null ) ; if ( axis != null ) { axis = axis . trim ( ) ; String unit = v . getUnitsString ( ) ; if ( axis . equalsIgnoreCase ( "X" ) ) { if ( SimpleUnit . isCompatible ( "m" , unit ) ) return AxisType . GeoX ; } else if ( axis . equalsIgnoreCase ( "Y" ) ) { if ( SimpleUnit . isCompatible ( "m" , unit ) ) return AxisType . GeoY ; } else if ( axis . equalsIgnoreCase ( "Z" ) ) { if ( unit == null ) return AxisType . GeoZ ; if ( SimpleUnit . isCompatible ( "m" , unit ) ) return AxisType . Height ; else if ( SimpleUnit . isCompatible ( "mbar" , unit ) ) return AxisType . Pressure ; else return AxisType . GeoZ ; } } if ( avhrr_oiv2 ) { if ( v . getShortName ( ) . equals ( "zlev" ) ) return AxisType . Height ; } try { String units = v . getUnitsString ( ) ; CalendarDateUnit cd = CalendarDateUnit . of ( null , units ) ; if ( cd != null ) return AxisType . Time ; } catch ( Throwable t ) { // ignore
 } return null ; }


Input: remove last file [CODESPLIT] public boolean delete ( ) { if ( nextFile == null ) return false ; fileList . remove ( nextFile ) ; File f = new File ( "C:/tmp/deleted/" + nextFile . getName ( ) ) ; return nextFile . renameTo ( f ) ; }


Input: / * set the Grid [CODESPLIT] public DataState setCoverage ( CoverageCollection coverageDataset , Coverage grid ) { this . dataState = new DataState ( coverageDataset , grid ) ; this . lastGrid = null ; isNewField = true ; return this . dataState ; }


Input: / * Get the data value at this projection ( x y ) point . [CODESPLIT] public String getXYvalueStr ( ProjectionPoint loc ) { if ( ( lastGrid == null ) || ( geodata == null ) ) return "" ; // convert to dataProjection, where x and y are orthogonal if ( ! sameProjection ) { LatLonPoint llpt = drawProjection . projToLatLon ( loc ) ; loc = dataProjection . latLonToProj ( llpt ) ; } // find the grid indexes HorizCoordSys hcs = lastGrid . getCoordSys ( ) . getHorizCoordSys ( ) ; Optional < HorizCoordSys . CoordReturn > opt = hcs . findXYindexFromCoord ( loc . getX ( ) , loc . getY ( ) ) ; // get value, construct the string if ( ! opt . isPresent ( ) ) return opt . getErrorMessage ( ) ; else { HorizCoordSys . CoordReturn cr = opt . get ( ) ; try { Index imaH = geodata . getIndex ( ) ; double dataValue = geodata . getDouble ( imaH . set ( cr . y , cr . x ) ) ; // int wantz = (geocs.getZAxis() == null) ? -1 : lastLevel; return makeXYZvalueStr ( dataValue , cr ) ; } catch ( Exception e ) { return "error " + cr . x + " " + cr . y ; } } }


Input:
/ * get an x y z data volume for the given time private void makeDataVolume ( GridDatatype g int time ) { try { dataVolume = g . readVolumeData ( time ) ; } catch ( java . io . IOException e ) { System . out . println ( Error reading netcdf file + e ) ; dataVolume = null ; } lastGrid = g ; lastTime = time ; lastLevel = - 1 ; // invalidate lastSlice = - 1 ; // invalidate dataVolumeChanged = true ; } [CODESPLIT] private GeoReferencedArray readHSlice ( int level , int time , int ensemble , int runtime ) { /* make sure x, y exists
    CoverageCS gcs = useG.getCoordinateSystem();
    CoordinateAxis xaxis = gcs.getXHorizAxis();
    CoordinateAxis yaxis = gcs.getYHorizAxis();
    if ((xaxis == null) || (yaxis == null))    // doesnt exist
      return null;
    if ((xaxis.getSize() <= 1) || (yaxis.getSize() <= 1)) // LOOK ??
      return null;   */ // make sure we need new one if ( dataState . grid . equals ( lastGrid ) && ( time == lastTime ) && ( level == lastLevel ) && ( horizStride == lastStride ) && ( ensemble == lastEnsemble ) && ( runtime == lastRunTime ) ) return dataH ; // nothing changed // get the data slice //dataH = useG.readDataSlice(runtime, ensemble, time, level, -1, -1); SubsetParams subset = new SubsetParams ( ) ; if ( level >= 0 && dataState . zaxis != null ) { double levelVal = dataState . zaxis . getCoordMidpoint ( level ) ; subset . set ( SubsetParams . vertCoord , levelVal ) ; } if ( time >= 0 && dataState . taxis != null ) { double timeVal = dataState . taxis . getCoordMidpoint ( time ) ; CalendarDate date = dataState . taxis . makeDate ( timeVal ) ; subset . set ( SubsetParams . time , date ) ; } if ( runtime >= 0 && dataState . rtaxis != null ) { double rtimeVal = dataState . rtaxis . getCoordMidpoint ( runtime ) ; CalendarDate date = dataState . rtaxis . makeDate ( rtimeVal ) ; subset . set ( SubsetParams . runtime , date ) ; } if ( ensemble >= 0 && dataState . ensaxis != null ) { double ensVal = dataState . ensaxis . getCoordMidpoint ( ensemble ) ; subset . set ( SubsetParams . ensCoord , ensVal ) ; } if ( horizStride != 1 ) subset . setHorizStride ( horizStride ) ; try { dataH = dataState . grid . readData ( subset ) ; geodata = dataH . getData ( ) . reduce ( ) ; // get rid of n=1 dimensions } catch ( IOException | InvalidRangeException e ) { e . printStackTrace ( ) ; } lastGrid = dataState . grid ; lastTime = time ; lastLevel = level ; lastEnsemble = ensemble ; lastRunTime = runtime ; lastStride = horizStride ; /*
    CoordinateAxis1D zaxis = gcs.getVerticalAxis();
    if ((zaxis == null) || (zaxis.getSize() < 1)) {
      dataH = dataVolume;  // volume is xy plane
    } else {
      dataH = dataVolume.slice(0, level);  // if z exists, always first (logical) dimension
    }

    if (debugArrayShape) {
      System.out.println("Horiz shape = ");
      for (int i = 0; i < dataH.getRank(); i++)
        System.out.println("   shape = " + dataH.getShape()[i]);
    } */ return dataH ; }


Input: set colorscale limits missing data [CODESPLIT] private void setColorScaleParams ( ) { if ( dataMinMaxType == ColorScale . MinMaxType . hold && ! isNewField ) return ; isNewField = false ; GeoReferencedArray dataArr = readHSlice ( wantLevel , wantTime , wantEnsemble , wantRunTime ) ; //else //  dataArr = makeVSlice(stridedGrid, wantSlice, wantTime, wantEnsemble, wantRunTime); if ( dataArr != null ) { MAMath . MinMax minmax = MAMath . getMinMaxSkipMissingData ( dataArr . getData ( ) , dataState . grid ) ; colorScale . setMinMax ( minmax . min , minmax . max ) ; colorScale . setGeoGrid ( dataState . grid ) ; } }


Input: Do the rendering to the given Graphics2D object . [CODESPLIT] public void renderPlanView ( java . awt . Graphics2D g , AffineTransform dFromN ) { if ( ( dataState . grid == null ) || ( colorScale == null ) || ( drawProjection == null ) ) return ; if ( ! drawGrid && ! drawContours ) return ; // no anitaliasing g . setRenderingHint ( RenderingHints . KEY_ANTIALIASING , RenderingHints . VALUE_ANTIALIAS_OFF ) ; dataH = readHSlice ( wantLevel , wantTime , wantEnsemble , wantRunTime ) ; if ( dataH == null ) return ; setColorScaleParams ( ) ; if ( drawGrid ) drawGridHoriz ( g , dataH ) ; //if (drawContours) //  drawContours(g, dataH.transpose(0, 1), dFromN); if ( drawGridLines ) drawGridLines ( g , dataH ) ; if ( drawBB ) drawGridBB ( g , this . dataState . coverageDataset . getLatlonBoundingBox ( ) ) ; }


Input: / * draw using GeneralPath shape private GeneralPath gp = new GeneralPath ( GeneralPath . WIND_EVEN_ODD 5 ) ; private Shape makeShape ( double lon1 double lat1 double lon2 double lat2 ) { gp . reset () ; ProjectionPoint pt = drawProjection . latLonToProj ( lat1 lon1 ) ; gp . moveTo ( ( float ) pt . getX () ( float ) pt . getY () ) ; [CODESPLIT] private void drawGridHorizRegular ( java . awt . Graphics2D g , GeoReferencedArray array ) { int count = 0 ; CoverageCoordSys gsys = array . getCoordSysForData ( ) ; CoverageCoordAxis1D xaxis = ( CoverageCoordAxis1D ) gsys . getXAxis ( ) ; CoverageCoordAxis1D yaxis = ( CoverageCoordAxis1D ) gsys . getYAxis ( ) ; Array data = array . getData ( ) . reduce ( ) ; if ( data . getRank ( ) != 2 ) { System . out . printf ( "drawGridHorizRegular Rank equals %d, must be 2%n" , data . getRank ( ) ) ; return ; } int nx = xaxis . getNcoords ( ) ; int ny = yaxis . getNcoords ( ) ; //// drawing optimizations sameProjection = drawProjection . equals ( dataProjection ) ; if ( drawProjection . isLatLon ( ) ) { projectll = ( LatLonProjection ) drawProjection ; double centerLon = projectll . getCenterLon ( ) ; if ( Debug . isSet ( "projection/LatLonShift" ) ) System . out . println ( "projection/LatLonShift: gridDraw = " + centerLon ) ; } // find the most common color and fill the entire area with it colorScale . resetHist ( ) ; IndexIterator iiter = array . getData ( ) . getIndexIterator ( ) ; while ( iiter . hasNext ( ) ) { double val = iiter . getDoubleNext ( ) ; colorScale . getIndexFromValue ( val ) ; // accum in histogram } int modeColor = colorScale . getHistMax ( ) ; if ( debugMiss ) System . out . println ( "mode = " + modeColor + " sameProj= " + sameProjection ) ; if ( sameProjection ) { double xmin = Math . min ( xaxis . getCoordEdge1 ( 0 ) , xaxis . getCoordEdgeLast ( ) ) ; double xmax = Math . max ( xaxis . getCoordEdge1 ( 0 ) , xaxis . getCoordEdgeLast ( ) ) ; double ymin = Math . min ( yaxis . getCoordEdge1 ( 0 ) , yaxis . getCoordEdgeLast ( ) ) ; double ymax = Math . max ( yaxis . getCoordEdge1 ( 0 ) , yaxis . getCoordEdgeLast ( ) ) ; // pre color the drawing area with the most used color count += drawRect ( g , modeColor , xmin , ymin , xmax , ymax , drawProjection . isLatLon ( ) ) ; } else if ( useModeForProjections ) drawPathShape ( g , modeColor , xaxis , yaxis ) ; debugPts = Debug . isSet ( "GridRenderer/showPts" ) ; // draw individual rects with run length Index imaH = data . getIndex ( ) ; for ( int y = 0 ; y < ny ; y ++ ) { double ybeg = yaxis . getCoordEdge1 ( y ) ; double yend = yaxis . getCoordEdge2 ( y ) ; int thisColor , lastColor = 0 ; int run = 0 ; int xbeg = 0 ; for ( int x = 0 ; x < nx ; x ++ ) { double val = data . getDouble ( imaH . set ( y , x ) ) ; thisColor = colorScale . getIndexFromValue ( val ) ; if ( ( run == 0 ) || ( lastColor == thisColor ) ) { // same color - keep running run ++ ; } else { if ( sameProjection ) { if ( lastColor != modeColor ) // dont have to draw these count += drawRect ( g , lastColor , xaxis . getCoordEdge1 ( xbeg ) , ybeg , xaxis . getCoordEdge2 ( x ) , yend , drawProjection . isLatLon ( ) ) ; } else { if ( ! useModeForProjections || ( lastColor != modeColor ) ) // dont have to draw mode count += drawPathRun ( g , lastColor , ybeg , yend , xaxis , xbeg , x - 1 , debugPts ) ; } xbeg = x ; } lastColor = thisColor ; } // get the ones at the end if ( sameProjection ) { if ( lastColor != modeColor ) count += drawRect ( g , lastColor , xaxis . getCoordEdge1 ( xbeg ) , ybeg , xaxis . getCoordEdgeLast ( ) , yend , drawProjection . isLatLon ( ) ) ; } else { if ( ! useModeForProjections || ( lastColor != modeColor ) ) count += drawPathRun ( g , lastColor , ybeg , yend , xaxis , xbeg , nx - 1 , false ) ; // needed ? } // if (debugPts) break; } if ( debugHorizDraw ) System . out . println ( "debugHorizDraw = " + count ) ; }


Input: is this a child of that ? [CODESPLIT] boolean isChildOf ( H5Group that ) { if ( parent == null ) return false ; if ( parent == that ) return true ; return parent . isChildOf ( that ) ; }


Input: Find the MessageType that matches this name . [CODESPLIT] public static MessageType getType ( String name ) { if ( name == null ) return null ; return hash . get ( name ) ; }


Input: Read a message [CODESPLIT] int read ( long filePos , int version , boolean creationOrderPresent , String objectName ) throws IOException { this . start = filePos ; raf . seek ( filePos ) ; if ( debugPos ) { log . debug ( "  --> Message Header starts at =" + raf . getFilePointer ( ) ) ; } if ( version == 1 ) { type = raf . readShort ( ) ; size = DataType . unsignedShortToInt ( raf . readShort ( ) ) ; headerMessageFlags = raf . readByte ( ) ; raf . skipBytes ( 3 ) ; header_length = 8 ; } else { type = ( short ) raf . readByte ( ) ; size = DataType . unsignedShortToInt ( raf . readShort ( ) ) ; //if (size > Short.MAX_VALUE) //  log.debug("HEY"); headerMessageFlags = raf . readByte ( ) ; header_length = 4 ; if ( creationOrderPresent ) { creationOrder = raf . readShort ( ) ; header_length += 2 ; } } mtype = MessageType . getType ( type ) ; if ( debug1 ) { log . debug ( "  -->" + mtype + " messageSize=" + size + " flags = " + Integer . toBinaryString ( headerMessageFlags ) ) ; if ( creationOrderPresent && debugCreationOrder ) { log . debug ( "     creationOrder = " + creationOrder ) ; } } if ( debugPos ) { log . debug ( "  --> Message Data starts at=" + raf . getFilePointer ( ) ) ; } if ( ( headerMessageFlags & 2 ) != 0 ) { // shared messData = getSharedDataObject ( mtype ) . mdt ; // eg a shared datatype, eg enums return header_length + size ; } if ( mtype == MessageType . NIL ) { // 0 // dont do nuttin } else if ( mtype == MessageType . SimpleDataspace ) { // 1 MessageDataspace data = new MessageDataspace ( ) ; data . read ( ) ; messData = data ; } else if ( mtype == MessageType . GroupNew ) { // 2 MessageGroupNew data = new MessageGroupNew ( ) ; data . read ( ) ; messData = data ; } else if ( mtype == MessageType . Datatype ) { // 3 MessageDatatype data = new MessageDatatype ( ) ; data . read ( objectName ) ; messData = data ; } else if ( mtype == MessageType . FillValueOld ) { // 4 MessageFillValueOld data = new MessageFillValueOld ( ) ; data . read ( ) ; messData = data ; } else if ( mtype == MessageType . FillValue ) { // 5 MessageFillValue data = new MessageFillValue ( ) ; data . read ( ) ; messData = data ; } else if ( mtype == MessageType . Link ) { // 6 MessageLink data = new MessageLink ( ) ; data . read ( ) ; messData = data ; } else if ( mtype == MessageType . Layout ) { // 8 MessageLayout data = new MessageLayout ( ) ; data . read ( ) ; messData = data ; } else if ( mtype == MessageType . GroupInfo ) { // 10 MessageGroupInfo data = new MessageGroupInfo ( ) ; data . read ( ) ; messData = data ; } else if ( mtype == MessageType . FilterPipeline ) { // 11 MessageFilter data = new MessageFilter ( ) ; data . read ( ) ; messData = data ; } else if ( mtype == MessageType . Attribute ) { // 12 MessageAttribute data = new MessageAttribute ( ) ; data . read ( raf . getFilePointer ( ) ) ; messData = data ; } else if ( mtype == MessageType . Comment ) { // 13 MessageComment data = new MessageComment ( ) ; data . read ( ) ; messData = data ; } else if ( mtype == MessageType . LastModifiedOld ) { // 14 MessageLastModifiedOld data = new MessageLastModifiedOld ( ) ; data . read ( ) ; messData = data ; } else if ( mtype == MessageType . ObjectHeaderContinuation ) { // 16 MessageContinue data = new MessageContinue ( ) ; data . read ( ) ; messData = data ; } else if ( mtype == MessageType . Group ) { // 17 MessageGroup data = new MessageGroup ( ) ; data . read ( ) ; messData = data ; } else if ( mtype == MessageType . LastModified ) { // 18 MessageLastModified data = new MessageLastModified ( ) ; data . read ( ) ; messData = data ; } else if ( mtype == MessageType . AttributeInfo ) { // 21 MessageAttributeInfo data = new MessageAttributeInfo ( ) ; data . read ( ) ; messData = data ; } else if ( mtype == MessageType . ObjectReferenceCount ) { // 21 MessageObjectReferenceCount data = new MessageObjectReferenceCount ( ) ; data . read ( ) ; messData = data ; } else { log . debug ( "****UNPROCESSED MESSAGE type = " + mtype + " raw = " + type ) ; log . warn ( "SKIP UNPROCESSED MESSAGE type = " + mtype + " raw = " + type ) ; //throw new UnsupportedOperationException("****UNPROCESSED MESSAGE type = " + mtype + " raw = " + type); } return header_length + size ; }


Input: debugging [CODESPLIT] public void showCompression ( Formatter f ) { if ( mtype != H5header . MessageType . AttributeInfo ) { f . format ( "No fractal heap" ) ; return ; } MessageAttributeInfo info = ( MessageAttributeInfo ) messData ; info . showFractalHeap ( f ) ; }


Input: Installs alignment decorators in all of the table s columns . [CODESPLIT] public static void installInAllColumns ( JTable table , int alignment ) { // We don't want to set up completely new cell renderers: rather, we want to use the existing ones but just // change their alignment. for ( int colViewIndex = 0 ; colViewIndex < table . getColumnCount ( ) ; ++ colViewIndex ) { installInOneColumn ( table , colViewIndex , alignment ) ; } }


Input: Installs alignment decorators in the table column at { @code colViewIndex } . [CODESPLIT] public static void installInOneColumn ( JTable table , int colViewIndex , int alignment ) { TableColumn tableColumn = table . getColumnModel ( ) . getColumn ( colViewIndex ) ; TableCellRenderer headerRenderer = tableColumn . getHeaderRenderer ( ) ; if ( headerRenderer == null ) { headerRenderer = table . getTableHeader ( ) . getDefaultRenderer ( ) ; } if ( ! ( headerRenderer instanceof RendererAlignmentDecorator ) ) { // Don't install a redundant decorator. tableColumn . setHeaderRenderer ( new RendererAlignmentDecorator ( headerRenderer , alignment ) ) ; } TableCellRenderer cellRenderer = tableColumn . getCellRenderer ( ) ; if ( cellRenderer == null ) { cellRenderer = table . getDefaultRenderer ( table . getColumnClass ( colViewIndex ) ) ; } if ( ! ( cellRenderer instanceof RendererAlignmentDecorator ) ) { // Don't install a redundant decorator. tableColumn . setCellRenderer ( new RendererAlignmentDecorator ( cellRenderer , alignment ) ) ; } }


Input: Returns the key adding a trailing { @link #S3_DELIMITER delimiter } . Returns { @code null } if the key is { @code null } . [CODESPLIT] public String getKeyWithTrailingDelimiter ( ) { if ( key == null ) { return null ; } else { assert ! key . endsWith ( S3_DELIMITER ) : "Didn't we strip this in the ctor?" ; return key + S3_DELIMITER ; } }


Input: Returns the parent URI of this URI . The determination is completely text - based using the { @link #S3_DELIMITER delimiter } . If the key is { @code null } { @code null } is returned . If it is non - { @code null } but doesn t have a logical parent the returned URI will have a { @code null } key ( but the same bucket ) . For example the parent of { @code s3 : // my - bucket / my - key } ( bucket = my - bucket key = my - key ) will be { @code s3 : // my - bucket } ( bucket == my - bucket key = null ) . [CODESPLIT] public S3URI getParent ( ) { if ( key == null ) { return null ; } int lastDelimPos = key . lastIndexOf ( S3_DELIMITER ) ; if ( lastDelimPos == - 1 ) { return new S3URI ( bucket , null ) ; } else { return new S3URI ( bucket , key . substring ( 0 , lastDelimPos ) ) ; } }


Input: Creates a new URI by resolving the specified path relative to { @code this } . If { @code key == null } the key of the returned URI will simply be { @code relativePath } . [CODESPLIT] public S3URI getChild ( String relativePath ) throws IllegalArgumentException { Preconditions . checkNotNull ( relativePath , "relativePath must be non-null." ) ; if ( relativePath . isEmpty ( ) ) { return this ; } else if ( relativePath . startsWith ( S3_DELIMITER ) ) { throw new IllegalArgumentException ( String . format ( "Path '%s' should be relative but begins with the delimiter string '%s'." , relativePath , S3_DELIMITER ) ) ; } if ( key == null ) { return new S3URI ( bucket , relativePath ) ; } else { return new S3URI ( bucket , key + S3_DELIMITER + relativePath ) ; } }


Input: Gets a temporary file to which the content of the S3Object that this URI points to can be downloaded . The path of the file is { @code $ { java . io . tmpdir } / S3Objects / $ { hashCode () } / $ { getBaseName () }} . This method does not cause the file to be created ; we re just returning a suitable path . [CODESPLIT] public File getTempFile ( ) { // To avoid collisions of files with the same name, create a parent dir named after the S3URI's hashCode(). File parentDir = new File ( S3ObjectTempDir , String . valueOf ( hashCode ( ) ) ) ; return new File ( parentDir , getBaseName ( ) ) ; }


Input: Specify the HMAC api key and secret to be used for authenticated requests [CODESPLIT] public CoinbaseBuilder withApiKey ( String api_key , String api_secret ) { this . api_key = api_key ; this . api_secret = api_secret ; return this ; }


Input: Cross - platform way of finding an executable in the $PATH . [CODESPLIT] static Stream < Path > which ( String program ) { return which ( program , Optional . ofNullable ( System . getenv ( "PATH" ) ) . orElse ( "" ) ) ; }


Input: Create a simple label . Create newlines with \ n . [CODESPLIT] public static Label of ( String value ) { return new Label ( value , false , false , false , false , null , null ) ; }


Input: Create a simple multiline label . [CODESPLIT] public static Label lines ( Justification just , String ... lines ) { final String sep = just == LEFT ? "\\l" : just == RIGHT ? "\\r" : "\n" ; final String value = Stream . of ( lines ) . map ( line -> line + sep ) . collect ( joining ( ) ) ; return new Label ( value , false , false , false , false , null , null ) ; }


Input: Create a HTML label . [CODESPLIT] public static Label html ( String value ) { return new Label ( value , true , false , false , false , null , null ) ; }


Input:
Create a HTML label from markdown . The following patterns are allowed :
 \ n newline ** bold ** * italics * ~~strike through~~ _underlined_ ^overlined^ __subscript__ ^^superscript^^ . [CODESPLIT] public static Label markdown ( String value ) { return html ( replaceMd ( replaceMd ( replaceMd ( replaceMd ( replaceMd ( replaceMd ( replaceMd ( value . replace ( "\n" , "
" ) , "\\*\\*" , "b" ) , "\\*" , "i" ) , "~~" , "s" ) , "__" , "sub" ) , "_" , "u" ) , "\\^\\^" , "sup" ) , "\\^" , "o" ) . replaceAll ( "\\\\([*~_^])" , "$1" ) ) ; }


Input: Create either a simple HTML or markdown label . If the value is not surrounded by < and > a simple Label is created . Otherwise if value contains some HTML tags a HTML label is created . Otherwise a markdown label is created . [CODESPLIT] public static Label raw ( String value ) { final boolean isTagged = value . startsWith ( "<" ) && value . endsWith ( ">" ) ; if ( ! isTagged ) { return of ( value ) ; } final String untagged = value . substring ( 1 , value . length ( ) - 1 ) ; final boolean hasTags = value . contains ( "/>" ) || value . contains ( "</" ) ; return hasTags ? html ( untagged ) : markdown ( untagged ) ; }


Input: Returns the { [CODESPLIT] public static synchronized CoreSocketFactory getInstance ( ) { if ( coreSocketFactory == null ) { logger . info ( "First Cloud SQL connection, generating RSA key pair." ) ; KeyPair keyPair = generateRsaKeyPair ( ) ; CredentialFactory credentialFactory ; if ( System . getProperty ( CredentialFactory . CREDENTIAL_FACTORY_PROPERTY ) != null ) { try { credentialFactory = ( CredentialFactory ) Class . forName ( System . getProperty ( CredentialFactory . CREDENTIAL_FACTORY_PROPERTY ) ) . newInstance ( ) ; } catch ( Exception err ) { throw new RuntimeException ( err ) ; } } else { credentialFactory = new ApplicationDefaultCredentialFactory ( ) ; } Credential credential = credentialFactory . create ( ) ; SQLAdmin adminApi = createAdminApiClient ( credential ) ; coreSocketFactory = new CoreSocketFactory ( new Clock ( ) , keyPair , credential , adminApi , DEFAULT_SERVER_PROXY_PORT ) ; } return coreSocketFactory ; }


Input: Creates a socket representing a connection to a Cloud SQL instance . [CODESPLIT] public Socket connect ( Properties props , String socketPathFormat ) throws IOException { // Gather parameters final String csqlInstanceName = props . getProperty ( CLOUD_SQL_INSTANCE_PROPERTY ) ; final List < String > ipTypes = listIpTypes ( props . getProperty ( "ipTypes" , DEFAULT_IP_TYPES ) ) ; final boolean forceUnixSocket = System . getenv ( "CLOUD_SQL_FORCE_UNIX_SOCKET" ) != null ; // Validate parameters Preconditions . checkArgument ( csqlInstanceName != null , "cloudSqlInstance property not set. Please specify this property in the JDBC URL or the " + "connection Properties with value in form \"project:region:instance\"" ) ; // GAE Standard runtimes provide a connection path at "/cloudsql/<CONNECTION_NAME>" if ( forceUnixSocket || runningOnGaeStandard ( ) ) { logger . info ( String . format ( "Connecting to Cloud SQL instance [%s] via unix socket." , csqlInstanceName ) ) ; UnixSocketAddress socketAddress = new UnixSocketAddress ( new File ( String . format ( socketPathFormat , csqlInstanceName ) ) ) ; return UnixSocketChannel . open ( socketAddress ) . socket ( ) ; } logger . info ( String . format ( "Connecting to Cloud SQL instance [%s] via SSL socket." , csqlInstanceName ) ) ; return getInstance ( ) . createSslSocket ( csqlInstanceName , ipTypes ) ; }


Input: Returns { [CODESPLIT] private boolean runningOnGaeStandard ( ) { // gaeEnv="standard" indicates standard instances String gaeEnv = System . getenv ( "GAE_ENV" ) ; // runEnv="Production" requires to rule out Java 8 emulated environments String runEnv = System . getProperty ( "com.google.appengine.runtime.environment" ) ; // gaeRuntime="java11" in Java 11 environments (no emulated environments) String gaeRuntime = System . getenv ( "GAE_RUNTIME" ) ; return "standard" . equals ( gaeEnv ) && ( "Production" . equals ( runEnv ) || "java11" . equals ( gaeRuntime ) ) ; }


Input: TODO ( berezv ) : separate creating socket and performing connection to make it easier to test [CODESPLIT] @ VisibleForTesting Socket createSslSocket ( String instanceName , List < String > ipTypes ) throws IOException { try { return createAndConfigureSocket ( instanceName , ipTypes , CertificateCaching . USE_CACHE ) ; } catch ( SSLHandshakeException err ) { logger . warning ( String . format ( "SSL handshake failed for Cloud SQL instance [%s], " + "retrying with new certificate.\n%s" , instanceName , Throwables . getStackTraceAsString ( err ) ) ) ; if ( ! forcedRenewRateLimiter . tryAcquire ( ) ) { logger . warning ( String . format ( "Renewing too often, rate limiting certificate renewal for Cloud SQL " + "instance [%s]." , instanceName ) ) ; forcedRenewRateLimiter . acquire ( ) ; } return createAndConfigureSocket ( instanceName , ipTypes , CertificateCaching . BYPASS_CACHE ) ; } }


Input: Converts the string property of IP types to a list by splitting by commas and upper - casing . [CODESPLIT] private static List < String > listIpTypes ( String cloudSqlIpTypes ) { String [ ] rawTypes = cloudSqlIpTypes . split ( "," ) ; ArrayList < String > result = new ArrayList <> ( rawTypes . length ) ; for ( int i = 0 ; i < rawTypes . length ; i ++ ) { if ( rawTypes [ i ] . trim ( ) . equalsIgnoreCase ( "PUBLIC" ) ) { result . add ( i , "PRIMARY" ) ; } else { result . add ( i , rawTypes [ i ] . trim ( ) . toUpperCase ( ) ) ; } } return result ; }


Input: TODO ( berezv ) : synchronize per instance instead of globally [CODESPLIT] @ VisibleForTesting synchronized InstanceSslInfo getInstanceSslInfo ( String instanceConnectionString , CertificateCaching certificateCaching ) { if ( certificateCaching . equals ( CertificateCaching . USE_CACHE ) ) { InstanceLookupResult lookupResult = cache . get ( instanceConnectionString ) ; if ( lookupResult != null ) { if ( ! lookupResult . isSuccessful ( ) && ( clock . now ( ) - lookupResult . getLastFailureMillis ( ) ) < 60 * 1000 ) { logger . warning ( "Re-throwing cached exception due to attempt to refresh instance information too " + "soon after error." ) ; throw lookupResult . getException ( ) . get ( ) ; } else if ( lookupResult . isSuccessful ( ) ) { InstanceSslInfo details = lookupResult . getInstanceSslInfo ( ) . get ( ) ; // Check if the cached certificate is still valid. if ( details != null ) { GregorianCalendar calendar = new GregorianCalendar ( ) ; calendar . setTimeInMillis ( clock . now ( ) ) ; calendar . add ( Calendar . MINUTE , 5 ) ; try { details . getEphemeralCertificate ( ) . checkValidity ( calendar . getTime ( ) ) ; } catch ( CertificateException err ) { logger . info ( String . format ( "Ephemeral certificate for Cloud SQL instance [%s] is about to expire, " + "obtaining new one." , instanceConnectionString ) ) ; details = null ; } } if ( details != null ) { return details ; } } } } String invalidInstanceError = String . format ( "Invalid Cloud SQL instance [%s], expected value in form [project:region:name]." , instanceConnectionString ) ; int beforeNameIndex = instanceConnectionString . lastIndexOf ( ' ' ) ; if ( beforeNameIndex <= 0 ) { throw new IllegalArgumentException ( invalidInstanceError ) ; } int beforeRegionIndex = instanceConnectionString . lastIndexOf ( ' ' , beforeNameIndex - 1 ) ; if ( beforeRegionIndex <= 0 ) { throw new IllegalArgumentException ( invalidInstanceError ) ; } String projectId = instanceConnectionString . substring ( 0 , beforeRegionIndex ) ; String region = instanceConnectionString . substring ( beforeRegionIndex + 1 , beforeNameIndex ) ; String instanceName = instanceConnectionString . substring ( beforeNameIndex + 1 ) ; InstanceLookupResult instanceLookupResult ; InstanceSslInfo details ; try { details = fetchInstanceSslInfo ( instanceConnectionString , projectId , region , instanceName ) ; instanceLookupResult = new InstanceLookupResult ( details ) ; cache . put ( instanceConnectionString , instanceLookupResult ) ; } catch ( RuntimeException err ) { instanceLookupResult = new InstanceLookupResult ( err ) ; cache . put ( instanceConnectionString , instanceLookupResult ) ; throw err ; } return details ; }


Input: Implements the interface for com . mysql . cj . protocol . SocketFactory for mysql - connector - java prior to version 8 . 0 . 13 . This change is required for backwards compatibility . [CODESPLIT] public < T extends Closeable > T connect ( String host , int portNumber , Properties props , int loginTimeout ) throws IOException { @ SuppressWarnings ( "unchecked" ) T socket = ( T ) CoreSocketFactory . getInstance ( ) . connect ( props , CoreSocketFactory . MYSQL_SOCKET_FILE_FORMAT ) ; return socket ; }


Input: Purges an invalid logger from the cache . [CODESPLIT] protected synchronized void purgeLogger ( FluentLogger logger ) { Iterator < Entry < FluentLogger , String > > it = loggers . entrySet ( ) . iterator ( ) ; while ( it . hasNext ( ) ) { if ( it . next ( ) . getKey ( ) == logger ) { it . remove ( ) ; return ; } } }


Input: Compile all sources [CODESPLIT] public Map < String , Class < ? > > compileAll ( ) throws Exception { if ( sourceCodes . size ( ) == 0 ) { throw new CompilationException ( "No source code to compile" ) ; } Collection < SourceCode > compilationUnits = sourceCodes . values ( ) ; CompiledCode [ ] code ; code = new CompiledCode [ compilationUnits . size ( ) ] ; Iterator < SourceCode > iter = compilationUnits . iterator ( ) ; for ( int i = 0 ; i < code . length ; i ++ ) { code [ i ] = new CompiledCode ( iter . next ( ) . getClassName ( ) ) ; } DiagnosticCollector < JavaFileObject > collector = new DiagnosticCollector <> ( ) ; ExtendedStandardJavaFileManager fileManager = new ExtendedStandardJavaFileManager ( javac . getStandardFileManager ( null , null , null ) , classLoader ) ; JavaCompiler . CompilationTask task = javac . getTask ( null , fileManager , collector , options , null , compilationUnits ) ; boolean result = task . call ( ) ; if ( ! result || collector . getDiagnostics ( ) . size ( ) > 0 ) { StringBuffer exceptionMsg = new StringBuffer ( ) ; exceptionMsg . append ( "Unable to compile the source" ) ; boolean hasWarnings = false ; boolean hasErrors = false ; for ( Diagnostic < ? extends JavaFileObject > d : collector . getDiagnostics ( ) ) { switch ( d . getKind ( ) ) { case NOTE : case MANDATORY_WARNING : case WARNING : hasWarnings = true ; break ; case OTHER : case ERROR : default : hasErrors = true ; break ; } exceptionMsg . append ( "\n" ) . append ( "[kind=" ) . append ( d . getKind ( ) ) ; exceptionMsg . append ( ", " ) . append ( "line=" ) . append ( d . getLineNumber ( ) ) ; exceptionMsg . append ( ", " ) . append ( "message=" ) . append ( d . getMessage ( Locale . US ) ) . append ( "]" ) ; } if ( hasWarnings && ! ignoreWarnings || hasErrors ) { throw new CompilationException ( exceptionMsg . toString ( ) ) ; } } Map < String , Class < ? > > classes = new HashMap < String , Class < ? > > ( ) ; for ( String className : sourceCodes . keySet ( ) ) { classes . put ( className , classLoader . loadClass ( className ) ) ; } return classes ; }


Input: Compile single source [CODESPLIT] public Class < ? > compile ( String className , String sourceCode ) throws Exception { return addSource ( className , sourceCode ) . compileAll ( ) . get ( className ) ; }


Input: Add source code to the compiler [CODESPLIT] public InMemoryJavaCompiler addSource ( String className , String sourceCode ) throws Exception { sourceCodes . put ( className , new SourceCode ( className , sourceCode ) ) ; return this ; }


Input: Reads Graphics Control Extension values . [CODESPLIT] private void readGraphicControlExt ( ) { // Block size. read ( ) ; // Packed fields. int packed = read ( ) ; // Disposal method. header . currentFrame . dispose = ( packed & 0x1c ) >> 2 ; if ( header . currentFrame . dispose == 0 ) { // Elect to keep old image if discretionary. header . currentFrame . dispose = 1 ; } header . currentFrame . transparency = ( packed & 1 ) != 0 ; // Delay in milliseconds. int delayInHundredthsOfASecond = readShort ( ) ; // TODO: consider allowing -1 to indicate show forever. if ( delayInHundredthsOfASecond < MIN_FRAME_DELAY ) { delayInHundredthsOfASecond = DEFAULT_FRAME_DELAY ; } header . currentFrame . delay = delayInHundredthsOfASecond * 10 ; // Transparent color index header . currentFrame . transIndex = read ( ) ; // Block terminator read ( ) ; }


Input: Reads next variable length block from input . [CODESPLIT] private int readBlock ( ) { blockSize = read ( ) ; int n = 0 ; if ( blockSize > 0 ) { int count = 0 ; try { while ( n < blockSize ) { count = blockSize - n ; rawData . get ( block , n , count ) ; n += count ; } } catch ( Exception e ) { if ( Log . isLoggable ( TAG , Log . DEBUG ) ) { Log . d ( TAG , "Error Reading Block n: " + n + " count: " + count + " blockSize: " + blockSize , e ) ; } header . status = GifDecoder . STATUS_FORMAT_ERROR ; } } return n ; }


Input: Get the next frame in the animation sequence . [CODESPLIT] synchronized Bitmap getNextFrame ( ) { if ( header . frameCount <= 0 || framePointer < 0 ) { if ( Log . isLoggable ( TAG , Log . DEBUG ) ) { Log . d ( TAG , "unable to decode frame, frameCount=" + header . frameCount + " framePointer=" + framePointer ) ; } status = STATUS_FORMAT_ERROR ; } if ( status == STATUS_FORMAT_ERROR || status == STATUS_OPEN_ERROR ) { if ( Log . isLoggable ( TAG , Log . DEBUG ) ) { Log . d ( TAG , "Unable to decode frame, status=" + status ) ; } return null ; } status = STATUS_OK ; GifFrame currentFrame = header . frames . get ( framePointer ) ; GifFrame previousFrame = null ; int previousIndex = framePointer - 1 ; if ( previousIndex >= 0 ) { previousFrame = header . frames . get ( previousIndex ) ; } // Set the appropriate color table. act = currentFrame . lct != null ? currentFrame . lct : header . gct ; if ( act == null ) { if ( Log . isLoggable ( TAG , Log . DEBUG ) ) { Log . d ( TAG , "No Valid Color Table for frame #" + framePointer ) ; } // No color table defined. status = STATUS_FORMAT_ERROR ; return null ; } // Reset the transparent pixel in the color table if ( currentFrame . transparency ) { // Prepare local copy of color table ("pct = act"), see #1068 System . arraycopy ( act , 0 , pct , 0 , act . length ) ; // Forget about act reference from shared header object, use copied version act = pct ; // Set transparent color if specified. act [ currentFrame . transIndex ] = 0 ; } // Transfer pixel data to image. return setPixels ( currentFrame , previousFrame ) ; }


Input: Creates new frame image from current data ( and previous frames as specified by their disposition codes ) . [CODESPLIT] private Bitmap setPixels ( GifFrame currentFrame , GifFrame previousFrame ) { // Final location of blended pixels. final int [ ] dest = mainScratch ; // clear all pixels when meet first frame if ( previousFrame == null ) { Arrays . fill ( dest , 0 ) ; } // fill in starting image contents based on last image's dispose code if ( previousFrame != null && previousFrame . dispose > DISPOSAL_UNSPECIFIED ) { // We don't need to do anything for DISPOSAL_NONE, if it has the correct pixels so will our // mainScratch and therefore so will our dest array. if ( previousFrame . dispose == DISPOSAL_BACKGROUND ) { // Start with a canvas filled with the background color int c = 0 ; if ( ! currentFrame . transparency ) { c = header . bgColor ; if ( currentFrame . lct != null && header . bgIndex == currentFrame . transIndex ) { c = 0 ; } } else if ( framePointer == 0 ) { // TODO: We should check and see if all individual pixels are replaced. If they are, the // first frame isn't actually transparent. For now, it's simpler and safer to assume // drawing a transparent background means the GIF contains transparency. isFirstFrameTransparent = true ; } fillRect ( dest , previousFrame , c ) ; } else if ( previousFrame . dispose == DISPOSAL_PREVIOUS ) { if ( previousImage == null ) { fillRect ( dest , previousFrame , 0 ) ; } else { // Start with the previous frame int downsampledIH = previousFrame . ih / sampleSize ; int downsampledIY = previousFrame . iy / sampleSize ; int downsampledIW = previousFrame . iw / sampleSize ; int downsampledIX = previousFrame . ix / sampleSize ; int topLeft = downsampledIY * downsampledWidth + downsampledIX ; previousImage . getPixels ( dest , topLeft , downsampledWidth , downsampledIX , downsampledIY , downsampledIW , downsampledIH ) ; } } } // Decode pixels for this frame into the global pixels[] scratch. decodeBitmapData ( currentFrame ) ; int downsampledIH = currentFrame . ih / sampleSize ; int downsampledIY = currentFrame . iy / sampleSize ; int downsampledIW = currentFrame . iw / sampleSize ; int downsampledIX = currentFrame . ix / sampleSize ; // Copy each source line to the appropriate place in the destination. int pass = 1 ; int inc = 8 ; int iline = 0 ; boolean isFirstFrame = framePointer == 0 ; for ( int i = 0 ; i < downsampledIH ; i ++ ) { int line = i ; if ( currentFrame . interlace ) { if ( iline >= downsampledIH ) { pass ++ ; switch ( pass ) { case 2 : iline = 4 ; break ; case 3 : iline = 2 ; inc = 4 ; break ; case 4 : iline = 1 ; inc = 2 ; break ; default : break ; } } line = iline ; iline += inc ; } line += downsampledIY ; if ( line < downsampledHeight ) { int k = line * downsampledWidth ; // Start of line in dest. int dx = k + downsampledIX ; // End of dest line. int dlim = dx + downsampledIW ; if ( k + downsampledWidth < dlim ) { // Past dest edge. dlim = k + downsampledWidth ; } // Start of line in source. int sx = i * sampleSize * currentFrame . iw ; int maxPositionInSource = sx + ( ( dlim - dx ) * sampleSize ) ; while ( dx < dlim ) { // Map color and insert in destination. int averageColor ; if ( sampleSize == 1 ) { int currentColorIndex = ( ( int ) mainPixels [ sx ] ) & 0x000000ff ; averageColor = act [ currentColorIndex ] ; } else { // TODO: This is substantially slower (up to 50ms per frame) than just grabbing the // current color index above, even with a sample size of 1. averageColor = averageColorsNear ( sx , maxPositionInSource , currentFrame . iw ) ; } if ( averageColor != 0 ) { dest [ dx ] = averageColor ; } else if ( ! isFirstFrameTransparent && isFirstFrame ) { isFirstFrameTransparent = true ; } sx += sampleSize ; dx ++ ; } } } // Copy pixels into previous image if ( savePrevious && ( currentFrame . dispose == DISPOSAL_UNSPECIFIED || currentFrame . dispose == DISPOSAL_NONE ) ) { if ( previousImage == null ) { previousImage = getNextBitmap ( ) ; } previousImage . setPixels ( dest , 0 , downsampledWidth , 0 , 0 , downsampledWidth , downsampledHeight ) ; } // Set pixels for current image. Bitmap result = getNextBitmap ( ) ; result . setPixels ( dest , 0 , downsampledWidth , 0 , 0 , downsampledWidth , downsampledHeight ) ; return result ; }


Input: Reads next variable length block from input . [CODESPLIT] private int readBlock ( ) { int blockSize = readByte ( ) ; if ( blockSize > 0 ) { try { if ( block == null ) { block = bitmapProvider . obtainByteArray ( 255 ) ; } final int remaining = workBufferSize - workBufferPosition ; if ( remaining >= blockSize ) { // Block can be read from the current work buffer. System . arraycopy ( workBuffer , workBufferPosition , block , 0 , blockSize ) ; workBufferPosition += blockSize ; } else if ( rawData . remaining ( ) + remaining >= blockSize ) { // Block can be read in two passes. System . arraycopy ( workBuffer , workBufferPosition , block , 0 , remaining ) ; workBufferPosition = workBufferSize ; readChunkIfNeeded ( ) ; final int secondHalfRemaining = blockSize - remaining ; System . arraycopy ( workBuffer , 0 , block , remaining , secondHalfRemaining ) ; workBufferPosition += secondHalfRemaining ; } else { status = STATUS_FORMAT_ERROR ; } } catch ( Exception e ) { Log . w ( TAG , "Error Reading Block" , e ) ; status = STATUS_FORMAT_ERROR ; } } return blockSize ; }


Input: Use this method to initialize the show / hide listeners for the dialog . [CODESPLIT] public static void initDialog ( BooleanProperty openProperty , final Stage parentStage , Supplier < Parent > rootSupplier ) { final Stage dialogStage = new Stage ( StageStyle . UTILITY ) ; dialogStage . initOwner ( parentStage ) ; dialogStage . initModality ( Modality . APPLICATION_MODAL ) ; openProperty . addListener ( ( obs , oldValue , newValue ) -> { if ( newValue ) { // when it is the first time the dialog is made visible (and therefore no scene exists) ... if ( dialogStage . getScene ( ) == null ) { // ... we create a new scene and register it in the stage. Scene dialogScene = new Scene ( rootSupplier . get ( ) ) ; dialogScene . getStylesheets ( ) . add ( "/contacts.css" ) ; dialogStage . setScene ( dialogScene ) ; } else { // ... otherwise we simple bring the dialog to front. dialogStage . toFront ( ) ; } dialogStage . sizeToScene ( ) ; dialogStage . show ( ) ; } else { dialogStage . close ( ) ; } } ) ; // when the user clicks on the close button of the dialog window // we want to set the property to false dialogStage . setOnCloseRequest ( event -> openProperty . set ( false ) ) ; }


Input: Persons in string representation . [CODESPLIT] public SelectableStringList selectablePersonsProperty ( ) { if ( selectablePersons == null ) { selectablePersons = new SelectableItemList <> ( FXCollections . observableArrayList ( repository . getPersons ( ) ) , person -> person . getFirstName ( ) + " " + person . getLastName ( ) ) ; } return selectablePersons ; }


Input: This method is called by the javafx runtime when the application is initialized . See { @link Application#init () } for more details . <p > In this method the initialization of the guice container is done . For this reason this method is marked as final and cannot be overwritten by users . <p > Please use { @link #initMvvmfx () } for your own initialization logic . [CODESPLIT] public final void init ( ) throws Exception { List < Module > modules = new ArrayList <> ( ) ; modules . add ( new MvvmfxModule ( ) ) ; modules . add ( new AbstractModule ( ) { @ Override protected void configure ( ) { bind ( HostServices . class ) . toProvider ( MvvmfxGuiceApplication . this :: getHostServices ) ; bind ( Stage . class ) . toProvider ( ( ) -> primaryStage ) ; bind ( Parameters . class ) . toProvider ( MvvmfxGuiceApplication . this :: getParameters ) ; } } ) ; this . initGuiceModules ( modules ) ; final Injector injector = Guice . createInjector ( modules ) ; MvvmFX . setCustomDependencyInjector ( injector :: getInstance ) ; injector . injectMembers ( this ) ; this . initMvvmfx ( ) ; }


Input: Try to inject the given { @link ResourceBundle } into the given target instance . [CODESPLIT] static void injectResourceBundle ( Object target , ResourceBundle resourceBundle ) { final List < Field > fieldsWithAnnotation = ReflectionUtils . getFieldsWithAnnotation ( target , InjectResourceBundle . class ) ; final boolean notAssignableFieldPresent = fieldsWithAnnotation . stream ( ) . anyMatch ( field -> ! field . getType ( ) . isAssignableFrom ( ResourceBundle . class ) ) ; if ( notAssignableFieldPresent ) { throw new IllegalStateException ( "The class [" + target + "] has at least one field with the annotation @InjectResourceBundle but the field is not of type ResourceBundle." ) ; } // check whether the user has provided any resourceBundle or not if ( resourceBundle == null || resourceBundle . equals ( EMPTY_RESOURCE_BUNDLE ) ) { if ( ! fieldsWithAnnotation . isEmpty ( ) ) { final boolean nonOptionalFieldsPresent = fieldsWithAnnotation . stream ( ) . flatMap ( field -> Arrays . stream ( field . getAnnotationsByType ( InjectResourceBundle . class ) ) ) . anyMatch ( annotation -> ! annotation . optional ( ) ) ; // if all annotated fields are marked as "optional", no exception has to be thrown. if ( nonOptionalFieldsPresent ) { throw new IllegalStateException ( "The class [" + target + "] expects a ResourceBundle to be injected but no ResourceBundle was defined while loading." ) ; } } } else { fieldsWithAnnotation . forEach ( field -> { if ( field . getType ( ) . isAssignableFrom ( ResourceBundle . class ) ) { ReflectionUtils . setField ( field , target , resourceBundle ) ; } else { throw new IllegalStateException ( "The class [" + target + "] has a field with the @InjectResourceBundle annotation but the type of the field doesn't match ResourceBundle" ) ; } } ) ; } }


Input: This method is used to set the clock to a fixed time . This is useful for tests . This way it s possible to create date / time instances with a predictable value for your tests . [CODESPLIT] public static void setFixedClock ( ZonedDateTime zonedDateTime ) { CentralClock . clock = Clock . fixed ( zonedDateTime . toInstant ( ) , ZoneId . systemDefault ( ) ) ; }


Input: Returns the message with the highest priority using the following algorithm : - if there are messages with { @link Severity#ERROR } take the first one . - otherwise if there are messages with { @link Severity#WARNING } take the first one . - otherwise an empty Optional is returned . [CODESPLIT] public Optional < ValidationMessage > getHighestMessage ( ) { final Optional < ValidationMessage > error = getMessages ( ) . stream ( ) . filter ( message -> message . getSeverity ( ) . equals ( Severity . ERROR ) ) . findFirst ( ) ; if ( error . isPresent ( ) ) { return error ; } else { final Optional < ValidationMessage > warning = getMessages ( ) . stream ( ) . filter ( message -> message . getSeverity ( ) . equals ( Severity . WARNING ) ) . findFirst ( ) ; return warning ; } }


Input: Merges the provided ResourceBundle with the global one ( if any ) . [CODESPLIT] public ResourceBundle mergeWithGlobal ( ResourceBundle resourceBundle ) { if ( globalResourceBundle == null ) { if ( resourceBundle == null ) { return EMPTY_RESOURCE_BUNDLE ; } else { return new ResourceBundleWrapper ( resourceBundle ) ; } } else { if ( resourceBundle == null ) { return new ResourceBundleWrapper ( globalResourceBundle ) ; } else { return merge ( resourceBundle , globalResourceBundle ) ; } } }


Input: Merges the list of ResourceBundles with the global one ( if any ) . <p / > The global resourceBundle has a lower priority then the provided ones . If there is the same key defined in the global and in one of the provided resourceBundles the value from the provided resourceBundle will be used . <p / > The order of resourceBundles in the list defines the priority for resourceBundles . ResourceBundles at the start of the list have a <strong > lower< / strong > priority compared to bundles at the end of the list . This means that the last resourceBundle will overwrite values from previous resourceBundles ( including the global resourceBundle ( if any )) . * [CODESPLIT] public ResourceBundle mergeListWithGlobal ( List < ResourceBundle > bundles ) { if ( globalResourceBundle == null ) { if ( bundles == null ) { return EMPTY_RESOURCE_BUNDLE ; } else { return reduce ( bundles ) ; } } else { if ( bundles == null ) { return new ResourceBundleWrapper ( globalResourceBundle ) ; } else { final List < ResourceBundle > resourceBundles = new ArrayList <> ( ) ; resourceBundles . add ( globalResourceBundle ) ; resourceBundles . addAll ( bundles ) ; return reduce ( resourceBundles ) ; } } }


Input: Returns an instance of the given type . When there is a custom injector defined ( See : { @link #setCustomInjector ( javafx . util . Callback ) } ) then this injector is used . Otherwise a new instance of the desired type is created . This is done by a call to { @link Class#newInstance () } which means that all constraints of the newInstance method are also need to be satisfied . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) public < T > T getInstanceOf ( Class < ? extends T > type ) { if ( isCustomInjectorDefined ( ) ) { return ( T ) customInjector . call ( type ) ; } else { try { // use default creation return type . newInstance ( ) ; } catch ( InstantiationException | IllegalAccessException e ) { throw new RuntimeException ( "Can't create instance of type " + type . getName ( ) + ". Make sure that the class has a public no-arg constructor." , e ) ; } } }