idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
138,700
public JSONArray execute ( ) throws Exception { try { JSONArray retVal = Client . getInstance ( port ) . map ( toString ( ) ) ; return retVal ; } catch ( Exception e ) { throw new Exception ( queryStringRepresentation + ": " + e . getMessage ( ) ) ; } }
Execute a series of commands
66
6
138,701
protected Object getInstantiatedClass ( String query ) { if ( query . equals ( Constants . UIAUTOMATOR_UIDEVICE ) ) { return device ; } return null ; }
Implementation of getInstantiatedClass that returns a UiDevice if one is requested
40
17
138,702
public synchronized void setHistory ( CollectHistory history ) { history_ = Optional . of ( history ) ; history_ . ifPresent ( getApi ( ) :: setHistory ) ; data_ . initWithHistoricalData ( history , getDecoratorLookBack ( ) ) ; }
Set the history module that the push processor is to use .
59
12
138,703
@ Override protected synchronized CollectionContext beginCollection ( DateTime now ) { data_ . startNewCycle ( now , getDecoratorLookBack ( ) ) ; return new CollectionContext ( ) { final Map < GroupName , Alert > alerts = new HashMap <> ( ) ; @ Override public Consumer < Alert > alertManager ( ) { return ( Alert alert ) -> { Alert combined = combine_alert_with_past_ ( alert , alerts_ ) ; alerts . put ( combined . getName ( ) , combined ) ; } ; } @ Override public MutableTimeSeriesCollectionPair tsdata ( ) { return data_ ; } /** * Store a newly completed collection cycle. */ @ Override public void commit ( ) { alerts_ = unmodifiableMap ( alerts ) ; try { getHistory ( ) . ifPresent ( history -> history . add ( getCollectionData ( ) ) ) ; } catch ( Exception ex ) { logger . log ( Level . WARNING , "unable to add collection data to history (dropped)" , ex ) ; } } } ; }
Begin a new collection cycle .
227
6
138,704
private static Alert combine_alert_with_past_ ( Alert alert , Map < GroupName , Alert > previous ) { Alert result = Optional . ofNullable ( previous . get ( alert . getName ( ) ) ) . map ( ( prev ) - > prev . extend ( alert ) ) . orElse ( alert ) ; logger . log ( Level . FINE , "emitting alert {0} -> {1}" , new Object [ ] { result . getName ( ) , result . getAlertState ( ) . name ( ) } ) ; return result ; }
Combine a new alert with its previous state .
119
10
138,705
public static synchronized PushMetricRegistryInstance create ( Supplier < DateTime > now , boolean has_config , EndpointRegistration api ) { return new PushMetricRegistryInstance ( now , has_config , api ) ; }
Create a plain uninitialized metric registry .
49
8
138,706
public static Mirage newNinePatchContaining ( NinePatch ninePatch , Rectangle content ) { Rectangle bounds = ninePatch . getBoundsSurrounding ( content ) ; Mirage mirage = new NinePatchMirage ( ninePatch , bounds . width , bounds . height ) ; return new TransformedMirage ( mirage , AffineTransform . getTranslateInstance ( bounds . x , bounds . y ) , false ) ; }
Returns a new Mirage that s a NinePatch stretched and positioned to contain the given Rectangle .
90
19
138,707
public static boolean isDisjoint ( Collection < Range > ranges ) { List < Range > rangesList = new ArrayList < Range > ( ranges . size ( ) ) ; rangesList . addAll ( ranges ) ; Collections . sort ( rangesList ) ; for ( int i = 0 ; i < rangesList . size ( ) - 1 ; i ++ ) { Range rCurrent = rangesList . get ( i ) ; Range rNext = rangesList . get ( i + 1 ) ; if ( rCurrent . overlapsWith ( rNext ) ) { return false ; } } return true ; }
Checks weather the given set of ranges are disjoint i . e . none of the ranges overlap .
124
22
138,708
private static EscapeStringResult escapeString ( String s , char quote ) { final String [ ] octal_strings = { "\\0" , "\\001" , "\\002" , "\\003" , "\\004" , "\\005" , "\\006" , "\\a" , "\\b" , "\\t" , "\\n" , "\\v" , "\\f" , "\\r" , "\\016" , "\\017" , "\\020" , "\\021" , "\\022" , "\\023" , "\\024" , "\\025" , "\\026" , "\\027" , "\\030" , "\\031" , "\\032" , "\\033" , "\\034" , "\\035" , "\\036" , "\\037" , } ; StringBuilder result = new StringBuilder ( s ) ; boolean needQuotes = s . isEmpty ( ) ; for ( int i = 0 , next_i ; i < result . length ( ) ; i = next_i ) { final int code_point = result . codePointAt ( i ) ; next_i = result . offsetByCodePoints ( i , 1 ) ; if ( code_point == 0 ) { result . replace ( i , next_i , "\\0" ) ; next_i = i + 2 ; needQuotes = true ; } else if ( code_point == ( int ) ' ' ) { result . replace ( i , next_i , "\\\\" ) ; next_i = i + 2 ; needQuotes = true ; } else if ( code_point == ( int ) quote ) { result . replace ( i , next_i , "\\" + quote ) ; next_i = i + 2 ; needQuotes = true ; } else if ( code_point < 32 ) { String octal = octal_strings [ code_point ] ; result . replace ( i , next_i , octal ) ; next_i = i + octal . length ( ) ; needQuotes = true ; } else if ( code_point >= 65536 ) { String repl = String . format ( "\\U%08x" , code_point ) ; result . replace ( i , next_i , repl ) ; next_i = i + repl . length ( ) ; needQuotes = true ; } else if ( code_point >= 128 ) { String repl = String . format ( "\\u%04x" , code_point ) ; result . replace ( i , next_i , repl ) ; next_i = i + repl . length ( ) ; needQuotes = true ; } } return new EscapeStringResult ( needQuotes , result ) ; }
Escape a string configuration element .
587
7
138,709
public static StringBuilder quotedString ( String s ) { final EscapeStringResult escapeString = escapeString ( s , ' ' ) ; final StringBuilder result = escapeString . buffer ; result . insert ( 0 , ' ' ) ; result . append ( ' ' ) ; return result ; }
Create a quoted string configuration element .
59
7
138,710
public static StringBuilder maybeQuoteIdentifier ( String s ) { final EscapeStringResult escapeString = escapeString ( s , ' ' ) ; final StringBuilder result = escapeString . buffer ; final boolean need_quotes = s . isEmpty ( ) || escapeString . needQuotes || KEYWORDS . contains ( s ) || ! IDENTIFIER_MATCHER . test ( s ) ; if ( need_quotes ) { result . insert ( 0 , ' ' ) ; result . append ( ' ' ) ; } return result ; }
Create an identifier configuration element .
114
6
138,711
public static StringBuilder durationConfigString ( Duration duration ) { Duration remainder = duration ; long days = remainder . getStandardDays ( ) ; remainder = remainder . minus ( Duration . standardDays ( days ) ) ; long hours = remainder . getStandardHours ( ) ; remainder = remainder . minus ( Duration . standardHours ( hours ) ) ; long minutes = remainder . getStandardMinutes ( ) ; remainder = remainder . minus ( Duration . standardMinutes ( minutes ) ) ; long seconds = remainder . getStandardSeconds ( ) ; remainder = remainder . minus ( Duration . standardSeconds ( seconds ) ) ; if ( ! remainder . isEqual ( Duration . ZERO ) ) Logger . getLogger ( ConfigSupport . class . getName ( ) ) . log ( Level . WARNING , "Duration is more precise than configuration will handle: {0}, dropping remainder: {1}" , new Object [ ] { duration , remainder } ) ; StringBuilder result = new StringBuilder ( ) ; if ( days != 0 ) { if ( result . length ( ) != 0 ) result . append ( ' ' ) ; result . append ( days ) . append ( ' ' ) ; } if ( hours != 0 ) { if ( result . length ( ) != 0 ) result . append ( ' ' ) ; result . append ( hours ) . append ( ' ' ) ; } if ( minutes != 0 ) { if ( result . length ( ) != 0 ) result . append ( ' ' ) ; result . append ( minutes ) . append ( ' ' ) ; } if ( result . length ( ) == 0 || seconds != 0 ) { if ( result . length ( ) != 0 ) result . append ( ' ' ) ; result . append ( seconds ) . append ( ' ' ) ; } return result ; }
Convert duration to an representation accepted by Configuration parser .
373
11
138,712
public < R > R download ( String uri , ContentHandler < BasicHttpResponse , R > handler ) throws RedmineException { final HttpGet request = new HttpGet ( uri ) ; return errorCheckingCommunicator . sendRequest ( request , handler ) ; }
Downloads a redmine content .
58
7
138,713
public String upload ( InputStream content ) throws RedmineException { final URI uploadURI = getURIConfigurator ( ) . getUploadURI ( ) ; final HttpPost request = new HttpPost ( uploadURI ) ; final AbstractHttpEntity entity = new InputStreamEntity ( content , - 1 ) ; /* Content type required by a Redmine */ entity . setContentType ( "application/octet-stream" ) ; request . setEntity ( entity ) ; final String result = getCommunicator ( ) . sendRequest ( request ) ; return parseResponse ( result , "upload" , RedmineJSONParser . UPLOAD_TOKEN_PARSER ) ; }
UPloads content on a server .
142
7
138,714
public < T > List < T > getObjectsList ( Class < T > objectClass , Collection < ? extends NameValuePair > params ) throws RedmineException { final EntityConfig < T > config = getConfig ( objectClass ) ; final List < T > result = new ArrayList < T > ( ) ; final List < NameValuePair > newParams = new ArrayList < NameValuePair > ( params ) ; newParams . add ( new BasicNameValuePair ( "limit" , String . valueOf ( objectsPerPage ) ) ) ; int offset = 0 ; int totalObjectsFoundOnServer ; do { List < NameValuePair > paramsList = new ArrayList < NameValuePair > ( newParams ) ; paramsList . add ( new BasicNameValuePair ( "offset" , String . valueOf ( offset ) ) ) ; final URI uri = getURIConfigurator ( ) . getObjectsURI ( objectClass , paramsList ) ; logger . debug ( uri . toString ( ) ) ; final HttpGet http = new HttpGet ( uri ) ; final String response = getCommunicator ( ) . sendRequest ( http ) ; logger . debug ( "received: " + response ) ; final List < T > foundItems ; try { final JSONObject responseObject = RedmineJSONParser . getResponse ( response ) ; foundItems = JsonInput . getListOrNull ( responseObject , config . multiObjectName , config . parser ) ; result . addAll ( foundItems ) ; /* Necessary for trackers */ if ( ! responseObject . has ( KEY_TOTAL_COUNT ) ) { break ; } totalObjectsFoundOnServer = JsonInput . getInt ( responseObject , KEY_TOTAL_COUNT ) ; } catch ( JSONException e ) { throw new RedmineFormatException ( e ) ; } if ( foundItems . size ( ) == 0 ) { break ; } offset += foundItems . size ( ) ; } while ( offset < totalObjectsFoundOnServer ) ; return result ; }
Returns an object list .
447
5
138,715
@ Nonnull protected Completer discoverCompleter ( ) { log . debug ( "Discovering completer" ) ; // TODO: Could probably use CliProcessorAware to avoid re-creating this CliProcessor cli = new CliProcessor ( ) ; cli . addBean ( this ) ; List < ArgumentDescriptor > argumentDescriptors = cli . getArgumentDescriptors ( ) ; Collections . sort ( argumentDescriptors ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Argument descriptors:" ) ; argumentDescriptors . forEach ( descriptor -> log . debug ( " {}" , descriptor ) ) ; } List < Completer > completers = new LinkedList <> ( ) ; // attempt to resolve @Complete on each argument argumentDescriptors . forEach ( descriptor -> { AccessibleObject accessible = descriptor . getSetter ( ) . getAccessible ( ) ; if ( accessible != null ) { Complete complete = accessible . getAnnotation ( Complete . class ) ; if ( complete != null ) { Completer completer = namedCompleters . get ( complete . value ( ) ) ; checkState ( completer != null , "Missing named completer: %s" , complete . value ( ) ) ; completers . add ( completer ) ; } } } ) ; // short-circuit if no completers detected if ( completers . isEmpty ( ) ) { return NullCompleter . INSTANCE ; } if ( log . isDebugEnabled ( ) ) { log . debug ( "Discovered completers:" ) ; completers . forEach ( completer -> { log . debug ( " {}" , completer ) ; } ) ; } // append terminal completer for strict completers . add ( NullCompleter . INSTANCE ) ; ArgumentCompleter completer = new ArgumentCompleter ( completers ) ; completer . setStrict ( true ) ; return completer ; }
Discover the completer for the command .
428
8
138,716
public static SimpleGraph < String , DefaultEdge > getSimpleGraphFromUser ( ) { Scanner sc = new Scanner ( System . in ) ; SimpleGraph < String , DefaultEdge > graph = new SimpleGraph < String , DefaultEdge > ( DefaultEdge . class ) ; // input number of vertices int verticeAmount ; do { System . out . print ( "Enter the number of vertices (more than one): " ) ; verticeAmount = sc . nextInt ( ) ; } while ( verticeAmount <= 1 ) ; // input vertices for ( int i = 1 ; i <= verticeAmount ; i ++ ) { System . out . print ( "Enter vertex name " + i + ": " ) ; String input = sc . next ( ) ; if ( graph . vertexSet ( ) . contains ( input ) ) { System . err . println ( "vertex with that name already exists" ) ; i -- ; } else { graph . addVertex ( input ) ; } } // input edges System . out . println ( "\nEnter edge (name => name)" ) ; String userWantsToContinue ; do { String e1 , e2 ; do { System . out . print ( "Edge from: " ) ; e1 = sc . next ( ) ; } while ( ! graph . vertexSet ( ) . contains ( e1 ) ) ; do { System . out . print ( "Edge to: " ) ; e2 = sc . next ( ) ; } while ( ! graph . vertexSet ( ) . contains ( e2 ) ) ; graph . addEdge ( e1 , e2 ) ; // add another edge? System . out . print ( "Add more edges? (y/n): " ) ; userWantsToContinue = sc . next ( ) ; } while ( userWantsToContinue . equals ( "y" ) || userWantsToContinue . equals ( "yes" ) || userWantsToContinue . equals ( "1" ) ) ; return graph ; }
Asks the user to input an graph
425
8
138,717
public void getTrimmedBounds ( Rectangle tbounds ) { tbounds . setBounds ( _tbounds . x , _tbounds . y , _mirage . getWidth ( ) , _mirage . getHeight ( ) ) ; }
Fills in the bounds of the trimmed image within the coordinate system defined by the complete virtual tile .
58
20
138,718
public Rectangle getBoundsSurrounding ( Rectangle content ) { Rectangle bounds = new Rectangle ( content ) ; bounds . width += _leftPad + _rightPad ; bounds . height += _topPad + _bottomPad ; bounds . x -= _leftPad ; bounds . y -= _topPad ; return bounds ; }
Returns a rectangle describing the bounds of this NinePatch when drawn such that it frames the given content rectangle .
70
21
138,719
protected static Rectangle getRectangle ( BufferedImage img , boolean stretch ) { Rectangle rect = new Rectangle ( 0 , 0 , img . getWidth ( ) - 2 , img . getHeight ( ) - 2 ) ; for ( int xx = 1 ; xx < rect . width + 1 ; xx ++ ) { if ( ImageUtil . hitTest ( img , xx , stretch ? 0 : img . getHeight ( ) - 1 ) ) { rect . x = xx - 1 ; rect . width -= rect . x ; break ; } } for ( int xx = img . getWidth ( ) - 1 ; xx >= rect . x + 1 ; xx -- ) { if ( ImageUtil . hitTest ( img , xx , stretch ? 0 : img . getHeight ( ) - 1 ) ) { rect . width = xx - rect . x ; break ; } } for ( int yy = 1 ; yy < rect . height + 1 ; yy ++ ) { if ( ImageUtil . hitTest ( img , stretch ? 0 : img . getWidth ( ) - 1 , yy ) ) { rect . y = yy - 1 ; rect . height -= rect . y ; break ; } } for ( int yy = img . getHeight ( ) - 1 ; yy >= rect . y + 1 ; yy -- ) { if ( ImageUtil . hitTest ( img , stretch ? 0 : img . getWidth ( ) - 1 , yy ) ) { rect . height = yy - rect . y ; break ; } } return rect ; }
Parses the image to find the bounds of the rectangle defined by pixels on the outside .
332
19
138,720
public void appendDirtySprite ( Sprite sprite , int tx , int ty ) { DirtyItem item = getDirtyItem ( ) ; item . init ( sprite , tx , ty ) ; _items . add ( item ) ; }
Appends the dirty sprite at the given coordinates to the dirty item list .
49
15
138,721
public void appendDirtyObject ( SceneObject scobj ) { DirtyItem item = getDirtyItem ( ) ; item . init ( scobj , scobj . info . x , scobj . info . y ) ; _items . add ( item ) ; }
Appends the dirty object tile at the given coordinates to the dirty item list .
55
16
138,722
public void paintAndClear ( Graphics2D gfx ) { int icount = _items . size ( ) ; for ( int ii = 0 ; ii < icount ; ii ++ ) { DirtyItem item = _items . get ( ii ) ; item . paint ( gfx ) ; item . clear ( ) ; _freelist . add ( item ) ; } _items . clear ( ) ; }
Paints all the dirty items in this list using the supplied graphics context . The items are removed from the dirty list after being painted and the dirty list ends up empty .
84
34
138,723
public void clear ( ) { for ( int icount = _items . size ( ) ; icount > 0 ; icount -- ) { DirtyItem item = _items . remove ( 0 ) ; item . clear ( ) ; _freelist . add ( item ) ; } }
Clears out any items that were in this list .
58
11
138,724
private Intermediate mapAndReduce ( Context ctx ) { /* Fetch each metric wildcard and add it to the to-be-processed list. */ final List < Map . Entry < Tags , MetricValue > > matcher_tsvs = matchers_ . stream ( ) . flatMap ( m -> m . filter ( ctx ) ) . map ( named_entry -> SimpleMapEntry . create ( named_entry . getKey ( ) . getTags ( ) , named_entry . getValue ( ) ) ) . collect ( Collectors . toList ( ) ) ; /* Resolve each expression. */ final Map < Boolean , List < TimeSeriesMetricDeltaSet > > expr_tsvs_map = exprs_ . stream ( ) . map ( expr -> expr . apply ( ctx ) ) . collect ( Collectors . partitioningBy ( TimeSeriesMetricDeltaSet :: isVector ) ) ; final List < TimeSeriesMetricDeltaSet > expr_tsvs = expr_tsvs_map . getOrDefault ( true , Collections . emptyList ( ) ) ; final Optional < T > scalar = expr_tsvs_map . getOrDefault ( false , Collections . emptyList ( ) ) . stream ( ) . map ( tsv_set -> map_ ( tsv_set . asScalar ( ) . get ( ) ) ) . reduce ( this :: reducer_ ) ; /* * Reduce everything using the reducer (in the derived class). */ return new Intermediate ( scalar , unmodifiableMap ( aggregation_ . apply ( matcher_tsvs . stream ( ) , expr_tsvs . stream ( ) . flatMap ( TimeSeriesMetricDeltaSet :: streamAsMap ) , Map . Entry :: getKey , Map . Entry :: getKey , Map . Entry :: getValue , Map . Entry :: getValue ) . entrySet ( ) . stream ( ) . map ( entry -> { return entry . getValue ( ) . stream ( ) . map ( this :: map_ ) . reduce ( this :: reducer_ ) . map ( v -> SimpleMapEntry . create ( entry . getKey ( ) , v ) ) ; } ) . flatMap ( opt -> opt . map ( Stream :: of ) . orElseGet ( Stream :: empty ) ) . collect ( Collectors . toMap ( entry -> entry . getKey ( ) , entry -> entry . getValue ( ) ) ) ) ) ; }
Create a reduction of the matchers and expressions for a given context .
517
14
138,725
public List < Issue > getIssues ( Map < String , String > pParameters ) throws RedmineException { Set < NameValuePair > params = new HashSet < NameValuePair > ( ) ; for ( final Entry < String , String > param : pParameters . entrySet ( ) ) { params . add ( new BasicNameValuePair ( param . getKey ( ) , param . getValue ( ) ) ) ; } return transport . getObjectsList ( Issue . class , params ) ; }
Generic method to search for issues .
108
7
138,726
public void deleteRelation ( Integer id ) throws RedmineException { transport . deleteObject ( IssueRelation . class , Integer . toString ( id ) ) ; }
Delete Issue Relation with the given ID .
35
9
138,727
public Attachment uploadAttachment ( String fileName , String contentType , InputStream content ) throws RedmineException , IOException { final InputStream wrapper = new MarkedInputStream ( content , "uploadStream" ) ; final String token ; try { token = transport . upload ( wrapper ) ; final Attachment result = new Attachment ( ) ; result . setToken ( token ) ; result . setContentType ( contentType ) ; result . setFileName ( fileName ) ; return result ; } catch ( RedmineException e ) { unwrapIO ( e , "uploadStream" ) ; throw e ; } }
Uploads an attachement .
129
7
138,728
private void unwrapIO ( RedmineException orig , String tag ) throws IOException { Throwable e = orig ; while ( e != null ) { if ( e instanceof MarkedIOException ) { final MarkedIOException marked = ( MarkedIOException ) e ; if ( tag . equals ( marked . getTag ( ) ) ) throw marked . getIOException ( ) ; } e = e . getCause ( ) ; } }
Unwraps an IO .
92
6
138,729
public void addMembership ( Membership membership ) throws RedmineException { final Project project = membership . getProject ( ) ; if ( project == null ) throw new IllegalArgumentException ( "Project must be set" ) ; if ( membership . getUser ( ) == null ) throw new IllegalArgumentException ( "User must be set" ) ; transport . addChildEntry ( Project . class , getProjectKey ( project ) , membership ) ; }
Add a membership .
93
4
138,730
public void export ( Writer output , UndirectedGraph < V , E > g ) { export ( output , g , false ) ; }
Exports an undirected graph into a PLAIN text file in GML format .
29
18
138,731
public void export ( Writer output , DirectedGraph < V , E > g ) { export ( output , g , true ) ; }
Exports a directed graph into a PLAIN text file in GML format .
28
16
138,732
public void set ( final Iterable < String > strings ) { checkNotNull ( strings ) ; candidates . clear ( ) ; addAll ( strings ) ; }
Set completion strings ; replacing any existing .
33
8
138,733
public void addAll ( final Iterable < String > strings ) { checkNotNull ( strings ) ; for ( String string : strings ) { add ( string ) ; } }
Add all strings to existing candidates .
36
7
138,734
public void add ( final String string ) { checkNotNull ( string ) ; candidates . put ( string , candidate ( string ) ) ; }
Add a string to existing candidates .
29
7
138,735
public void add ( final String string , final Candidate candidate ) { checkNotNull ( string ) ; checkNotNull ( candidate ) ; candidates . put ( string , candidate ) ; }
Add string with specific completer .
37
7
138,736
protected void initNextPath ( long initStamp , long tickStamp ) { if ( _paths . size ( ) == 0 ) { _pable . pathCompleted ( tickStamp ) ; } else { _curPath = _paths . remove ( 0 ) ; _lastInit = initStamp ; _curPath . init ( _pableRep , initStamp ) ; _curPath . tick ( _pableRep , tickStamp ) ; } }
Initialize and start the next path in the sequence .
100
11
138,737
public static String getStatus ( String elementName , long percentage , double speed , String speedUnit , Duration eta ) { StringBuilder sb = new StringBuilder ( getBar ( percentage ) ) ; sb . append ( ( long ) speed ) ; if ( elementName != null ) { sb . append ( " " ) . append ( elementName ) ; } sb . append ( "/" ) . append ( speedUnit ) ; sb . append ( " ETA " ) . append ( FORMATTER . print ( eta . toPeriod ( ) ) ) ; return sb . toString ( ) ; }
Generate the full status .
131
6
138,738
protected static String getBar ( long percentage ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( percentage ) ; sb . append ( "% [" ) ; for ( int i = 0 ; i < 100 ; i ++ ) { if ( percentage == 100 || i < percentage - 1 ) { sb . append ( "=" ) ; } else if ( i == percentage - 1 ) { sb . append ( ">" ) ; } else { sb . append ( " " ) ; } } sb . append ( "] " ) ; return sb . toString ( ) ; }
Generates the progress bar for the given percentage
129
9
138,739
@ Override public void processConnect ( WebSocketChannel channel , WSURI location , String [ ] protocols ) { nextHandler . processConnect ( channel , location , protocols ) ; }
Process connect request to uri and protocol specified
37
9
138,740
@ Override public synchronized void processAuthorize ( WebSocketChannel channel , String authorizeToken ) { nextHandler . processAuthorize ( channel , authorizeToken ) ; }
Send authorize token to the Gateway
34
6
138,741
public tsfile_data data ( TimeSeriesCollection ts_data ) { final dictionary_delta dict_delta = new dictionary_delta ( ) ; dict_delta . gdd = new path_dictionary_delta [ 0 ] ; dict_delta . mdd = new path_dictionary_delta [ 0 ] ; dict_delta . sdd = new strval_dictionary_delta [ 0 ] ; dict_delta . tdd = new tag_dictionary_delta [ 0 ] ; final List < tsfile_record > records = new ArrayList <> ( ) ; final Iterator < TimeSeriesValue > tsv_iter = ts_data . getTSValues ( ) . stream ( ) . iterator ( ) ; while ( tsv_iter . hasNext ( ) ) { final TimeSeriesValue tsv = tsv_iter . next ( ) ; tsfile_record record = new tsfile_record ( ) ; record . group_ref = simpleGroupPath_index ( dict_delta , tsv . getGroup ( ) . getPath ( ) ) ; record . tag_ref = tags_index ( dict_delta , tsv . getGroup ( ) . getTags ( ) ) ; record . metrics = tsv . getMetrics ( ) . entrySet ( ) . stream ( ) . map ( entry -> { tsfile_record_entry tre = new tsfile_record_entry ( ) ; tre . metric_ref = metricName_index ( dict_delta , entry . getKey ( ) ) ; tre . v = metric_value_ ( dict_delta , entry . getValue ( ) ) ; return tre ; } ) . toArray ( tsfile_record_entry [ ] :: new ) ; records . add ( record ) ; } tsfile_data result = new tsfile_data ( ) ; result . records = records . stream ( ) . toArray ( tsfile_record [ ] :: new ) ; result . ts = timestamp ( ts_data . getTimestamp ( ) ) ; if ( dict_delta . gdd . length > 0 || dict_delta . mdd . length > 0 || dict_delta . sdd . length > 0 || dict_delta . tdd . length > 0 ) result . dd = dict_delta ; return result ; }
Transform a TimeSeriesCollection into the XDR serialized form .
503
13
138,742
public static < T > Iterable < T > simpleIterable ( final Iterable < T > iterable ) { requireNonNull ( iterable ) ; return ( ) -> iterable . iterator ( ) ; }
Wraps any iterable into a generic iterable object . This is useful for using complex iterables such as FluentIterable with libraries that use reflection to determine bean definitions such as Jackson .
44
39
138,743
public static < T > Iterable < T > distinct ( final Iterable < T > iterable ) { requireNonNull ( iterable ) ; return ( ) -> Iterators2 . distinct ( iterable . iterator ( ) ) ; }
If we can assume the iterable is sorted return the distinct elements . This only works if the data provided is sorted .
49
24
138,744
public String encodeAuthAmqPlain ( String username , String password ) { AmqpBuffer bytes = new AmqpBuffer ( ) ; bytes . putShortString ( "LOGIN" ) ; bytes . putTypeIdentifier ( "Longstr" ) ; bytes . putLongString ( username ) ; bytes . putShortString ( "PASSWORD" ) ; bytes . putTypeIdentifier ( "Longstr" ) ; bytes . putLongString ( password ) ; bytes . flip ( ) ; int len = bytes . remaining ( ) ; StringBuilder builder = new StringBuilder ( ) ; for ( int i = 0 ; i < len ; i ++ ) { builder . append ( ( char ) ( bytes . getUnsigned ( ) ) ) ; } String s = builder . toString ( ) ; return s ; }
Encodes the AMQPLAIN authentication response as an AmqpArguments
172
16
138,745
private Arg [ ] getMethodArguments ( List < Parameter > param ) { Arg [ ] val = new Arg [ param . size ( ) ] ; for ( int i = 0 ; i < param . size ( ) ; i ++ ) { String type = param . get ( i ) . type ; Arg arg = new Arg ( ) ; arg . type = type ; arg . name = param . get ( i ) . name ; Object v = null ; String type1 = null ; try { type1 = this . getMappedType ( type ) ; v = getObjectOfType ( type1 ) ; } catch ( Exception e ) { throw new IllegalStateException ( "type codec failed for type " + type + " for domain " + e . getMessage ( ) ) ; } // support unpacking of consecutive bits from a single byte this . bitCount = ( byte ) ( ( type1 == "Bit" ) ? this . bitCount + 1 : 0 ) ; arg . value = v ; val [ i ] = arg ; } return val ; }
Decodes arguments given a method s parameter list
221
9
138,746
public AmqpFrame getFrame ( ) { int pos = this . position ( ) ; AmqpMethod method = new AmqpMethod ( ) ; int classIndex ; AmqpFrame frame = new AmqpFrame ( ) ; // If there is at least one Frame in the buffer, attempt to decode it. if ( this . remaining ( ) > 7 ) { frame . setHeader ( this . getFrameHeader ( ) ) ; frame . setChannelId ( ( short ) frame . getHeader ( ) . channel ) ; frame . setType ( ( short ) frame . getHeader ( ) . frameType ) ; // the buffer must have an additional byte for the Frame end marker if ( this . remaining ( ) >= frame . getHeader ( ) . size + 1 ) { switch ( frame . getType ( ) ) { case AmqpConstants . FRAME_BODY : WrappedByteBuffer body = new AmqpBuffer ( ) ; // copy body into new Buffer int end = this . position ( ) + ( int ) frame . getHeader ( ) . size ; while ( position ( ) < end ) { body . put ( get ( ) ) ; } frame . setBody ( body ) ; frame . setMethodName ( "body" ) ; break ; case AmqpConstants . FRAME_HEADER : classIndex = this . getUnsignedShort ( ) ; @ SuppressWarnings ( "unused" ) short weight = ( short ) this . getUnsignedShort ( ) ; @ SuppressWarnings ( "unused" ) long bodySize = this . getUnsignedLong ( ) ; frame . setContentProperties ( this . getContentProperties ( ) ) ; frame . setMethodName ( "header" ) ; break ; case AmqpConstants . FRAME_METHOD : classIndex = this . getUnsignedShort ( ) ; int methodIndex = this . getUnsignedShort ( ) ; String indexes = String . valueOf ( classIndex ) + String . valueOf ( methodIndex ) ; method = MethodLookup . LookupMethod ( indexes ) ; // pull parameter list off of method List < Parameter > params = method . allParameters ; frame . setMethodName ( method . name ) ; frame . setArgs ( this . getMethodArguments ( params ) ) ; break ; case AmqpConstants . FRAME_HEARTBEAT : case AmqpConstants . FRAME_RABBITMQ_HEARTBEAT : throw new IllegalStateException ( "Received heartbeat frame even though the client has expressed no interest in heartbeat via tune-ok method." ) ; default : throw new IllegalStateException ( "Unrecognized AMQP 0-9-1 Frame type = " + frame . getType ( ) ) ; } short frameEnd = ( short ) this . getUnsigned ( ) ; if ( frameEnd != AmqpConstants . FRAME_END ) { throw new IllegalStateException ( "Invalid end of AMQP method frame" ) ; } } else { this . position ( pos ) ; return null ; } return frame ; } return null ; }
Parses the ByteBuffer and returns an AMQP frame
665
13
138,747
AmqpBuffer putMethodArguments ( Object [ ] args , List < Parameter > formalParams ) { for ( int i = 0 ; i < formalParams . size ( ) ; i ++ ) { String type = formalParams . get ( i ) . type ; if ( type == null ) { throw new IllegalStateException ( "Unknown AMQP domain " + type ) ; } String typeMap = getMappedType ( type ) ; putObjectOfType ( typeMap , args [ i ] ) ; // support packing of consecutive bits into a single byte this . bitCount = ( byte ) ( ( typeMap == "Bit" ) ? this . bitCount + 1 : 0 ) ; } return this ; }
Encodes arguments given a method s parameter list and the provided arguments
153
13
138,748
@ Override public void update ( Graphics g ) { Shape clip = g . getClip ( ) ; Rectangle dirty ; if ( clip != null ) { dirty = clip . getBounds ( ) ; } else { dirty = getRootPane ( ) . getBounds ( ) ; // account for our frame insets Insets insets = getInsets ( ) ; dirty . x += insets . left ; dirty . y += insets . top ; } if ( _fmgr != null ) { _fmgr . restoreFromBack ( dirty ) ; } }
We catch update requests and forward them on to the repaint infrastructure .
120
14
138,749
public static < T extends Serializable > T deserialize ( byte [ ] bytes ) throws IOException , ClassNotFoundException { return deserialize ( bytes , false ) ; }
Utility for returning a Serializable object from a byte array .
38
13
138,750
public PushProcessorPipeline build ( List < PushProcessorSupplier > processor_suppliers ) throws Exception { ApiServer api = null ; PushMetricRegistryInstance registry = null ; final List < PushProcessor > processors = new ArrayList <> ( processor_suppliers . size ( ) ) ; try { final EndpointRegistration epr ; if ( epr_ == null ) epr = api = new ApiServer ( api_sockaddr_ ) ; else epr = epr_ ; registry = cfg_ . create ( PushMetricRegistryInstance :: new , epr ) ; for ( PushProcessorSupplier pps : processor_suppliers ) processors . ( pps . build ( epr ) ) ; if ( history_ != null ) registry . setHistory ( history_ ) ; if ( api != null ) api . start ( ) ; return new PushProcessorPipeline ( registry , collect_interval_seconds_ , processors ) ; } catch ( Exception ex ) { try { if ( api != null ) api . close ( ) ; } catch ( Exception ex1 ) { ex . addSuppressed ( ex1 ) ; } try { if ( registry != null ) registry . close ( ) ; } catch ( Exception ex1 ) { ex . addSuppressed ( ex1 ) ; } for ( PushProcessor pp : processors ) { try { pp . close ( ) ; } catch ( Exception ex1 ) { ex . addSuppressed ( ex1 ) ; } } throw ex ; } }
Creates a push processor .
328
6
138,751
public static BufferedImage createCompatibleImage ( BufferedImage source , int width , int height ) { WritableRaster raster = source . getRaster ( ) . createCompatibleWritableRaster ( width , height ) ; return new BufferedImage ( source . getColorModel ( ) , raster , false , null ) ; }
Creates a new buffered image with the same sample model and color model as the source image but with the new width and height .
73
27
138,752
public static BufferedImage createErrorImage ( int width , int height ) { BufferedImage img = new BufferedImage ( width , height , BufferedImage . TYPE_BYTE_INDEXED ) ; Graphics2D g = ( Graphics2D ) img . getGraphics ( ) ; g . setColor ( Color . red ) ; Label l = new Label ( "Error" ) ; l . layout ( g ) ; Dimension d = l . getSize ( ) ; // fill that sucker with errors for ( int yy = 0 ; yy < height ; yy += d . height ) { for ( int xx = 0 ; xx < width ; xx += ( d . width + 5 ) ) { l . render ( g , xx , yy ) ; } } g . dispose ( ) ; return img ; }
Creates an image with the word Error written in it .
172
12
138,753
public static BufferedImage recolorImage ( BufferedImage image , Colorization [ ] zations ) { ColorModel cm = image . getColorModel ( ) ; if ( ! ( cm instanceof IndexColorModel ) ) { throw new RuntimeException ( Logger . format ( "Unable to recolor images with non-index color model" , "cm" , cm . getClass ( ) ) ) ; } // now process the image IndexColorModel icm = ( IndexColorModel ) cm ; int size = icm . getMapSize ( ) ; int zcount = zations . length ; int [ ] rgbs = new int [ size ] ; // fetch the color data icm . getRGBs ( rgbs ) ; // convert the colors to HSV float [ ] hsv = new float [ 3 ] ; int [ ] fhsv = new int [ 3 ] ; for ( int ii = 0 ; ii < size ; ii ++ ) { int value = rgbs [ ii ] ; // don't fiddle with alpha pixels if ( ( value & 0xFF000000 ) == 0 ) { continue ; } // convert the color to HSV int red = ( value >> 16 ) & 0xFF ; int green = ( value >> 8 ) & 0xFF ; int blue = ( value >> 0 ) & 0xFF ; Color . RGBtoHSB ( red , green , blue , hsv ) ; Colorization . toFixedHSV ( hsv , fhsv ) ; // see if this color matches and of our colorizations and recolor it if it does for ( int z = 0 ; z < zcount ; z ++ ) { Colorization cz = zations [ z ] ; if ( cz != null && cz . matches ( hsv , fhsv ) ) { // massage the HSV bands and update the RGBs array rgbs [ ii ] = cz . recolorColor ( hsv ) ; break ; } } } // create a new image with the adjusted color palette IndexColorModel nicm = new IndexColorModel ( icm . getPixelSize ( ) , size , rgbs , 0 , icm . hasAlpha ( ) , icm . getTransparentPixel ( ) , icm . getTransferType ( ) ) ; return new BufferedImage ( nicm , image . getRaster ( ) , false , null ) ; }
Recolors the supplied image using the supplied colorizations .
497
12
138,754
public static void tileImage ( Graphics2D gfx , Mirage image , int x , int y , int width , int height ) { int iwidth = image . getWidth ( ) , iheight = image . getHeight ( ) ; int xnum = width / iwidth , xplus = width % iwidth ; int ynum = height / iheight , yplus = height % iheight ; Shape oclip = gfx . getClip ( ) ; for ( int ii = 0 ; ii < ynum ; ii ++ ) { // draw the full copies of the image across int xx = x ; for ( int jj = 0 ; jj < xnum ; jj ++ ) { image . paint ( gfx , xx , y ) ; xx += iwidth ; } if ( xplus > 0 ) { gfx . clipRect ( xx , y , xplus , iheight ) ; image . paint ( gfx , xx , y ) ; gfx . setClip ( oclip ) ; } y += iheight ; } if ( yplus > 0 ) { int xx = x ; for ( int jj = 0 ; jj < xnum ; jj ++ ) { gfx . clipRect ( xx , y , iwidth , yplus ) ; image . paint ( gfx , xx , y ) ; gfx . setClip ( oclip ) ; xx += iwidth ; } if ( xplus > 0 ) { gfx . clipRect ( xx , y , xplus , yplus ) ; image . paint ( gfx , xx , y ) ; gfx . setClip ( oclip ) ; } } }
Paints multiple copies of the supplied image using the supplied graphics context such that the requested area is filled with the image .
347
24
138,755
public static void tileImageAcross ( Graphics2D gfx , Mirage image , int x , int y , int width ) { tileImage ( gfx , image , x , y , width , image . getHeight ( ) ) ; }
Paints multiple copies of the supplied image using the supplied graphics context such that the requested width is filled with the image .
49
24
138,756
public static void tileImageDown ( Graphics2D gfx , Mirage image , int x , int y , int height ) { tileImage ( gfx , image , x , y , image . getWidth ( ) , height ) ; }
Paints multiple copies of the supplied image using the supplied graphics context such that the requested height is filled with the image .
49
24
138,757
public static BufferedImage createTracedImage ( ImageCreator isrc , BufferedImage src , Color tcolor , int thickness ) { return createTracedImage ( isrc , src , tcolor , thickness , 1.0f , 1.0f ) ; }
Creates and returns a new image consisting of the supplied image traced with the given color and thickness .
57
20
138,758
protected static boolean bordersNonTransparentPixel ( BufferedImage data , int wid , int hei , boolean [ ] traced , int x , int y ) { // check the three-pixel row above the pixel if ( y > 0 ) { for ( int rxx = x - 1 ; rxx <= x + 1 ; rxx ++ ) { if ( rxx < 0 || rxx >= wid || traced [ ( ( y - 1 ) * wid ) + rxx ] ) { continue ; } if ( ( data . getRGB ( rxx , y - 1 ) & TRANS_MASK ) != 0 ) { return true ; } } } // check the pixel to the left if ( x > 0 && ! traced [ ( y * wid ) + ( x - 1 ) ] ) { if ( ( data . getRGB ( x - 1 , y ) & TRANS_MASK ) != 0 ) { return true ; } } // check the pixel to the right if ( x < wid - 1 && ! traced [ ( y * wid ) + ( x + 1 ) ] ) { if ( ( data . getRGB ( x + 1 , y ) & TRANS_MASK ) != 0 ) { return true ; } } // check the three-pixel row below the pixel if ( y < hei - 1 ) { for ( int rxx = x - 1 ; rxx <= x + 1 ; rxx ++ ) { if ( rxx < 0 || rxx >= wid || traced [ ( ( y + 1 ) * wid ) + rxx ] ) { continue ; } if ( ( data . getRGB ( rxx , y + 1 ) & TRANS_MASK ) != 0 ) { return true ; } } } return false ; }
Returns whether the given pixel is bordered by any non - transparent pixel .
364
15
138,759
public static BufferedImage composeMaskedImage ( ImageCreator isrc , BufferedImage mask , BufferedImage base ) { int wid = base . getWidth ( ) ; int hei = base . getHeight ( ) ; Raster maskdata = mask . getData ( ) ; Raster basedata = base . getData ( ) ; // create a new image using the rasters if possible if ( maskdata . getNumBands ( ) == 4 && basedata . getNumBands ( ) >= 3 ) { WritableRaster target = basedata . createCompatibleWritableRaster ( wid , hei ) ; // copy the alpha from the mask image int [ ] adata = maskdata . getSamples ( 0 , 0 , wid , hei , 3 , ( int [ ] ) null ) ; target . setSamples ( 0 , 0 , wid , hei , 3 , adata ) ; // copy the RGB from the base image for ( int ii = 0 ; ii < 3 ; ii ++ ) { int [ ] cdata = basedata . getSamples ( 0 , 0 , wid , hei , ii , ( int [ ] ) null ) ; target . setSamples ( 0 , 0 , wid , hei , ii , cdata ) ; } return new BufferedImage ( mask . getColorModel ( ) , target , true , null ) ; } else { // otherwise composite them by rendering them with an alpha // rule BufferedImage target = isrc . createImage ( wid , hei , Transparency . TRANSLUCENT ) ; Graphics2D g2 = target . createGraphics ( ) ; try { g2 . drawImage ( mask , 0 , 0 , null ) ; g2 . setComposite ( AlphaComposite . SrcIn ) ; g2 . drawImage ( base , 0 , 0 , null ) ; } finally { g2 . dispose ( ) ; } return target ; } }
Create an image using the alpha channel from the first and the RGB values from the second .
410
18
138,760
public static BufferedImage composeMaskedImage ( ImageCreator isrc , Shape mask , BufferedImage base ) { int wid = base . getWidth ( ) ; int hei = base . getHeight ( ) ; // alternate method for composition: // 1. create WriteableRaster with base data // 2. test each pixel with mask.contains() and set the alpha channel to fully-alpha if false // 3. create buffered image from raster // (I didn't use this method because it depends on the colormodel of the source image, and // was booching when the souce image was a cut-up from a tileset, and it seems like it // would take longer than the method we are using. But it's something to consider) // composite them by rendering them with an alpha rule BufferedImage target = isrc . createImage ( wid , hei , Transparency . TRANSLUCENT ) ; Graphics2D g2 = target . createGraphics ( ) ; try { g2 . setColor ( Color . BLACK ) ; // whatever, really g2 . fill ( mask ) ; g2 . setComposite ( AlphaComposite . SrcIn ) ; g2 . drawImage ( base , 0 , 0 , null ) ; } finally { g2 . dispose ( ) ; } return target ; }
Create a new image using the supplied shape as a mask from which to cut out pixels from the supplied image . Pixels inside the shape will be added to the final image pixels outside the shape will be clear .
282
42
138,761
public static void computeTrimmedBounds ( BufferedImage image , Rectangle tbounds ) { // this could be more efficient, but it's run as a batch process and doesn't really take // that long anyway int width = image . getWidth ( ) , height = image . getHeight ( ) ; int firstrow = - 1 , lastrow = - 1 , minx = width , maxx = 0 ; for ( int yy = 0 ; yy < height ; yy ++ ) { int firstidx = - 1 , lastidx = - 1 ; for ( int xx = 0 ; xx < width ; xx ++ ) { // if this pixel is transparent, do nothing int argb = image . getRGB ( xx , yy ) ; if ( ( argb >> 24 ) == 0 ) { continue ; } // otherwise, if we've not seen a non-transparent pixel, make a note that this is // the first non-transparent pixel in the row if ( firstidx == - 1 ) { firstidx = xx ; } // keep track of the last non-transparent pixel we saw lastidx = xx ; } // if we saw no pixels on this row, we can bail now if ( firstidx == - 1 ) { continue ; } // update our min and maxx minx = Math . min ( firstidx , minx ) ; maxx = Math . max ( lastidx , maxx ) ; // otherwise keep track of the first row on which we see pixels and the last row on // which we see pixels if ( firstrow == - 1 ) { firstrow = yy ; } lastrow = yy ; } // fill in the dimensions if ( firstrow != - 1 ) { tbounds . x = minx ; tbounds . y = firstrow ; tbounds . width = maxx - minx + 1 ; tbounds . height = lastrow - firstrow + 1 ; } else { // Entirely blank image. Return 1x1 blank image. tbounds . x = 0 ; tbounds . y = 0 ; tbounds . width = 1 ; tbounds . height = 1 ; } }
Computes the bounds of the smallest rectangle that contains all non - transparent pixels of this image . This isn t extremely efficient so you shouldn t be doing this anywhere exciting .
465
34
138,762
public static long getEstimatedMemoryUsage ( Raster raster ) { // we assume that the data buffer stores each element in a byte-rounded memory element; // maybe the buffer is smarter about things than this, but we're better to err on the safe // side DataBuffer db = raster . getDataBuffer ( ) ; int bpe = ( int ) Math . ceil ( DataBuffer . getDataTypeSize ( db . getDataType ( ) ) / 8f ) ; return bpe * db . getSize ( ) ; }
Returns the estimated memory usage in bytes for the specified raster .
113
13
138,763
public static long getEstimatedMemoryUsage ( Iterator < BufferedImage > iter ) { long size = 0 ; while ( iter . hasNext ( ) ) { BufferedImage image = iter . next ( ) ; size += getEstimatedMemoryUsage ( image ) ; } return size ; }
Returns the estimated memory usage in bytes for all buffered images in the supplied iterator .
61
17
138,764
protected static GraphicsConfiguration getDefGC ( ) { if ( _gc == null ) { // obtain information on our graphics environment try { GraphicsEnvironment env = GraphicsEnvironment . getLocalGraphicsEnvironment ( ) ; GraphicsDevice gd = env . getDefaultScreenDevice ( ) ; _gc = gd . getDefaultConfiguration ( ) ; } catch ( HeadlessException e ) { // no problem, just return null } } return _gc ; }
Obtains the default graphics configuration for this VM . If the JVM is in headless mode this method will return null .
90
25
138,765
public void getIntersectingSprites ( List < Sprite > list , Shape shape ) { int size = _sprites . size ( ) ; for ( int ii = 0 ; ii < size ; ii ++ ) { Sprite sprite = _sprites . get ( ii ) ; if ( sprite . intersects ( shape ) ) { list . add ( sprite ) ; } } }
When an animated view processes its dirty rectangles it may require an expansion of the dirty region which may in turn require the invalidation of more sprites than were originally invalid . In such cases the animated view can call back to the sprite manager asking it to append the sprites that intersect a particular region to the given list .
78
63
138,766
public void getHitSprites ( List < Sprite > list , int x , int y ) { for ( int ii = _sprites . size ( ) - 1 ; ii >= 0 ; ii -- ) { Sprite sprite = _sprites . get ( ii ) ; if ( sprite . hitTest ( x , y ) ) { list . add ( sprite ) ; } } }
When an animated view is determining what entity in its view is under the mouse pointer it may require a list of sprites that are hit by a particular pixel . The sprites bounds are first checked and sprites with bounds that contain the supplied point are further checked for a non - transparent at the specified location .
78
59
138,767
public Sprite getHighestHitSprite ( int x , int y ) { // since they're stored in lowest -> highest order.. for ( int ii = _sprites . size ( ) - 1 ; ii >= 0 ; ii -- ) { Sprite sprite = _sprites . get ( ii ) ; if ( sprite . hitTest ( x , y ) ) { return sprite ; } } return null ; }
Finds the sprite with the highest render order that hits the specified pixel .
84
15
138,768
public void removeSprites ( Predicate < Sprite > pred ) { int idxoff = 0 ; for ( int ii = 0 , ll = _sprites . size ( ) ; ii < ll ; ii ++ ) { Sprite sprite = _sprites . get ( ii - idxoff ) ; if ( pred . apply ( sprite ) ) { _sprites . remove ( sprite ) ; sprite . invalidate ( ) ; sprite . shutdown ( ) ; // we need to preserve the original "index" relative to the current tick position, // so we don't decrement ii directly idxoff ++ ; if ( ii <= _tickpos ) { _tickpos -- ; } } } }
Removes all sprites that match the supplied predicate .
143
10
138,769
public void cancelMove ( ) { if ( _path != null ) { Path oldpath = _path ; _path = null ; oldpath . wasRemoved ( this ) ; if ( _observers != null ) { _observers . apply ( new CancelledOp ( this , oldpath ) ) ; } } }
Cancels any path that the sprite may currently be moving along .
68
14
138,770
public void pathCompleted ( long timestamp ) { Path oldpath = _path ; _path = null ; oldpath . wasRemoved ( this ) ; if ( _observers != null ) { _observers . apply ( new CompletedOp ( this , oldpath , timestamp ) ) ; } }
Called by the active path when it has completed .
62
11
138,771
protected boolean tickPath ( long tickStamp ) { if ( _path == null ) { return false ; } // initialize the path if we haven't yet if ( _pathStamp == 0 ) { _path . init ( this , _pathStamp = tickStamp ) ; } // it's possible that as a result of init() the path completed and removed itself with a // call to pathCompleted(), so we have to be careful here return ( _path == null ) ? true : _path . tick ( this , tickStamp ) ; }
Ticks any path assigned to this sprite .
115
9
138,772
public void layout ( Graphics2D gfx , SceneObject tipFor , Rectangle boundary ) { layout ( gfx , ICON_PAD , EXTRA_PAD ) ; bounds = new Rectangle ( _size ) ; // locate the most appropriate tip layout for ( int ii = 0 , ll = _layouts . size ( ) ; ii < ll ; ii ++ ) { LayoutReg reg = _layouts . get ( ii ) ; String act = tipFor . info . action == null ? "" : tipFor . info . action ; if ( act . startsWith ( reg . prefix ) ) { reg . layout . layout ( gfx , boundary , tipFor , this ) ; break ; } } }
Called to initialize the tip so that it can be painted .
149
13
138,773
public static void registerTipLayout ( String prefix , TipLayout layout ) { LayoutReg reg = new LayoutReg ( ) ; reg . prefix = prefix ; reg . layout = layout ; _layouts . insertSorted ( reg ) ; }
It may be desirable to layout object tips specially depending on what sort of actions they represent so we allow different tip layout algorithms to be registered for particular object prefixes . The registration is simply a list searched from longest string to shortest string for the first match to an object s action .
49
56
138,774
public static boolean isLeaf ( Node node ) { return node instanceof Leaf || node . children ( ) == null || node . children ( ) . size ( ) == 0 ; }
Returns true if a node is a leaf . Note that a leaf can also be a parent node that does not have any children .
38
26
138,775
public static boolean isEmpty ( Node node ) { return ( node == null || ( node . children ( ) != null && node . children ( ) . size ( ) == 0 ) ) ; }
Determines if a node is null or a single parent node without children .
40
16
138,776
public static boolean parentContainsOnlyLeaves ( ParentNode parentNode ) { for ( Node child : parentNode . children ( ) ) { if ( ! isLeaf ( child ) ) return false ; } return true ; }
Determines if parent node has children that are all leaves
47
12
138,777
public static Criteria criteriaFromNode ( Node node , Comparator rangeComparator ) { return criteriaFromNode ( node , rangeComparator , null ) ; }
Creates criteria from a node . A Comparator is injected into all nodes which need to determine order or equality .
33
23
138,778
public static void renameTileSet ( String mapPath , String oldName , String newName ) throws PersistenceException { MapFileTileSetIDBroker broker = new MapFileTileSetIDBroker ( new File ( mapPath ) ) ; if ( ! broker . renameTileSet ( oldName , newName ) ) { throw new PersistenceException ( "No such old tileset '" + oldName + "'." ) ; } broker . commit ( ) ; }
Loads up the tileset map file with the specified path and copies the tileset ID from the old tileset name to the new tileset name . This is necessary when a tileset is renamed so that the new name does not cause the tileset to be assigned a new tileset ID . Bear in mind that the old name should never again be used as it will conflict with a tileset provided under the new name .
97
86
138,779
protected TrimmedTileSet trim ( TileSet aset , OutputStream fout ) throws IOException { return TrimmedTileSet . trimTileSet ( aset , fout ) ; }
Converts the tileset to a trimmed tile set and saves it at the specified location .
41
18
138,780
protected void saveBroker ( File mapfile , HashMapIDBroker broker ) throws RuntimeException { // bail if the broker wasn't modified if ( ! broker . isModified ( ) ) { return ; } try { BufferedWriter bout = new BufferedWriter ( new FileWriter ( mapfile ) ) ; broker . writeTo ( bout ) ; bout . close ( ) ; } catch ( IOException ioe ) { throw new RuntimeException ( "Unable to store component ID map [mapfile=" + mapfile + "]" , ioe ) ; } }
Stores a persistent representation of the supplied hashmap ID broker in the specified file .
118
17
138,781
private static GroupName nameFromObjectName ( ObjectName obj_name , NamedResolverMap resolvedMap ) { String name = obj_name . getKeyProperty ( "name" ) ; String type = obj_name . getKeyProperty ( "type" ) ; String domain = obj_name . getDomain ( ) ; Map < String , MetricValue > tags = obj_name . getKeyPropertyList ( ) . entrySet ( ) . stream ( ) . filter ( ( entry ) - > ! entry . getKey ( ) . equals ( "name" ) ) . filter ( ( entry ) - > ! entry . getKey ( ) . equals ( "type" ) ) . map ( Tag :: valueOf ) . collect ( Collectors . toMap ( ( Tag t ) -> t . getName ( ) , ( Tag t ) -> t . getValue ( ) ) ) ; final List < String > path = new ArrayList <> ( ) ; if ( name != null ) { path . addAll ( Arrays . asList ( name . split ( "\\." ) ) ) ; } else if ( type != null ) { path . addAll ( Arrays . asList ( domain . split ( "\\." ) ) ) ; path . add ( type ) ; } else { path . addAll ( Arrays . asList ( domain . split ( "\\." ) ) ) ; } return resolvedMap . getGroupName ( path , tags ) ; }
Extract a metric group name from a JMX ObjectName .
307
13
138,782
static boolean isSorted ( Iterable < ? extends TimeSeriesCollection > tscIterable ) { final Iterator < ? extends TimeSeriesCollection > iter = tscIterable . iterator ( ) ; if ( ! iter . hasNext ( ) ) return true ; // Empty collection is ordered. DateTime timestamp = iter . next ( ) . getTimestamp ( ) ; while ( iter . hasNext ( ) ) { final DateTime nextTimestamp = iter . next ( ) . getTimestamp ( ) ; if ( ! nextTimestamp . isAfter ( timestamp ) ) return false ; timestamp = nextTimestamp ; } return true ; }
Validation function to check if an iterable is sorted with ascending timestamps .
133
17
138,783
public void resolve ( Observer observer ) { // if we were waiting to unload, cancel that if ( _state == UNLOADING ) { _state = LOADED ; _manager . restoreClip ( this ) ; } // if we're already loaded, this is easy if ( _state == LOADED ) { if ( observer != null ) { observer . clipLoaded ( this ) ; } return ; } // queue up the observer if ( observer != null ) { _observers . add ( observer ) ; } // if we're already loading, we can stop here if ( _state == LOADING ) { return ; } // create our OpenAL buffer and then queue ourselves up to have // our clip data loaded AL10 . alGetError ( ) ; // throw away any unchecked error prior to an op we want to check _buffer = new Buffer ( _manager ) ; int errno = AL10 . alGetError ( ) ; if ( errno != AL10 . AL_NO_ERROR ) { log . warning ( "Failed to create buffer [key=" + getKey ( ) + ", errno=" + errno + "]." ) ; _buffer = null ; // queue up a failure notification so that we properly return // from this method and our sound has a chance to register // itself as an observer before we jump up and declare failure _manager . queueClipFailure ( this ) ; } else { _state = LOADING ; _manager . queueClipLoad ( this ) ; } }
Instructs this buffer to resolve its underlying clip and be ready to be played ASAP .
318
17
138,784
public void dispose ( ) { if ( _buffer != null ) { // if there are sources bound to this buffer, we must wait // for them to be unbound if ( _bound > 0 ) { _state = UNLOADING ; return ; } // free up our buffer _buffer . delete ( ) ; _buffer = null ; _state = UNLOADED ; } }
Frees up the internal audio buffers associated with this clip .
78
12
138,785
protected boolean bind ( Clip clip ) { AL10 . alGetError ( ) ; // throw away any unchecked error prior to an op we want to check _buffer . setData ( clip . format , clip . data , clip . frequency ) ; int errno = AL10 . alGetError ( ) ; if ( errno != AL10 . AL_NO_ERROR ) { log . warning ( "Failed to bind clip" , "key" , getKey ( ) , "errno" , errno ) ; failed ( ) ; return false ; } _state = LOADED ; _size = _buffer . getSize ( ) ; _observers . apply ( new ObserverList . ObserverOp < Observer > ( ) { public boolean apply ( Observer observer ) { observer . clipLoaded ( ClipBuffer . this ) ; return true ; } } ) ; _observers . clear ( ) ; return true ; }
This method is called back on the main thread and instructs this buffer to bind the clip data to this buffer s OpenAL buffer .
193
27
138,786
protected void failed ( ) { if ( _buffer != null ) { _buffer . delete ( ) ; _buffer = null ; } _state = UNLOADED ; _observers . apply ( new ObserverList . ObserverOp < Observer > ( ) { public boolean apply ( Observer observer ) { observer . clipFailed ( ClipBuffer . this ) ; return true ; } } ) ; _observers . clear ( ) ; }
Called when we fail in some part of the process in resolving our clip data . Notifies our observers and resets the clip to the UNLOADED state .
90
33
138,787
protected void createVolatileImage ( ) { // release any previous volatile image we might hold if ( _image != null ) { _image . flush ( ) ; } // create a new, compatible, volatile image // _image = _imgr.createVolatileImage( // _bounds.width, _bounds.height, getTransparency()); _image = _imgr . createImage ( _bounds . width , _bounds . height , getTransparency ( ) ) ; // render our source image into the volatile image refreshVolatileImage ( ) ; }
Creates our volatile image from the information in our source image .
119
13
138,788
public boolean askBoolean ( final String question ) { checkNotNull ( question ) ; log . trace ( "Ask boolean; question={}" , question ) ; String result = readLine ( String . format ( "%s (yes/no): " , question ) ) ; return result . equalsIgnoreCase ( "yes" ) ; }
Ask a question which results in a boolean result .
70
10
138,789
public void addPressCommand ( int keyCode , String command , int rate ) { addPressCommand ( keyCode , command , rate , DEFAULT_REPEAT_DELAY ) ; }
Adds a mapping from a key press to an action command string that will auto - repeat at the specified repeat rate . Overwrites any existing mapping and repeat rate that may have already been registered .
41
39
138,790
public void addPressCommand ( int keyCode , String command , int rate , long repeatDelay ) { KeyRecord krec = getKeyRecord ( keyCode ) ; krec . pressCommand = command ; krec . repeatRate = rate ; krec . repeatDelay = repeatDelay ; }
Adds a mapping from a key press to an action command string that will auto - repeat at the specified repeat rate after the specified auto - repeat delay has expired . Overwrites any existing mapping for the specified key code that may have already been registered .
63
50
138,791
public void addReleaseCommand ( int keyCode , String command ) { KeyRecord krec = getKeyRecord ( keyCode ) ; krec . releaseCommand = command ; }
Adds a mapping from a key release to an action command string . Overwrites any existing mapping that may already have been registered .
36
26
138,792
protected KeyRecord getKeyRecord ( int keyCode ) { KeyRecord krec = _keys . get ( keyCode ) ; if ( krec == null ) { krec = new KeyRecord ( ) ; _keys . put ( keyCode , krec ) ; } return krec ; }
Returns the key record for the specified key creating it and inserting it in the key table if necessary .
61
20
138,793
public void addSprite ( Sprite sprite ) { _metamgr . addSprite ( sprite ) ; if ( ( ( sprite instanceof ActionSprite ) || ( sprite instanceof HoverSprite ) ) && ( _actionSpriteCount ++ == 0 ) ) { if ( _actionHandler == null ) { _actionHandler = createActionSpriteHandler ( ) ; } addMouseListener ( _actionHandler ) ; addMouseMotionListener ( _actionHandler ) ; } }
Adds a sprite to this panel .
99
7
138,794
public void removeSprite ( Sprite sprite ) { _metamgr . removeSprite ( sprite ) ; if ( ( ( sprite instanceof ActionSprite ) || ( sprite instanceof HoverSprite ) ) && ( -- _actionSpriteCount == 0 ) ) { removeMouseListener ( _actionHandler ) ; removeMouseMotionListener ( _actionHandler ) ; } }
Removes a sprite from this panel .
77
8
138,795
public void clearSprites ( ) { _metamgr . clearSprites ( ) ; if ( _actionHandler != null ) { removeMouseListener ( _actionHandler ) ; removeMouseMotionListener ( _actionHandler ) ; _actionSpriteCount = 0 ; } }
Removes all sprites from this panel .
57
8
138,796
public void tick ( long tickStamp ) { if ( _metamgr . isPaused ( ) ) { return ; } // let derived classes do their business willTick ( tickStamp ) ; // tick our meta manager which will tick our sprites and animations _metamgr . tick ( tickStamp ) ; // let derived classes do their business didTick ( tickStamp ) ; // make a note that the next paint will correspond to a call to tick() _tickPaintPending = true ; }
from interface FrameParticipant
109
5
138,797
public void addObscurer ( Obscurer obscurer ) { if ( _obscurerList == null ) { _obscurerList = Lists . newArrayList ( ) ; } _obscurerList . add ( obscurer ) ; }
Adds an element that could be obscuring the panel and thus requires extra redrawing .
53
18
138,798
protected void addObscurerDirtyRegions ( boolean changedOnly ) { if ( _obscurerList != null ) { for ( Obscurer obscurer : _obscurerList ) { Rectangle obscured = obscurer . getObscured ( changedOnly ) ; if ( obscured != null ) { Point pt = new Point ( obscured . x , obscured . y ) ; SwingUtilities . convertPointFromScreen ( pt , this ) ; addObscurerDirtyRegion ( new Rectangle ( pt . x , pt . y , obscured . width , obscured . height ) ) ; } } } }
Add dirty regions for all our obscurers .
128
9
138,799
protected void paintDirtyRect ( Graphics2D gfx , Rectangle rect ) { // paint the behind the scenes stuff paintBehind ( gfx , rect ) ; // paint back sprites and animations paintBits ( gfx , AnimationManager . BACK , rect ) ; // paint the between the scenes stuff paintBetween ( gfx , rect ) ; // paint front sprites and animations paintBits ( gfx , AnimationManager . FRONT , rect ) ; // paint anything in front paintInFront ( gfx , rect ) ; }
Paints all the layers of the specified dirty region .
109
11