idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
138,300
public void start ( float startPercent , long duration , ResultListener < TimerView > finisher ) { // Sanity check input arguments if ( startPercent < 0.0f || startPercent >= 1.0f ) { throw new IllegalArgumentException ( "Invalid starting percent " + startPercent ) ; } if ( duration < 0 ) { throw new IllegalArgumentException ( "Invalid duration " + duration ) ; } // Stop any current processing stop ( ) ; // Record the timer's full duration and effective start time _duration = duration ; // Change the completion percent and make sure the starting // time gets updated on the next tick changeComplete ( startPercent ) ; _start = Long . MIN_VALUE ; // Thank you sir; would you kindly take a chair in the waiting room? _finisher = finisher ; // The warning and completion handlers haven't been triggered yet _warned = false ; _completed = false ; // Start things running _running = true ; }
Start the timer running from the specified percentage complete to expire at the specified time .
203
16
138,301
public void unpause ( ) { // Don't unpause the timer if it wasn't paused to begin with if ( _lastUpdate == Long . MIN_VALUE || _start == Long . MIN_VALUE ) { return ; } // Adjust the starting time when the timer next ticks _processUnpause = true ; // Start things running again _running = true ; }
Unpause the timer .
75
5
138,302
public void changeComplete ( float complete ) { // Store the new state _complete = complete ; // Determine the percentage difference between the "actual" // completion state and the completion amount to render during // the smooth interpolation _renderOffset = _renderComplete - _complete ; // When the timer next ticks, find out when this interpolation // should start _renderOffsetTime = Long . MIN_VALUE ; }
Generate an unexpected change in the timer s completion and set up the necessary details to render interpolation from the old to new states
84
26
138,303
protected void invalidate ( ) { // Schedule the timer's location on screen to get repainted _invalidated = true ; _host . repaint ( _bounds . x , _bounds . y , _bounds . width , _bounds . height ) ; }
Invalidates this view s bounds via the host component .
58
11
138,304
public void checkFrameParticipation ( ) { // Determine whether or not the timer should participate in // media ticks boolean participate = _host . isShowing ( ) ; // Start participating if necessary if ( participate && ! _participating ) { _fmgr . registerFrameParticipant ( this ) ; _participating = true ; } // Stop participating if necessary else if ( ! participate && _participating ) { _fmgr . removeFrameParticipant ( this ) ; _participating = false ; } }
Check that the frame knows about the timer .
105
9
138,305
public static int getTileHash ( int x , int y ) { long seed = ( ( ( x << 2 ) ^ y ) ^ MULTIPLIER ) & MASK ; long hash = ( seed * MULTIPLIER + ADDEND ) & MASK ; return ( int ) ( hash >>> 30 ) ; }
Compute some hash value for randomizing tileset picks based on x and y coordinates .
68
18
138,306
public static ObjectSequence < TimeSeriesCollection > fixSequence ( ObjectSequence < TimeSeriesCollection > seq ) { seq = seq . sort ( ) ; // Does nothing if already sorted. if ( ! seq . isDistinct ( ) && ! seq . isEmpty ( ) ) { List < ObjectSequence < TimeSeriesCollection >> toConcat = new ArrayList <> ( ) ; int lastGoodIdx = 0 ; int curIdx = 0 ; while ( curIdx < seq . size ( ) ) { final TimeSeriesCollection curElem = seq . get ( curIdx ) ; // Find first item with different timestamp. int nextIdx = curIdx + 1 ; while ( nextIdx < seq . size ( ) && curElem . getTimestamp ( ) . equals ( seq . get ( nextIdx ) . getTimestamp ( ) ) ) { ++ nextIdx ; } // If more than 1 adjecent element share timestamp, merge them together. if ( curIdx + 1 < nextIdx ) { toConcat . add ( seq . limit ( curIdx ) . skip ( lastGoodIdx ) ) ; TimeSeriesCollection replacement = new LazyMergedTSC ( seq . limit ( nextIdx ) . skip ( curIdx ) ) ; toConcat . add ( ObjectSequence . of ( true , true , true , replacement ) ) ; lastGoodIdx = curIdx = nextIdx ; } else { // Advance curIdx. ++ curIdx ; } } if ( lastGoodIdx < curIdx ) toConcat . add ( seq . skip ( lastGoodIdx ) ) ; seq = ObjectSequence . concat ( toConcat , true , true ) ; } return seq ; }
Fix a sequence to contain only distinct sorted elements .
378
10
138,307
public static ObjectSequence < TimeSeriesCollection > mergeSequences ( ObjectSequence < TimeSeriesCollection > ... tsSeq ) { if ( tsSeq . length == 0 ) return ObjectSequence . empty ( ) ; if ( tsSeq . length == 1 ) return tsSeq [ 0 ] ; // Sort sequences and remove any that are empty. final Queue < ObjectSequence < TimeSeriesCollection > > seq = new PriorityQueue <> ( Comparator . comparing ( ObjectSequence :: first ) ) ; seq . addAll ( Arrays . stream ( tsSeq ) . filter ( s -> ! s . isEmpty ( ) ) . collect ( Collectors . toList ( ) ) ) ; // It's possible the filtering reduced the number of elements to 0 or 1... if ( seq . isEmpty ( ) ) return ObjectSequence . empty ( ) ; if ( seq . size ( ) == 1 ) return seq . element ( ) ; final List < ObjectSequence < TimeSeriesCollection > > output = new ArrayList <> ( tsSeq . length ) ; while ( ! seq . isEmpty ( ) ) { final ObjectSequence < TimeSeriesCollection > head = seq . remove ( ) ; if ( seq . isEmpty ( ) ) { output . add ( head ) ; continue ; } if ( head . last ( ) . compareTo ( seq . element ( ) . first ( ) ) < 0 ) { output . add ( head ) ; continue ; } final List < ObjectSequence < TimeSeriesCollection > > toMerge = new ArrayList <> ( ) ; // Find the intersecting range. final int headProblemStart = head . equalRange ( tsc -> tsc . compareTo ( seq . element ( ) . first ( ) ) ) . getBegin ( ) ; output . add ( head . limit ( headProblemStart ) ) ; // Add non-intersecting range to output. toMerge . add ( head . skip ( headProblemStart ) ) ; // Add problematic area to 'toMerge' collection. // Find all remaining intersecting ranges and add them to 'toMerge', replacing them with their non-intersecting ranges. final TimeSeriesCollection headLast = head . last ( ) ; while ( ! seq . isEmpty ( ) && seq . element ( ) . first ( ) . compareTo ( headLast ) <= 0 ) { final ObjectSequence < TimeSeriesCollection > succ = seq . remove ( ) ; TimeSeriesCollection succFirst = succ . first ( ) ; System . err . println ( "succ.first: " + succ . first ( ) + ", head.last: " + headLast ) ; // Add intersecting range of succ to 'toMerge'. final int succProblemEnd = succ . equalRange ( tsc -> tsc . compareTo ( headLast ) ) . getEnd ( ) ; assert succProblemEnd > 0 ; toMerge . add ( succ . limit ( succProblemEnd ) ) ; // Add non-intersecting range of succ back to 'seq'. ObjectSequence < TimeSeriesCollection > succNoProblem = succ . skip ( succProblemEnd ) ; if ( ! succNoProblem . isEmpty ( ) ) seq . add ( succNoProblem ) ; } assert ( toMerge . size ( ) > 1 ) ; output . add ( fixSequence ( ObjectSequence . concat ( toMerge , false , false ) ) ) ; } return ObjectSequence . concat ( output , true , true ) ; }
Given zero or more sequences that are all sorted and distinct merge them together .
741
15
138,308
public void queueResource ( String bundle , String resource , boolean loop ) { try { queueURL ( new URL ( "resource://" + bundle + "/" + resource ) , loop ) ; } catch ( MalformedURLException e ) { log . warning ( "Invalid resource url." , "resource" , resource , e ) ; } }
Adds a resource to the queue of files to play .
72
11
138,309
public static boolean isMappedIPv4Address ( Inet6Address ip ) { byte bytes [ ] = ip . getAddress ( ) ; return ( ( bytes [ 0 ] == 0x00 ) && ( bytes [ 1 ] == 0x00 ) && ( bytes [ 2 ] == 0x00 ) && ( bytes [ 3 ] == 0x00 ) && ( bytes [ 4 ] == 0x00 ) && ( bytes [ 5 ] == 0x00 ) && ( bytes [ 6 ] == 0x00 ) && ( bytes [ 7 ] == 0x00 ) && ( bytes [ 8 ] == 0x00 ) && ( bytes [ 9 ] == 0x00 ) && ( bytes [ 10 ] == ( byte ) 0xff ) && ( bytes [ 11 ] == ( byte ) 0xff ) ) ; }
Evaluates whether the argument is an IPv6 mapped address .
170
13
138,310
public static Inet4Address getMappedIPv4Address ( Inet6Address ip ) { if ( ! isMappedIPv4Address ( ip ) ) throw new IllegalArgumentException ( String . format ( "Address '%s' is not IPv4-mapped." , toAddrString ( ip ) ) ) ; return getInet4Address ( copyOfRange ( ip . getAddress ( ) , 12 , 16 ) ) ; }
Returns the IPv4 address embedded in an IPv4 mapped address .
96
13
138,311
protected void checkIdle ( ) { long now = getTimeStamp ( ) ; switch ( _state ) { case ACTIVE : // check whether they've idled out if ( now >= ( _lastEvent + _toIdleTime ) ) { log . info ( "User idle for " + ( now - _lastEvent ) + "ms." ) ; _state = IDLE ; idledOut ( ) ; } break ; case IDLE : // check whether they've been idle for too long if ( now >= ( _lastEvent + _toIdleTime + _toAbandonTime ) ) { log . info ( "User idle for " + ( now - _lastEvent ) + "ms. " + "Abandoning ship." ) ; _state = ABANDONED ; abandonedShip ( ) ; } break ; } }
Checks the last user event time and posts a command to idle them out if they ve been inactive for too long or log them out if they ve been idle for too long .
178
36
138,312
private void run_implementation_ ( PushProcessor p ) throws Exception { final Map < GroupName , Alert > alerts = registry_ . getCollectionAlerts ( ) ; final TimeSeriesCollection tsdata = registry_ . getCollectionData ( ) ; p . accept ( tsdata , unmodifiableMap ( alerts ) , registry_ . getFailedCollections ( ) ) ; }
Run the implementation of uploading the values and alerts .
80
10
138,313
@ Override public final void run ( ) { try { registry_ . updateCollection ( ) ; final long t0 = System . nanoTime ( ) ; processors_ . forEach ( p -> { try { run_implementation_ ( p ) ; } catch ( Exception ex ) { logger . log ( Level . SEVERE , p . getClass ( ) . getName ( ) + " failed to run properly, some or all metrics may be missed this cycle" , ex ) ; } } ) ; final long t_processor = System . nanoTime ( ) ; registry_ . updateProcessorDuration ( Duration . millis ( TimeUnit . NANOSECONDS . toMillis ( t_processor - t0 ) ) ) ; } catch ( Throwable t ) { /* * We catch any and all throwables. * If we don't and let an exception or error escape, * the scheduled executor service will _silently_ drop our task. */ logger . log ( Level . SEVERE , "failed to perform collection" , t ) ; } }
Run the collection cycle .
224
5
138,314
public void resolveBlock ( SceneBlock block , boolean hipri ) { log . debug ( "Queueing block for resolution" , "block" , block , "hipri" , hipri ) ; if ( hipri ) { _queue . prepend ( block ) ; } else { _queue . append ( block ) ; } }
Queues up a scene block for resolution .
69
9
138,315
public static boolean openNotification ( ) throws Exception { boolean success = false ; // get API level int apiLevel = Client . getInstance ( ) . mapField ( "android.os.Build$VERSION" , "SDK_INT" ) . getInt ( 0 ) ; if ( apiLevel >= 18 ) { success = Client . getInstance ( ) . map ( Constants . UIAUTOMATOR_UIDEVICE , "openNotification" ) . getBoolean ( 0 ) ; } else { // try a brute force method int displayHeight = getDisplayHeight ( ) ; // Calculated a Y position to pull down to that is the display height minus 10% int pullTo = displayHeight - ( int ) ( ( double ) displayHeight * .1 ) ; Client . getInstance ( ) . map ( Constants . UIAUTOMATOR_UIDEVICE , "swipe" , 10 , 0 , 10 , pullTo , 100 ) ; success = true ; } return success ; }
Open notification shade
210
3
138,316
public static boolean click ( int x , int y ) throws Exception { return Client . getInstance ( ) . map ( Constants . UIAUTOMATOR_UIDEVICE , "click" , x , y ) . getBoolean ( 0 ) ; }
Click at x y position
54
5
138,317
public void moveAndFadeIn ( Path path , long pathDuration , float fadePortion ) { move ( path ) ; setAlpha ( 0.0f ) ; _fadeInDuration = ( long ) ( pathDuration * fadePortion ) ; }
Puts this sprite on the specified path and fades it in over the specified duration .
54
17
138,318
public void moveAndFadeOut ( Path path , long pathDuration , float fadePortion ) { move ( path ) ; setAlpha ( 1.0f ) ; _fadeStamp = 0 ; _pathDuration = pathDuration ; _fadeOutDuration = ( long ) ( pathDuration * fadePortion ) ; _fadeDelay = _pathDuration - _fadeOutDuration ; }
Puts this sprite on the specified path and fades it out over the specified duration .
85
17
138,319
public void moveAndFadeInAndOut ( Path path , long pathDuration , float fadePortion ) { move ( path ) ; setAlpha ( 0.0f ) ; _pathDuration = pathDuration ; _fadeInDuration = _fadeOutDuration = ( long ) ( pathDuration * fadePortion ) ; }
Puts this sprite on the specified path fading it in over the specified duration at the beginning and fading it out at the end .
69
26
138,320
public void setAlpha ( float alpha ) { if ( alpha < 0.0f ) { alpha = 0.0f ; } else if ( alpha > 1.0f ) { alpha = 1.0f ; } if ( alpha != _alphaComposite . getAlpha ( ) ) { _alphaComposite = AlphaComposite . getInstance ( AlphaComposite . SRC_OVER , alpha ) ; if ( _mgr != null ) { _mgr . getRegionManager ( ) . invalidateRegion ( _bounds ) ; } } }
Sets the alpha value of this sprite .
120
9
138,321
public static void register ( PerformanceObserver obs , String name , long delta ) { // get the observer's action hashtable Map < String , PerformanceAction > actions = _observers . get ( obs ) ; if ( actions == null ) { // create it if it didn't exist _observers . put ( obs , actions = Maps . newHashMap ( ) ) ; } // add the action to the set we're tracking actions . put ( name , new PerformanceAction ( obs , name , delta ) ) ; }
Register a new action with an observer the action name and the milliseconds to wait between checkpointing the action s performance .
109
23
138,322
public static void unregister ( PerformanceObserver obs , String name ) { // get the observer's action hashtable Map < String , PerformanceAction > actions = _observers . get ( obs ) ; if ( actions == null ) { log . warning ( "Attempt to unregister by unknown observer " + "[observer=" + obs + ", name=" + name + "]." ) ; return ; } // attempt to remove the specified action PerformanceAction action = actions . remove ( name ) ; if ( action == null ) { log . warning ( "Attempt to unregister unknown action " + "[observer=" + obs + ", name=" + name + "]." ) ; return ; } // if the observer has no actions left, remove the observer's action // hash in its entirety if ( actions . size ( ) == 0 ) { _observers . remove ( obs ) ; } }
Un - register the named action associated with the given observer .
183
12
138,323
public static void tick ( PerformanceObserver obs , String name ) { // get the observer's action hashtable Map < String , PerformanceAction > actions = _observers . get ( obs ) ; if ( actions == null ) { log . warning ( "Attempt to tick by unknown observer " + "[observer=" + obs + ", name=" + name + "]." ) ; return ; } // get the specified action PerformanceAction action = actions . get ( name ) ; if ( action == null ) { log . warning ( "Attempt to tick unknown value " + "[observer=" + obs + ", name=" + name + "]." ) ; return ; } // tick the action action . tick ( ) ; }
Tick the named action associated with the given observer .
147
11
138,324
private URI _getSpecURI ( String spec ) { URI specURI = URI . create ( spec ) ; if ( _scheme . indexOf ( ' ' ) == - 1 ) { return specURI ; } String schemeSpecificPart = specURI . getSchemeSpecificPart ( ) ; return URI . create ( schemeSpecificPart ) ; }
the appropriate URI that can be used to retrieve the needed parts .
71
13
138,325
protected boolean checkTileIndex ( int tileIndex ) { int tcount = getTileCount ( ) ; if ( tileIndex >= 0 && tileIndex < tcount ) { return true ; } else { log . warning ( "Requested invalid tile [tset=" + this + ", index=" + tileIndex + "]." , new Exception ( ) ) ; return false ; } }
Used to ensure that the specified tile index is valid .
78
11
138,326
public TagInfo getTag ( String shortname ) { TagInfo tags [ ] = getTags ( ) ; if ( tags == null || tags . length == 0 ) { return null ; } for ( int i = 0 ; i < tags . length ; i ++ ) { if ( tags [ i ] . getTagName ( ) . equals ( shortname ) ) { return tags [ i ] ; } } return null ; }
Get the TagInfo for a given tag name looking through all the tags in this tag library .
88
19
138,327
public TagFileInfo getTagFile ( String shortname ) { TagFileInfo tagFiles [ ] = getTagFiles ( ) ; if ( tagFiles == null || tagFiles . length == 0 ) { return null ; } for ( int i = 0 ; i < tagFiles . length ; i ++ ) { if ( tagFiles [ i ] . getName ( ) . equals ( shortname ) ) { return tagFiles [ i ] ; } } return null ; }
Get the TagFileInfo for a given tag name looking through all the tag files in this tag library .
97
21
138,328
public FunctionInfo getFunction ( String name ) { if ( functions == null || functions . length == 0 ) { System . err . println ( "No functions" ) ; return null ; } for ( int i = 0 ; i < functions . length ; i ++ ) { if ( functions [ i ] . getName ( ) . equals ( name ) ) { return functions [ i ] ; } } return null ; }
Get the FunctionInfo for a given function name looking through all the functions in this tag library .
86
19
138,329
protected int readSamples ( ) throws IOException { int samples ; while ( ( samples = _dsp . synthesis_pcmout ( _pcm , _offsets ) ) <= 0 ) { if ( samples == 0 && ! readPacket ( ) ) { return 0 ; } if ( _block . synthesis ( _packet ) == 0 ) { _dsp . synthesis_blockin ( _block ) ; } } return samples ; }
Reads a buffer s worth of samples .
94
9
138,330
protected boolean readPacket ( ) throws IOException { int result ; while ( ( result = _stream . packetout ( _packet ) ) != 1 ) { if ( result == 0 && ! readPage ( ) ) { return false ; } } return true ; }
Reads a packet .
56
5
138,331
protected boolean readPage ( ) throws IOException { int result ; while ( ( result = _sync . pageout ( _page ) ) != 1 ) { if ( result == 0 && ! readChunk ( ) ) { return false ; } } _stream . pagein ( _page ) ; return true ; }
Reads in a page .
65
6
138,332
protected boolean readChunk ( ) throws IOException { int offset = _sync . buffer ( BUFFER_SIZE ) ; int bytes = _in . read ( _sync . data , offset , BUFFER_SIZE ) ; if ( bytes > 0 ) { _sync . wrote ( bytes ) ; return true ; } return false ; }
Reads in a chunk of data from the underlying input stream .
69
13
138,333
public static TrimmedTileSet trimTileSet ( TileSet source , OutputStream destImage ) throws IOException { return trimTileSet ( source , destImage , FastImageIO . FILE_SUFFIX ) ; }
Convenience function to trim the tile set and save it using FastImageIO .
46
17
138,334
public boolean sourceIsReady ( ) { // make a note of our source's last modification time _sourceLastMod = _source . lastModified ( ) ; // if we are unpacking files, the time to do so is now if ( _unpacked != null && _unpacked . lastModified ( ) != _sourceLastMod ) { try { resolveJarFile ( ) ; } catch ( IOException ioe ) { log . warning ( "Failure resolving jar file" , "source" , _source , ioe ) ; wipeBundle ( true ) ; return false ; } log . info ( "Unpacking into " + _cache + "..." ) ; if ( ! _cache . exists ( ) ) { if ( ! _cache . mkdir ( ) ) { log . warning ( "Failed to create bundle cache directory" , "dir" , _cache ) ; closeJar ( ) ; // we are hopelessly fucked return false ; } } else { FileUtil . recursiveClean ( _cache ) ; } // unpack the jar file (this will close the jar when it's done) if ( ! FileUtil . unpackJar ( _jarSource , _cache ) ) { // if something went awry, delete everything in the hopes // that next time things will work wipeBundle ( true ) ; return false ; } // if everything unpacked smoothly, create our unpack stamp try { _unpacked . createNewFile ( ) ; if ( ! _unpacked . setLastModified ( _sourceLastMod ) ) { log . warning ( "Failed to set last mod on stamp file" , "file" , _unpacked ) ; } } catch ( IOException ioe ) { log . warning ( "Failure creating stamp file" , "file" , _unpacked , ioe ) ; // no need to stick a fork in things at this point } } return true ; }
Called by the resource manager once it has ensured that our resource jar file is up to date and ready for reading .
400
24
138,335
public void wipeBundle ( boolean deleteJar ) { // clear out our cache directory if ( _cache != null ) { FileUtil . recursiveClean ( _cache ) ; } // delete our unpack stamp file if ( _unpacked != null ) { _unpacked . delete ( ) ; } // clear out any .jarv file that Getdown might be maintaining so // that we ensure that it is revalidated File vfile = new File ( FileUtil . resuffix ( _source , ".jar" , ".jarv" ) ) ; if ( vfile . exists ( ) && ! vfile . delete ( ) ) { log . warning ( "Failed to delete vfile" , "file" , vfile ) ; } // close and delete our source jar file if ( deleteJar && _source != null ) { closeJar ( ) ; if ( ! _source . delete ( ) ) { log . warning ( "Failed to delete source" , "source" , _source , "exists" , _source . exists ( ) ) ; } } }
Clears out everything associated with this resource bundle in the hopes that we can download it afresh and everything will work the next time around .
226
28
138,336
public File getResourceFile ( String path ) throws IOException { if ( resolveJarFile ( ) ) { return null ; } // if we have been unpacked, return our unpacked file if ( _cache != null ) { File cfile = new File ( _cache , path ) ; if ( cfile . exists ( ) ) { return cfile ; } else { return null ; } } // otherwise, we unpack resources as needed into a temp directory String tpath = StringUtil . md5hex ( _source . getPath ( ) + "%" + path ) ; File tfile = new File ( getCacheDir ( ) , tpath ) ; if ( tfile . exists ( ) && ( tfile . lastModified ( ) > _sourceLastMod ) ) { return tfile ; } JarEntry entry = _jarSource . getJarEntry ( path ) ; if ( entry == null ) { // log.info("Couldn't locate path in jar", "path", path, "jar", _jarSource); return null ; } // copy the resource into the temporary file BufferedOutputStream fout = new BufferedOutputStream ( new FileOutputStream ( tfile ) ) ; InputStream jin = _jarSource . getInputStream ( entry ) ; StreamUtil . copy ( jin , fout ) ; jin . close ( ) ; fout . close ( ) ; return tfile ; }
Returns a file from which the specified resource can be loaded . This method will unpack the resource into a temporary directory and return a reference to that file .
299
31
138,337
public boolean containsResource ( String path ) { try { if ( resolveJarFile ( ) ) { return false ; } return ( _jarSource . getJarEntry ( path ) != null ) ; } catch ( IOException ioe ) { return false ; } }
Returns true if this resource bundle contains the resource with the specified path . This avoids actually loading the resource in the event that the caller only cares to know that the resource exists .
54
35
138,338
protected boolean resolveJarFile ( ) throws IOException { // if we don't yet have our resource bundle's last mod time, we // have not yet been notified that it is ready if ( _sourceLastMod == - 1 ) { return true ; } if ( ! _source . exists ( ) ) { throw new IOException ( "Missing jar file for resource bundle: " + _source + "." ) ; } try { if ( _jarSource == null ) { _jarSource = new JarFile ( _source ) ; } return false ; } catch ( IOException ioe ) { String msg = "Failed to resolve resource bundle jar file '" + _source + "'" ; log . warning ( msg + "." , ioe ) ; throw ( IOException ) new IOException ( msg ) . initCause ( ioe ) ; } }
Creates the internal jar file reference if we ve not already got it ; we do this lazily so as to avoid any jar - or zip - file - related antics until and unless doing so is required and because the resource manager would like to be able to create bundles before the associated files have been fully downloaded .
177
63
138,339
public static File getCacheDir ( ) { if ( _tmpdir == null ) { String tmpdir = System . getProperty ( "java.io.tmpdir" ) ; if ( tmpdir == null ) { log . info ( "No system defined temp directory. Faking it." ) ; tmpdir = System . getProperty ( "user.home" ) ; } setCacheDir ( new File ( tmpdir ) ) ; } return _tmpdir ; }
Returns the cache directory used for unpacked resources .
97
10
138,340
public static void setCacheDir ( File tmpdir ) { String rando = Long . toHexString ( ( long ) ( Math . random ( ) * Long . MAX_VALUE ) ) ; _tmpdir = new File ( tmpdir , "narcache_" + rando ) ; if ( ! _tmpdir . exists ( ) ) { if ( _tmpdir . mkdirs ( ) ) { log . debug ( "Created narya temp cache directory '" + _tmpdir + "'." ) ; } else { log . warning ( "Failed to create temp cache directory '" + _tmpdir + "'." ) ; } } // add a hook to blow away the temp directory when we exit Runtime . getRuntime ( ) . addShutdownHook ( new Thread ( ) { @ Override public void run ( ) { log . info ( "Clearing narya temp cache '" + _tmpdir + "'." ) ; FileUtil . recursiveDelete ( _tmpdir ) ; } } ) ; }
Specifies the directory in which our temporary resource files should be stored .
216
14
138,341
protected static String stripSuffix ( String path ) { if ( path . endsWith ( ".jar" ) ) { return path . substring ( 0 , path . length ( ) - 4 ) ; } else { // we have to change the path somehow return path + "-cache" ; } }
Strips the . jar off of jar file paths .
62
12
138,342
public static < T > CloseableIterator < T > distinct ( final CloseableIterator < T > iterator ) { return wrap ( Iterators2 . distinct ( iterator ) , iterator ) ; }
If we can assume the closeable iterator is sorted return the distinct elements . This only works if the data provided is sorted .
39
25
138,343
public Stream < RangeWithCount > stream ( ) { return buckets_ . stream ( ) . map ( bucket -> new RangeWithCount ( bucket . getRange ( ) , bucket . getEvents ( ) ) ) ; }
Returns a map of range - &gt ; event count . The elements of the stream are a mutable copy of the internal data .
45
27
138,344
public Optional < Double > avg ( ) { if ( isEmpty ( ) ) return Optional . empty ( ) ; return Optional . of ( sum ( ) / getEventCount ( ) ) ; }
Return the average of the histogram .
40
8
138,345
public double sum ( ) { return buckets_ . stream ( ) . mapToDouble ( b -> b . getRange ( ) . getMidPoint ( ) * b . getEvents ( ) ) . sum ( ) ; }
Return the sum of the histogram .
46
8
138,346
public double get ( double index ) { ListIterator < Bucket > b = buckets_ . listIterator ( 0 ) ; ListIterator < Bucket > e = buckets_ . listIterator ( buckets_ . size ( ) ) ; while ( b . nextIndex ( ) < e . previousIndex ( ) ) { final ListIterator < Bucket > mid = buckets_ . listIterator ( b . nextIndex ( ) / 2 + e . nextIndex ( ) / 2 ) ; final Bucket mid_bucket = mid . next ( ) ; mid . previous ( ) ; // Undo position change made by mid.next(). if ( mid_bucket . getRunningEventsCount ( ) == index && mid . nextIndex ( ) >= e . previousIndex ( ) ) { return mid_bucket . getRange ( ) . getCeil ( ) ; } else if ( mid_bucket . getRunningEventsCount ( ) <= index ) { b = mid ; b . next ( ) ; } else if ( mid_bucket . getRunningEventsCount ( ) - mid_bucket . getEvents ( ) > index ) { e = mid ; } else { b = mid ; break ; } } final Bucket bucket = b . next ( ) ; b . previous ( ) ; // Undo position change made by b.next(). final double low = bucket . getRunningEventsCount ( ) - bucket . getEvents ( ) ; final double off = index - low ; final double left_fraction = off / bucket . getEvents ( ) ; final double right_fraction = 1 - left_fraction ; return bucket . getRange ( ) . getCeil ( ) * left_fraction + bucket . getRange ( ) . getFloor ( ) * right_fraction ; }
Get the value at a given position .
371
8
138,347
public Histogram modifyEventCounters ( BiFunction < Range , Double , Double > fn ) { return new Histogram ( stream ( ) . map ( entry -> { entry . setCount ( fn . apply ( entry . getRange ( ) , entry . getCount ( ) ) ) ; return entry ; } ) ) ; }
Create a new histogram after applying the function on each of the event counters .
67
16
138,348
public static Histogram add ( Histogram x , Histogram y ) { return new Histogram ( Stream . concat ( x . stream ( ) , y . stream ( ) ) ) ; }
Add two histograms together .
40
6
138,349
public static Histogram subtract ( Histogram x , Histogram y ) { return new Histogram ( Stream . concat ( x . stream ( ) , y . stream ( ) . map ( rwc -> { rwc . setCount ( - rwc . getCount ( ) ) ; return rwc ; } ) ) ) ; }
Subtracts two histograms .
73
8
138,350
public static Histogram multiply ( Histogram x , double y ) { return x . modifyEventCounters ( ( r , d ) -> d * y ) ; }
Multiply histogram by scalar .
34
9
138,351
public static Histogram divide ( Histogram x , double y ) { return x . modifyEventCounters ( ( r , d ) -> d / y ) ; }
Divide histogram by scalar .
34
8
138,352
@ Override public int compareTo ( Histogram o ) { int cmp = 0 ; final Iterator < Bucket > iter = buckets_ . iterator ( ) , o_iter = o . buckets_ . iterator ( ) ; while ( cmp == 0 && iter . hasNext ( ) && o_iter . hasNext ( ) ) { final Bucket next = iter . next ( ) , o_next = o_iter . next ( ) ; cmp = Double . compare ( next . getRange ( ) . getFloor ( ) , o_next . getRange ( ) . getFloor ( ) ) ; if ( cmp == 0 ) cmp = Double . compare ( next . getRange ( ) . getCeil ( ) , o_next . getRange ( ) . getCeil ( ) ) ; if ( cmp == 0 ) cmp = Double . compare ( next . getEvents ( ) , o_next . getEvents ( ) ) ; } if ( cmp == 0 ) cmp = ( iter . hasNext ( ) ? 1 : ( o_iter . hasNext ( ) ? - 1 : 0 ) ) ; return cmp ; }
Compare two histograms .
248
5
138,353
@ Override protected final Object convertToObject ( final String text ) throws Exception { Map map = CollectionUtil . toMap ( text , keyEditor , valueEditor ) ; if ( map == null ) { return null ; } return createMap ( map ) ; }
Treats the text value of this property as an input stream that is converted into a Property bundle .
55
21
138,354
@ Nullable @ Override public NodeGraphicDefinition getGroupGraphics ( Object group , Set < String > groupElements ) { return null ; }
we have no groups in this example
31
7
138,355
public static final String name ( SimpleGroupPath group , MetricName metric ) { return name ( Stream . concat ( group . getPath ( ) . stream ( ) , metric . getPath ( ) . stream ( ) ) . collect ( Collectors . joining ( "." ) ) ) ; }
Convert a group + metric to a wavefront name .
62
12
138,356
private static Optional < Map . Entry < String , String > > createTagEntry ( Map . Entry < String , MetricValue > tag_entry ) { final Optional < String > opt_tag_value = tag_entry . getValue ( ) . asString ( ) ; return opt_tag_value . map ( tag_value -> SimpleMapEntry . create ( name ( tag_entry . getKey ( ) ) , escapeTagValue ( tag_value ) ) ) ; }
Transform a tag entry into a wavefront tag .
100
10
138,357
private static Map . Entry < String , String > maybeTruncateTagEntry ( Map . Entry < String , String > tag_entry ) { String k = tag_entry . getKey ( ) ; String v = tag_entry . getValue ( ) ; if ( k . length ( ) + v . length ( ) <= MAX_TAG_KEY_VAL_CHARS - 2 ) // 2 chars for the quotes around the value return tag_entry ; if ( k . length ( ) > TRUNCATE_TAG_NAME ) k = k . substring ( 0 , TRUNCATE_TAG_NAME ) ; if ( k . length ( ) + v . length ( ) > MAX_TAG_KEY_VAL_CHARS - 2 ) v = v . substring ( 0 , MAX_TAG_KEY_VAL_CHARS - 2 - k . length ( ) ) ; return SimpleMapEntry . create ( k , v ) ; }
Truncate tag keys and values to prevent them from exceeding the max length of a tag entry .
200
20
138,358
public static Map < String , String > tags ( Tags tags ) { return tags . stream ( ) . map ( WavefrontStrings :: createTagEntry ) . flatMap ( opt -> opt . map ( Stream :: of ) . orElseGet ( Stream :: empty ) ) . map ( WavefrontStrings :: maybeTruncateTagEntry ) . collect ( Collectors . toMap ( Map . Entry :: getKey , Map . Entry :: getValue ) ) ; }
Create a map of tags for wavefront .
97
9
138,359
public static Optional < String > wavefrontValue ( MetricValue mv ) { // Omit NaN and Inf. if ( mv . isInfiniteOrNaN ( ) ) return Optional . empty ( ) ; return mv . value ( ) . map ( Number :: toString ) ; }
Create a wavefront compatible string representation of the metric value .
63
12
138,360
private static String extractTagSource ( Map < String , String > tag_map ) { return Optional . ofNullable ( tag_map . remove ( "source" ) ) . orElseGet ( ( ) -> { return Optional . ofNullable ( tag_map . get ( "cluster" ) ) . map ( WavefrontStrings :: escapeTagValue ) . orElseGet ( ( ) -> tag_map . getOrDefault ( "moncluster" , "monsoon" ) ) ; } ) ; }
Extract the source tag from the tag_map .
109
11
138,361
private static String wavefrontLine ( DateTime ts , SimpleGroupPath group , MetricName metric , String value , String source , Map < String , String > tag_map ) { return new StringBuilder ( ) . append ( name ( group , metric ) ) . append ( ' ' ) . append ( value ) . append ( ' ' ) . append ( timestamp ( ts ) ) . append ( ' ' ) . append ( "source=" ) . append ( source ) . append ( ' ' ) . append ( tag_map . entrySet ( ) . stream ( ) . map ( entry -> entry . getKey ( ) + "=\"" + entry . getValue ( ) + ' ' ) . collect ( Collectors . joining ( " " ) ) ) . toString ( ) ; }
Build the wavefront line from its parts .
164
9
138,362
public static Optional < String > wavefrontLine ( DateTime ts , GroupName group , MetricName metric , MetricValue metric_value ) { return wavefrontValue ( metric_value ) . map ( value -> { final Map < String , String > tag_map = tags ( group . getTags ( ) ) ; final String source = extractTagSource ( tag_map ) ; // Modifies tag_map. return wavefrontLine ( ts , group . getPath ( ) , metric , value , source , tag_map ) ; } ) ; }
Convert a metric to a wavefront string .
116
10
138,363
public static Stream < String > wavefrontLine ( DateTime ts , TimeSeriesValue tsv ) { final GroupName group = tsv . getGroup ( ) ; return tsv . getMetrics ( ) . entrySet ( ) . stream ( ) . flatMap ( metricEntry -> wavefrontLineForMetric ( ts , group , metricEntry ) ) ; }
Convert a time series value into the string entries for wavefront .
76
14
138,364
public Point getEndPos ( ) { return new Point ( ( int ) ( _center . x + Math . round ( Math . cos ( _sangle + _delta ) * _xradius ) ) , ( int ) ( _center . y + Math . round ( Math . sin ( _sangle + _delta ) * _yradius ) ) ) ; }
Returns the position of the end of the path .
79
10
138,365
public static Serializable loadConfig ( InputStream source ) throws IOException { try { ObjectInputStream oin = new ObjectInputStream ( source ) ; return ( Serializable ) oin . readObject ( ) ; } catch ( ClassNotFoundException cnfe ) { String errmsg = "Unknown config class" ; throw ( IOException ) new IOException ( errmsg ) . initCause ( cnfe ) ; } }
Unserializes a configuration object from the supplied input stream .
89
12
138,366
public static void saveConfig ( File target , Serializable config ) throws IOException { FileOutputStream fout = new FileOutputStream ( target ) ; ObjectOutputStream oout = new ObjectOutputStream ( fout ) ; oout . writeObject ( config ) ; oout . close ( ) ; }
Serializes the supplied configuration object to the specified file path .
63
12
138,367
public void historyUpdated ( int adjustment ) { if ( adjustment != 0 ) { for ( int ii = 0 , nn = _showingHistory . size ( ) ; ii < nn ; ii ++ ) { ChatGlyph cg = _showingHistory . get ( ii ) ; cg . histIndex -= adjustment ; } // some history entries were deleted, we need to re-figure the history scrollbar action resetHistoryOffset ( ) ; } if ( isLaidOut ( ) && isHistoryMode ( ) ) { int val = _historyModel . getValue ( ) ; updateHistBar ( val - adjustment ) ; // only repaint if we need to if ( ( val != _historyModel . getValue ( ) ) || ( adjustment != 0 ) || ! _histOffsetFinal ) { figureCurrentHistory ( ) ; } } }
from interface HistoryList . Observer
177
6
138,368
public boolean displayMessage ( ChatMessage message , boolean alreadyDisplayed ) { // nothing doing if we've not been laid out if ( ! isLaidOut ( ) ) { return false ; } // possibly display it now Graphics2D gfx = getTargetGraphics ( ) ; if ( gfx != null ) { displayMessage ( message , gfx ) ; // display it gfx . dispose ( ) ; // clean up return true ; } return false ; }
documentation inherited from superinterface ChatDisplay
95
8
138,369
protected void updateDimmed ( List < ? extends ChatGlyph > glyphs ) { for ( ChatGlyph glyph : glyphs ) { glyph . setDim ( _dimmed ) ; } }
Update the chat glyphs in the specified list to be set to the current dimmed setting .
43
19
138,370
protected void setHistoryEnabled ( boolean historyEnabled ) { if ( historyEnabled && _historyModel == null ) { _historyModel = _scrollbar . getModel ( ) ; _historyModel . addChangeListener ( this ) ; resetHistoryOffset ( ) ; // out with the subtitles, we'll be displaying history clearGlyphs ( _subtitles ) ; // "scroll" down to the latest history entry updateHistBar ( _history . size ( ) - 1 ) ; // refigure our history figureCurrentHistory ( ) ; } else if ( ! historyEnabled && _historyModel != null ) { _historyModel . removeChangeListener ( this ) ; _historyModel = null ; // out with the history, we'll be displaying subtitles clearGlyphs ( _showingHistory ) ; } }
Configures us for display of chat history or not .
168
11
138,371
protected void viewDidScroll ( List < ? extends ChatGlyph > glyphs , int dx , int dy ) { for ( ChatGlyph glyph : glyphs ) { glyph . viewDidScroll ( dx , dy ) ; } }
Helper function for informing glyphs of the scrolled view .
50
12
138,372
protected void updateHistBar ( int val ) { // we may need to figure out the new history offset amount.. if ( ! _histOffsetFinal && _history . size ( ) > _histOffset ) { Graphics2D gfx = getTargetGraphics ( ) ; if ( gfx != null ) { figureHistoryOffset ( gfx ) ; gfx . dispose ( ) ; } } // then figure out the new value and range int oldval = Math . max ( _histOffset , val ) ; int newmaxval = Math . max ( 0 , _history . size ( ) - 1 ) ; int newval = ( oldval >= newmaxval - 1 ) ? newmaxval : oldval ; // and set it, which MAY generate a change event, but we want to ignore it so we use the // _settingBar flag _settingBar = true ; _historyModel . setRangeProperties ( newval , _historyExtent , _histOffset , newmaxval + _historyExtent , _historyModel . getValueIsAdjusting ( ) ) ; _settingBar = false ; }
Update the history scrollbar with the specified value .
230
10
138,373
protected void figureHistoryOffset ( Graphics2D gfx ) { if ( ! isLaidOut ( ) ) { return ; } int hei = _subtitleYSpacing ; int hsize = _history . size ( ) ; for ( int ii = 0 ; ii < hsize ; ii ++ ) { ChatGlyph rec = getHistorySubtitle ( ii , gfx ) ; Rectangle r = rec . getBounds ( ) ; hei += r . height ; // oop, we passed it, it was the last one if ( hei >= _subtitleHeight ) { _histOffset = Math . max ( 0 , ii - 1 ) ; _histOffsetFinal = true ; return ; } hei += getHistorySubtitleSpacing ( ii ) ; } // basically, this means there isn't yet enough history to fill the first 'page' of the // history scrollback, so we set the offset to the max value, but we do not set // _histOffsetFinal to be true so that this will be recalculated _histOffset = hsize - 1 ; }
Figure out how many of the first history elements fit in our bounds such that we can set the bounds on the scrollbar correctly such that the scrolling to the smallest value just barely puts the first element onscreen .
229
42
138,374
protected void figureCurrentHistory ( ) { int first = _historyModel . getValue ( ) ; int count = 0 ; Graphics2D gfx = null ; if ( isLaidOut ( ) && ! _history . isEmpty ( ) ) { gfx = getTargetGraphics ( ) ; if ( gfx == null ) { log . warning ( "Can't figure current history, no graphics." ) ; return ; } // start from the bottom.. Rectangle vbounds = _target . getViewBounds ( ) ; int ypos = vbounds . height - _subtitleYSpacing ; for ( int ii = first ; ii >= 0 ; ii -- , count ++ ) { ChatGlyph rec = getHistorySubtitle ( ii , gfx ) ; // see if it will fit Rectangle r = rec . getBounds ( ) ; ypos -= r . height ; if ( ( count != 0 ) && ypos <= ( vbounds . height - _subtitleHeight ) ) { break ; // don't add that one.. } // position it rec . setLocation ( vbounds . x + _subtitleXSpacing , vbounds . y + ypos ) ; // add space for the next ypos -= getHistorySubtitleSpacing ( ii ) ; } } // finally, because we've been adding to the _showingHistory here (via getHistorySubtitle) // and in figureHistoryOffset (possibly called prior to this method) we now need to prune // out the ChatGlyphs that aren't actually needed and make sure the ones that are are // positioned on the screen correctly for ( Iterator < ChatGlyph > itr = _showingHistory . iterator ( ) ; itr . hasNext ( ) ; ) { ChatGlyph cg = itr . next ( ) ; boolean managed = ( _target != null ) && _target . isManaged ( cg ) ; if ( cg . histIndex <= first && cg . histIndex > ( first - count ) ) { // it should be showing if ( ! managed ) { _target . addAnimation ( cg ) ; } } else { // it shouldn't be showing if ( managed ) { _target . abortAnimation ( cg ) ; } itr . remove ( ) ; } } if ( gfx != null ) { gfx . dispose ( ) ; } }
Figure out which ChatMessages in the history should currently appear in the showing history .
506
17
138,375
protected ChatGlyph getHistorySubtitle ( int index , Graphics2D layoutGfx ) { // do a brute search (over a small set) for an already-created subtitle for ( int ii = 0 , nn = _showingHistory . size ( ) ; ii < nn ; ii ++ ) { ChatGlyph cg = _showingHistory . get ( ii ) ; if ( cg . histIndex == index ) { return cg ; } } // it looks like we have to create a new one: expensive! ChatGlyph cg = createHistorySubtitle ( index , layoutGfx ) ; cg . histIndex = index ; cg . setDim ( _dimmed ) ; _showingHistory . add ( cg ) ; return cg ; }
Get the glyph for the specified history index creating if necessary .
168
12
138,376
protected ChatGlyph createHistorySubtitle ( int index , Graphics2D layoutGfx ) { ChatMessage message = _history . get ( index ) ; int type = getType ( message , true ) ; return createSubtitle ( message , type , layoutGfx , false ) ; }
Creates a subtitle for display in the history panel .
61
11
138,377
protected int getHistorySubtitleSpacing ( int index ) { ChatMessage message = _history . get ( index ) ; return _logic . getSubtitleSpacing ( getType ( message , true ) ) ; }
Determines the amount of spacing to put after a history subtitle .
46
14
138,378
protected void clearGlyphs ( List < ChatGlyph > glyphs ) { if ( _target != null ) { for ( int ii = 0 , nn = glyphs . size ( ) ; ii < nn ; ii ++ ) { ChatGlyph rec = glyphs . get ( ii ) ; _target . abortAnimation ( rec ) ; } } else if ( ! glyphs . isEmpty ( ) ) { log . warning ( "No target to abort chat animations" ) ; } glyphs . clear ( ) ; }
Clears out the supplied list of chat glyphs .
114
11
138,379
protected void displayMessage ( ChatMessage message , Graphics2D gfx ) { // get the non-history message type... int type = getType ( message , false ) ; if ( type != ChatLogic . IGNORECHAT ) { // display it now displayMessage ( message , type , gfx ) ; } }
Display the specified message now unless we are to ignore it .
67
12
138,380
protected void displayMessage ( ChatMessage message , int type , Graphics2D layoutGfx ) { // if we're in history mode, this will show up in the history and we'll rebuild our // subtitle list if and when history goes away if ( isHistoryMode ( ) ) { return ; } addSubtitle ( createSubtitle ( message , type , layoutGfx , true ) ) ; }
Display the message after we ve decided which type it is .
82
12
138,381
protected void addSubtitle ( ChatGlyph rec ) { // scroll up the old subtitles Rectangle r = rec . getBounds ( ) ; scrollUpSubtitles ( - r . height - _logic . getSubtitleSpacing ( rec . getType ( ) ) ) ; // put this one in place Rectangle vbounds = _target . getViewBounds ( ) ; rec . setLocation ( vbounds . x + _subtitleXSpacing , vbounds . y + vbounds . height - _subtitleYSpacing - r . height ) ; // add it to our list and to our media panel rec . setDim ( _dimmed ) ; _subtitles . add ( rec ) ; _target . addAnimation ( rec ) ; }
Add a subtitle for display now .
166
7
138,382
protected ChatGlyph createSubtitle ( ChatMessage message , int type , Graphics2D layoutGfx , boolean expires ) { // we might need to modify the textual part with translations, but we can't do that to the // message object, since other chatdisplays also get it. String text = message . message ; Tuple < String , Boolean > finfo = _logic . decodeFormat ( type , message . getFormat ( ) ) ; String format = finfo . left ; boolean quotes = finfo . right ; // now format the text if ( format != null ) { if ( quotes ) { text = "\"" + text + "\"" ; } text = " " + text ; text = xlate ( MessageBundle . tcompose ( format , ( ( UserMessage ) message ) . getSpeakerDisplayName ( ) ) ) + text ; } return createSubtitle ( layoutGfx , type , message . timestamp , null , 0 , text , expires ) ; }
Create a subtitle but don t do anything funny with it .
208
12
138,383
protected ChatGlyph createSubtitle ( Graphics2D gfx , int type , long timestamp , Icon icon , int indent , String text , boolean expires ) { Dimension is = new Dimension ( ) ; if ( icon != null ) { is . setSize ( icon . getIconWidth ( ) , icon . getIconHeight ( ) ) ; } Rectangle vbounds = _target . getViewBounds ( ) ; Label label = _logic . createLabel ( text ) ; label . setFont ( _logic . getFont ( type ) ) ; int paddedIconWidth = ( icon == null ) ? 0 : is . width + ICON_PADDING ; label . setTargetWidth ( vbounds . width - indent - paddedIconWidth - 2 * ( _subtitleXSpacing + Math . max ( UIManager . getInt ( "ScrollBar.width" ) , PAD ) ) ) ; label . layout ( gfx ) ; gfx . dispose ( ) ; Dimension ls = label . getSize ( ) ; Rectangle r = new Rectangle ( 0 , 0 , ls . width + indent + paddedIconWidth , Math . max ( is . height , ls . height ) ) ; r . grow ( 0 , 1 ) ; Point iconpos = r . getLocation ( ) ; iconpos . translate ( indent , r . height - is . height - 1 ) ; Point labelpos = r . getLocation ( ) ; labelpos . translate ( indent + paddedIconWidth , 1 ) ; Rectangle lr = new Rectangle ( r . x + indent + paddedIconWidth , r . y , r . width - indent - paddedIconWidth , ls . height + 2 ) ; // last a really long time if we're not supposed to expire long lifetime = Integer . MAX_VALUE ; if ( expires ) { lifetime = getChatExpire ( timestamp , label . getText ( ) ) - timestamp ; } Shape shape = _logic . getSubtitleShape ( type , lr , r ) ; return new ChatGlyph ( this , type , lifetime , r . union ( shape . getBounds ( ) ) , shape , icon , iconpos , label , labelpos , _logic . getOutlineColor ( type ) ) ; }
Create a subtitle - a line of text that goes on the bottom .
478
14
138,384
protected long getChatExpire ( long timestamp , String text ) { long [ ] durations = _logic . getDisplayDurations ( getDisplayDurationOffset ( ) ) ; // start the computation from the maximum of the timestamp or our last expire time long start = Math . max ( timestamp , _lastExpire ) ; // set the next expire to a time proportional to the text length _lastExpire = start + Math . min ( text . length ( ) * durations [ 0 ] , durations [ 2 ] ) ; // but don't let it be longer than the maximum display time _lastExpire = Math . min ( timestamp + durations [ 2 ] , _lastExpire ) ; // and be sure to pop up the returned time so that it is above the min return Math . max ( timestamp + durations [ 1 ] , _lastExpire ) ; }
Get the expire time for the specified chat .
183
9
138,385
protected void scrollUpSubtitles ( int dy ) { // dirty and move all the old glyphs Rectangle vbounds = _target . getViewBounds ( ) ; int miny = vbounds . y + vbounds . height - _subtitleHeight ; for ( Iterator < ChatGlyph > iter = _subtitles . iterator ( ) ; iter . hasNext ( ) ; ) { ChatGlyph sub = iter . next ( ) ; sub . translate ( 0 , dy ) ; if ( sub . getBounds ( ) . y <= miny ) { iter . remove ( ) ; _target . abortAnimation ( sub ) ; } } }
Scroll all the subtitles up by the specified amount .
143
10
138,386
private static ParsedLine extractCommandArguments ( final ParsedLine line ) { // copy the list, so we can mutate and pop the first item off LinkedList < String > words = Lists . newLinkedList ( line . words ( ) ) ; String remove = words . pop ( ) ; String rawLine = line . line ( ) ; // rebuild that list sans the first argument if ( remove . length ( ) > rawLine . length ( ) ) { return new DefaultParser . ArgumentList ( rawLine . substring ( remove . length ( ) + 1 , rawLine . length ( ) ) , words , line . wordIndex ( ) - 1 , line . wordCursor ( ) , line . cursor ( ) - remove . length ( ) + 1 ) ; } else { return new DefaultParser . ArgumentList ( "" , Collections . emptyList ( ) , 0 , 0 , 0 ) ; } }
Extract the command specific portions of the given line .
191
11
138,387
protected void convert ( ) { if ( _image == null ) { return ; } // obtain the target color and offset try { BufferedImage image ; if ( _tabs . getSelectedIndex ( ) == 0 ) { // All recolorings from file. image = getAllRecolors ( _labelColors . isSelected ( ) ) ; if ( image == null ) { return ; } } else if ( _tabs . getSelectedIndex ( ) == 1 ) { ArrayList < Colorization > zations = Lists . newArrayList ( ) ; if ( _classList1 . getSelectedItem ( ) != NONE ) { zations . add ( _colRepo . getColorization ( ( String ) _classList1 . getSelectedItem ( ) , ( String ) _colorList1 . getSelectedItem ( ) ) ) ; } if ( _classList2 . getSelectedItem ( ) != NONE ) { zations . add ( _colRepo . getColorization ( ( String ) _classList2 . getSelectedItem ( ) , ( String ) _colorList2 . getSelectedItem ( ) ) ) ; } if ( _classList3 . getSelectedItem ( ) != NONE ) { zations . add ( _colRepo . getColorization ( ( String ) _classList3 . getSelectedItem ( ) , ( String ) _colorList3 . getSelectedItem ( ) ) ) ; } if ( _classList4 . getSelectedItem ( ) != NONE ) { zations . add ( _colRepo . getColorization ( ( String ) _classList4 . getSelectedItem ( ) , ( String ) _colorList4 . getSelectedItem ( ) ) ) ; } image = ImageUtil . recolorImage ( _image , zations . toArray ( new Colorization [ zations . size ( ) ] ) ) ; } else { // Manual recoloring int color = Integer . parseInt ( _source . getText ( ) , 16 ) ; float hueD = _hueD . getValue ( ) ; float satD = _saturationD . getValue ( ) ; float valD = _valueD . getValue ( ) ; float [ ] dists = new float [ ] { hueD , satD , valD } ; float hueO = _hueO . getValue ( ) ; float satO = _saturationO . getValue ( ) ; float valO = _valueO . getValue ( ) ; float [ ] offsets = new float [ ] { hueO , satO , valO } ; image = ImageUtil . recolorImage ( _image , new Color ( color ) , dists , offsets ) ; } _newImage . setIcon ( new ImageIcon ( image ) ) ; _status . setText ( "Recolored image." ) ; repaint ( ) ; } catch ( NumberFormatException nfe ) { _status . setText ( "Invalid value: " + nfe . getMessage ( ) ) ; } }
Performs colorizations .
655
5
138,388
public BufferedImage getAllRecolors ( boolean label ) { if ( _colRepo == null ) { return null ; } ColorPository . ClassRecord colClass = _colRepo . getClassRecord ( ( String ) _classList . getSelectedItem ( ) ) ; int classId = colClass . classId ; BufferedImage img = new BufferedImage ( _image . getWidth ( ) , _image . getHeight ( ) * colClass . colors . size ( ) , BufferedImage . TYPE_INT_ARGB ) ; Graphics gfx = img . getGraphics ( ) ; gfx . setColor ( Color . BLACK ) ; int y = 0 ; Integer [ ] sortedKeys = colClass . colors . keySet ( ) . toArray ( new Integer [ colClass . colors . size ( ) ] ) ; Arrays . sort ( sortedKeys ) ; for ( int key : sortedKeys ) { Colorization coloriz = _colRepo . getColorization ( classId , key ) ; BufferedImage subImg = ImageUtil . recolorImage ( _image , coloriz . rootColor , coloriz . range , coloriz . offsets ) ; gfx . drawImage ( subImg , 0 , y , null , null ) ; if ( label ) { ColorRecord crec = _colRepo . getColorRecord ( classId , key ) ; gfx . drawString ( crec . name , 2 , y + gfx . getFontMetrics ( ) . getHeight ( ) + 2 ) ; gfx . drawRect ( 0 , y , _image . getWidth ( ) - 1 , _image . getHeight ( ) ) ; } y += subImg . getHeight ( ) ; } return img ; }
Gets an image with all recolorings of the selection colorization class .
374
16
138,389
public void setColorizeFile ( File path ) { try { if ( path . getName ( ) . endsWith ( "xml" ) ) { ColorPositoryParser parser = new ColorPositoryParser ( ) ; _colRepo = ( ColorPository ) ( parser . parseConfig ( path ) ) ; } else { _colRepo = ColorPository . loadColorPository ( new FileInputStream ( path ) ) ; } _classList . removeAllItems ( ) ; _classList1 . removeAllItems ( ) ; _classList1 . addActionListener ( new ActionListener ( ) { public void actionPerformed ( ActionEvent event ) { setupColors ( _colorList1 , ( String ) _classList1 . getSelectedItem ( ) ) ; } } ) ; _classList2 . removeAllItems ( ) ; _classList2 . addActionListener ( new ActionListener ( ) { public void actionPerformed ( ActionEvent event ) { setupColors ( _colorList2 , ( String ) _classList2 . getSelectedItem ( ) ) ; } } ) ; _classList3 . removeAllItems ( ) ; _classList3 . addActionListener ( new ActionListener ( ) { public void actionPerformed ( ActionEvent event ) { setupColors ( _colorList3 , ( String ) _classList3 . getSelectedItem ( ) ) ; } } ) ; _classList4 . removeAllItems ( ) ; _classList4 . addActionListener ( new ActionListener ( ) { public void actionPerformed ( ActionEvent event ) { setupColors ( _colorList4 , ( String ) _classList4 . getSelectedItem ( ) ) ; } } ) ; Iterator < ColorPository . ClassRecord > iter = _colRepo . enumerateClasses ( ) ; ArrayList < String > names = Lists . newArrayList ( ) ; while ( iter . hasNext ( ) ) { String str = iter . next ( ) . name ; names . add ( str ) ; } _classList1 . addItem ( NONE ) ; _classList2 . addItem ( NONE ) ; _classList3 . addItem ( NONE ) ; _classList4 . addItem ( NONE ) ; Collections . sort ( names ) ; for ( String name : names ) { _classList . addItem ( name ) ; _classList1 . addItem ( name ) ; _classList2 . addItem ( name ) ; _classList3 . addItem ( name ) ; _classList4 . addItem ( name ) ; } _classList . setSelectedIndex ( 0 ) ; _classList1 . setSelectedIndex ( 0 ) ; _classList2 . setSelectedIndex ( 0 ) ; _classList3 . setSelectedIndex ( 0 ) ; _classList4 . setSelectedIndex ( 0 ) ; _colFilePath . setText ( path . getPath ( ) ) ; CONFIG . setValue ( LAST_COLORIZATION_KEY , path . getAbsolutePath ( ) ) ; } catch ( Exception ex ) { _status . setText ( "Error opening colorization file: " + ex ) ; } }
Loads up the colorization classes from the specified file .
682
12
138,390
public static String stripControlCharacters ( String rawValue ) { if ( rawValue == null ) { return null ; } String value = replaceEntities ( rawValue ) ; boolean hasControlChars = false ; for ( int i = value . length ( ) - 1 ; i >= 0 ; i -- ) { if ( Character . isISOControl ( value . charAt ( i ) ) ) { hasControlChars = true ; break ; } } if ( ! hasControlChars ) { return value ; } StringBuilder buf = new StringBuilder ( value . length ( ) ) ; int i = 0 ; // Skip initial control characters (i.e. left trim) for ( ; i < value . length ( ) ; i ++ ) { if ( ! Character . isISOControl ( value . charAt ( i ) ) ) { break ; } } // Copy non control characters and substitute control characters with // a space. The last control characters are trimmed. boolean suppressingControlChars = false ; for ( ; i < value . length ( ) ; i ++ ) { if ( Character . isISOControl ( value . charAt ( i ) ) ) { suppressingControlChars = true ; continue ; } else { if ( suppressingControlChars ) { suppressingControlChars = false ; buf . append ( ' ' ) ; } buf . append ( value . charAt ( i ) ) ; } } return buf . toString ( ) ; }
Strip a String of it s ISO control characters .
299
11
138,391
public static void write ( BufferedImage image , OutputStream out ) throws IOException { DataOutputStream dout = new DataOutputStream ( out ) ; // write the image dimensions int width = image . getWidth ( ) , height = image . getHeight ( ) ; dout . writeInt ( width ) ; dout . writeInt ( height ) ; // write the color model information IndexColorModel cmodel = ( IndexColorModel ) image . getColorModel ( ) ; int tpixel = cmodel . getTransparentPixel ( ) ; dout . writeInt ( tpixel ) ; int msize = cmodel . getMapSize ( ) ; int [ ] map = new int [ msize ] ; cmodel . getRGBs ( map ) ; dout . writeInt ( msize ) ; for ( int element : map ) { dout . writeInt ( element ) ; } // write the raster data DataBufferByte dbuf = ( DataBufferByte ) image . getRaster ( ) . getDataBuffer ( ) ; byte [ ] data = dbuf . getData ( ) ; if ( data . length != width * height ) { String errmsg = "Raster data not same size as image! [" + width + "x" + height + " != " + data . length + "]" ; throw new IllegalStateException ( errmsg ) ; } dout . write ( data ) ; dout . flush ( ) ; }
Writes the supplied image to the supplied output stream .
303
11
138,392
public List < AmqpTableEntry > getEntries ( String key ) { if ( ( key == null ) || ( tableEntryArray == null ) ) { return null ; } List < AmqpTableEntry > entries = new ArrayList < AmqpTableEntry > ( ) ; for ( AmqpTableEntry entry : tableEntryArray ) { if ( entry . key . equals ( key ) ) { entries . add ( entry ) ; } } return entries ; }
Returns a list of AmqpTableEntry objects that matches the specified key . If a null key is passed in then a null is returned . Also if the internal structure is null then a null is returned .
100
42
138,393
public void update ( long numProcessedDuringStep ) { if ( this . closed ) { throw new ETAPrinterException ( "You cannot update a closed ETAPrinter!" ) ; } DateTime now = DateTime . now ( ) ; ItemsDuration itemsDuration = null ; if ( numProcessedDuringStep > 0 ) { long stepDuration = new Duration ( this . lastStep , now ) . getMillis ( ) ; int numItems = 1 ; do { long duration = stepDuration / ( numProcessedDuringStep / numItems ) ; itemsDuration = new ItemsDuration ( numItems , duration ) ; numItems ++ ; } while ( itemsDuration . durationMillis == 0 ) ; } this . lastStep = now ; this . numProcessed += numProcessedDuringStep ; if ( this . numProcessed == this . totalElementsToProcess ) { this . close ( ) ; } else { this . print ( itemsDuration ) ; } }
Updates and prints the progress bar with the new values .
202
12
138,394
public static TagAttributeInfo getIdAttribute ( TagAttributeInfo a [ ] ) { for ( int i = 0 ; i < a . length ; i ++ ) { if ( a [ i ] . getName ( ) . equals ( ID ) ) { return a [ i ] ; } } return null ; // no such attribute }
Convenience static method that goes through an array of TagAttributeInfo objects and looks for id .
68
20
138,395
protected static < T > Class < T > firstKnownType ( T ... objects ) { for ( T obj : objects ) if ( obj != null ) return ( Class < T > ) obj . getClass ( ) ; return null ; }
Utility method to allow subclasses to extract type from known variables .
49
14
138,396
public ColorRecord [ ] enumerateColors ( String className ) { // make sure the class exists ClassRecord record = getClassRecord ( className ) ; if ( record == null ) { return null ; } // create the array ColorRecord [ ] crecs = new ColorRecord [ record . colors . size ( ) ] ; Iterator < ColorRecord > iter = record . colors . values ( ) . iterator ( ) ; for ( int ii = 0 ; iter . hasNext ( ) ; ii ++ ) { crecs [ ii ] = iter . next ( ) ; } return crecs ; }
Returns an array containing the records for the colors in the specified class .
124
14
138,397
public int [ ] enumerateColorIds ( String className ) { // make sure the class exists ClassRecord record = getClassRecord ( className ) ; if ( record == null ) { return null ; } int [ ] cids = new int [ record . colors . size ( ) ] ; Iterator < ColorRecord > crecs = record . colors . values ( ) . iterator ( ) ; for ( int ii = 0 ; crecs . hasNext ( ) ; ii ++ ) { cids [ ii ] = crecs . next ( ) . colorId ; } return cids ; }
Returns an array containing the ids of the colors in the specified class .
124
15
138,398
public ColorRecord getRandomStartingColor ( String className , Random rand ) { // make sure the class exists ClassRecord record = getClassRecord ( className ) ; return ( record == null ) ? null : record . randomStartingColor ( rand ) ; }
Returns a random starting color from the specified color class .
53
11
138,399
public Colorization getColorization ( int classId , int colorId ) { ColorRecord color = getColorRecord ( classId , colorId ) ; return ( color == null ) ? null : color . getColorization ( ) ; }
Looks up a colorization by id .
49
8