idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
138,900 | static Integer getArrayIndex ( Map < String , String > meta , int level ) { return Integer . parseInt ( meta . get ( level + ARRAY_IDX_SUFFIX ) ) ; } | Returns an array index for a specific level from the metadata from a flattened json tree . | 43 | 17 |
138,901 | static boolean hasArrayIndex ( Map < String , String > meta , int level ) { return meta . containsKey ( level + ARRAY_IDX_SUFFIX ) ; } | Determines whether or not a map of metadata contains array index information at the given level in a flattened json tree . | 38 | 24 |
138,902 | static Map < Integer , Integer > levelsToIndices ( Map < String , String > meta ) { Set < Map . Entry < String , String > > entries = meta . entrySet ( ) ; Map < Integer , Integer > levelToIdx = new HashMap <> ( ) ; for ( Map . Entry < String , String > entry : entries ) if ( entry . getKey ( ) . endsWith ( ARRAY_IDX_SUFFIX ) ) levelToIdx . put ( parseInt ( entry . getKey ( ) . substring ( 0 , entry . getKey ( ) . indexOf ( ' ' ) ) ) , parseInt ( entry . getValue ( ) ) ) ; return levelToIdx ; } | Converts all array index information in a given map of metadata to a map that is keyed only by the level and each value is the index in the array for that level . This is used to optimize lookup since a string is used for the key in the metadata that should not conflict with keys that other applications may want to set . | 154 | 67 |
138,903 | public void stream ( final String bundle , final String path , final boolean loop , final ResultListener < Stream > listener ) throws IOException { if ( ! path . endsWith ( ".ogg" ) ) { log . warning ( "Unknown file type for streaming" , "bundle" , bundle , "path" , path ) ; return ; } InputStream rsrc = _loader . getSound ( bundle , path ) ; final StreamDecoder dec = new OggStreamDecoder ( ) ; dec . init ( rsrc ) ; getSoundQueue ( ) . postRunnable ( new Runnable ( ) { public void run ( ) { Stream s = new Stream ( _alSoundManager ) { @ Override protected void update ( float time ) { super . update ( time ) ; if ( _state != AL10 . AL_PLAYING ) { return ; } super . setGain ( _clipVol * _streamGain ) ; } @ Override public void setGain ( float gain ) { _streamGain = gain ; super . setGain ( _clipVol * _streamGain ) ; } @ Override protected int getFormat ( ) { return dec . getFormat ( ) ; } @ Override protected int getFrequency ( ) { return dec . getFrequency ( ) ; } @ Override protected int populateBuffer ( ByteBuffer buf ) throws IOException { int read = dec . read ( buf ) ; if ( buf . hasRemaining ( ) && loop ) { dec . init ( _loader . getSound ( bundle , path ) ) ; read = Math . max ( 0 , read ) ; read += dec . read ( buf ) ; } return read ; } protected float _streamGain = 1F ; } ; s . setGain ( _clipVol ) ; listener . requestCompleted ( s ) ; } } ) ; } | Streams ogg files from the given bundle and path . | 391 | 12 |
138,904 | private Map < Any2 < Integer , String > , String > resolve_template_args_ ( Matcher matcher ) { return template_ . getArguments ( ) . stream ( ) . collect ( Collectors . toMap ( arg -> arg , arg -> arg . mapCombine ( matcher :: group , matcher :: group ) ) ) ; } | Convert a regexp match to a map of matcher arguments . | 74 | 14 |
138,905 | private Optional < MetricValue > rewrite_ ( MetricValue v ) { return v . asString ( ) . map ( pattern_ :: matcher ) . filter ( matcher -> matcher . find ( ) ) . map ( this :: resolve_template_args_ ) . map ( template_ :: apply ) . map ( MetricValue :: fromStrValue ) ; } | Rewrite a string metric according to matcher and template . Strings that don t match the regexp are omitted . | 78 | 24 |
138,906 | public Serializable parseConfig ( File source ) throws IOException , SAXException { Digester digester = new Digester ( ) ; Serializable config = createConfigObject ( ) ; addRules ( digester ) ; digester . push ( config ) ; digester . parse ( new FileInputStream ( source ) ) ; return config ; } | Parses the supplied configuration file into a serializable configuration object . | 71 | 14 |
138,907 | public Tags filter ( Set < String > tag_names ) { return Tags . valueOf ( tags_ . entrySet ( ) . stream ( ) . filter ( entry -> tag_names . contains ( entry . getKey ( ) ) ) ) ; } | Reduce the list of tags to only those specified in the argument set . | 52 | 15 |
138,908 | protected void trackPathable ( ) { // if we're tracking a pathable, adjust our view coordinates if ( _fpath == null ) { return ; } int width = getWidth ( ) , height = getHeight ( ) ; int nx = _vbounds . x , ny = _vbounds . y ; // figure out where to move switch ( _fmode ) { case TRACK_PATHABLE : nx = _fpath . getX ( ) ; ny = _fpath . getY ( ) ; break ; case CENTER_ON_PATHABLE : nx = _fpath . getX ( ) - width / 2 ; ny = _fpath . getY ( ) - height / 2 ; break ; case ENCLOSE_PATHABLE : Rectangle bounds = _fpath . getBounds ( ) ; if ( nx > bounds . x ) { nx = bounds . x ; } else if ( nx + width < bounds . x + bounds . width ) { nx = bounds . x + bounds . width - width ; } if ( ny > bounds . y ) { ny = bounds . y ; } else if ( ny + height < bounds . y + bounds . height ) { ny = bounds . y + bounds . height - height ; } break ; default : log . warning ( "Eh? Set to invalid pathable mode" , "mode" , _fmode ) ; break ; } // Log.info("Tracking pathable [mode=" + _fmode + // ", pable=" + _fpath + ", nx=" + nx + ", ny=" + ny + "]."); setViewLocation ( nx , ny ) ; } | Implements the standard pathable tracking support . Derived classes may wish to override this if they desire custom tracking functionality . | 366 | 25 |
138,909 | public void updateBounds ( ) { Dimension size = _label . getSize ( ) ; _bounds . width = size . width ; _bounds . height = size . height ; } | Updates the bounds of the sprite after a change to the label . | 40 | 14 |
138,910 | protected void layoutLabel ( ) { Graphics2D gfx = _mgr . createGraphics ( ) ; if ( gfx == null ) { return ; } try { gfx . setRenderingHint ( RenderingHints . KEY_ANTIALIASING , ( _antiAliased ) ? RenderingHints . VALUE_ANTIALIAS_ON : RenderingHints . VALUE_ANTIALIAS_OFF ) ; _label . layout ( gfx ) ; } finally { gfx . dispose ( ) ; } } | Lays out our underlying label which must be done if the text is changed . | 114 | 16 |
138,911 | @ Override public void addRuleInstances ( Digester digester ) { // this creates the appropriate instance when we encounter a // <action> tag digester . addObjectCreate ( _prefix + ACTION_PATH , ActionSequence . class . getName ( ) ) ; // grab the name attribute from the <action> tag digester . addRule ( _prefix + ACTION_PATH , new SetPropertyFieldsRule ( ) ) ; // grab the other attributes from their respective tags digester . addRule ( _prefix + ACTION_PATH + "/framesPerSecond" , new SetFieldRule ( "framesPerSecond" ) ) ; CallMethodSpecialRule origin = new CallMethodSpecialRule ( ) { @ Override public void parseAndSet ( String bodyText , Object target ) throws Exception { int [ ] coords = StringUtil . parseIntArray ( bodyText ) ; if ( coords . length != 2 ) { String errmsg = "Invalid <origin> specification '" + bodyText + "'." ; throw new Exception ( errmsg ) ; } ( ( ActionSequence ) target ) . origin . setLocation ( coords [ 0 ] , coords [ 1 ] ) ; } } ; digester . addRule ( _prefix + ACTION_PATH + "/origin" , origin ) ; CallMethodSpecialRule orient = new CallMethodSpecialRule ( ) { @ Override public void parseAndSet ( String bodyText , Object target ) throws Exception { ActionSequence seq = ( ( ActionSequence ) target ) ; String [ ] ostrs = StringUtil . parseStringArray ( bodyText ) ; seq . orients = new int [ ostrs . length ] ; for ( int ii = 0 ; ii < ostrs . length ; ii ++ ) { int orient = DirectionUtil . fromShortString ( ostrs [ ii ] ) ; if ( orient != DirectionCodes . NONE ) { seq . orients [ ii ] = orient ; } else { String errmsg = "Invalid orientation specification " + "[index=" + ii + ", orient=" + ostrs [ ii ] + "]." ; throw new Exception ( errmsg ) ; } } } } ; digester . addRule ( _prefix + ACTION_PATH + "/orients" , orient ) ; } | Adds the necessary rules to the digester to parse our actions . | 475 | 13 |
138,912 | public static String validate ( ActionSequence seq ) { if ( StringUtil . isBlank ( seq . name ) ) { return "Missing 'name' definition." ; } if ( seq . framesPerSecond == 0 ) { return "Missing 'framesPerSecond' definition." ; } if ( seq . orients == null ) { return "Missing 'orients' definition." ; } return null ; } | Validates that all necessary fields have been parsed and set in this action sequence object and are valid . | 85 | 20 |
138,913 | private boolean getNextEviction ( ) { long nowTime = System . currentTimeMillis ( ) ; final long sleepEndTime = nowTime + evictionInverval ; while ( nowTime < sleepEndTime ) { final long toSleep = Math . max ( 100 , sleepEndTime - nowTime ) ; synchronized ( this ) { if ( terminate ) return false ; try { wait ( toSleep ) ; } catch ( InterruptedException e ) { // ignore } } nowTime = System . currentTimeMillis ( ) ; } return true ; } | Waits for a next eviction . | 115 | 7 |
138,914 | public static List < Point > getPath ( TraversalPred tpred , Object trav , int longest , int ax , int ay , int bx , int by , boolean partial ) { return getPath ( tpred , new Stepper ( ) , trav , longest , ax , ay , bx , by , partial ) ; } | Gets a path with the default stepper which assumes the piece can move one in any of the eight cardinal directions . | 71 | 24 |
138,915 | protected void computeTransformedBounds ( ) { int w = _base . getWidth ( ) ; int h = _base . getHeight ( ) ; Point [ ] points = new Point [ ] { new Point ( 0 , 0 ) , new Point ( w , 0 ) , new Point ( 0 , h ) , new Point ( w , h ) } ; _transform . transform ( points , 0 , points , 0 , 4 ) ; int minX , minY , maxX , maxY ; minX = minY = Integer . MAX_VALUE ; maxX = maxY = Integer . MIN_VALUE ; for ( int ii = 0 ; ii < 4 ; ii ++ ) { minX = Math . min ( minX , points [ ii ] . x ) ; maxX = Math . max ( maxX , points [ ii ] . x ) ; minY = Math . min ( minY , points [ ii ] . y ) ; maxY = Math . max ( maxY , points [ ii ] . y ) ; } _bounds = new Rectangle ( minX , minY , maxX - minX , maxY - minY ) ; } | Compute the bounds of the base Mirage after it has been transformed . | 244 | 14 |
138,916 | public BufferedImage createImage ( int width , int height , int trans ) { // DEBUG: override transparency for the moment on all images trans = Transparency . TRANSLUCENT ; if ( _gc != null ) { return _gc . createCompatibleImage ( width , height , trans ) ; } else { // if we're running in headless mode, do everything in 24-bit return new BufferedImage ( width , height , BufferedImage . TYPE_INT_ARGB ) ; } } | documentation inherited from interface BaseImageManager . OptimalImageCreator | 104 | 14 |
138,917 | static ConverterFactory getConverterFactory ( Configuration conf ) { Class < ? extends ConverterFactory > converterFactoryClass = conf . getClass ( CONVERTER_FACTORY , null , ConverterFactory . class ) ; if ( converterFactoryClass == null ) { throw new RuntimeException ( "ConverterFactory class was not set on the configuration" ) ; } LOG . debug ( "Got input ConverterFactory class from conf: {}" , converterFactoryClass ) ; return ReflectionUtils . newInstance ( converterFactoryClass , conf ) ; } | Gets the ConverterFactory from the configuration | 117 | 9 |
138,918 | public static void setConverterFactoryClass ( Configuration conf , Class < ? extends ConverterFactory > converterFactoryClass ) { conf . setClass ( CONVERTER_FACTORY , converterFactoryClass , ConverterFactory . class ) ; LOG . debug ( "Set input ConverterFactory class on conf: {}" , converterFactoryClass ) ; } | Sets the ConverterFactory class | 73 | 7 |
138,919 | static StructTypeInfo getTypeInfo ( Configuration conf ) { StructTypeInfo inputTypeInfo = ( StructTypeInfo ) TypeInfoUtils . getTypeInfoFromTypeString ( conf . get ( INPUT_TYPE_INFO ) ) ; LOG . debug ( "Got input typeInfo from conf: {}" , inputTypeInfo ) ; return inputTypeInfo ; } | Gets the StructTypeInfo that declares the columns to be read from the configuration | 75 | 16 |
138,920 | public static void setTypeInfo ( Configuration conf , StructTypeInfo typeInfo ) { conf . set ( INPUT_TYPE_INFO , typeInfo . getTypeName ( ) ) ; LOG . debug ( "Set input typeInfo on conf: {}" , typeInfo ) ; } | Sets the StructTypeInfo that declares the columns to be read in the configuration | 58 | 16 |
138,921 | static StructTypeInfo getSchemaTypeInfo ( Configuration conf ) { String schemaTypeInfo = conf . get ( SCHEMA_TYPE_INFO ) ; if ( schemaTypeInfo != null && ! schemaTypeInfo . isEmpty ( ) ) { LOG . debug ( "Got schema typeInfo from conf: {}" , schemaTypeInfo ) ; return ( StructTypeInfo ) TypeInfoUtils . getTypeInfoFromTypeString ( conf . get ( SCHEMA_TYPE_INFO ) ) ; } return null ; } | Gets the StructTypeInfo that declares the total schema of the file from the configuration | 106 | 17 |
138,922 | public static void setSchemaTypeInfo ( Configuration conf , StructTypeInfo schemaTypeInfo ) { if ( schemaTypeInfo != null ) { conf . set ( SCHEMA_TYPE_INFO , schemaTypeInfo . getTypeName ( ) ) ; LOG . debug ( "Set schema typeInfo on conf: {}" , schemaTypeInfo ) ; } } | Sets the StructTypeInfo that declares the total schema of the file in the configuration | 73 | 17 |
138,923 | static void setReadColumns ( Configuration conf , StructTypeInfo actualStructTypeInfo ) { StructTypeInfo readStructTypeInfo = getTypeInfo ( conf ) ; LOG . info ( "Read StructTypeInfo: {}" , readStructTypeInfo ) ; List < Integer > ids = new ArrayList <> ( ) ; List < String > names = new ArrayList <> ( ) ; List < String > readNames = readStructTypeInfo . getAllStructFieldNames ( ) ; List < String > actualNames = actualStructTypeInfo . getAllStructFieldNames ( ) ; for ( int i = 0 ; i < actualNames . size ( ) ; i ++ ) { String actualName = actualNames . get ( i ) ; if ( readNames . contains ( actualName ) ) { // make sure they are the same type TypeInfo actualTypeInfo = actualStructTypeInfo . getStructFieldTypeInfo ( actualName ) ; TypeInfo readTypeInfo = readStructTypeInfo . getStructFieldTypeInfo ( actualName ) ; if ( ! actualTypeInfo . equals ( readTypeInfo ) ) { throw new IllegalStateException ( "readTypeInfo [" + readTypeInfo + "] does not match actualTypeInfo [" + actualTypeInfo + "]" ) ; } // mark the column as to-be-read ids . add ( i ) ; names . add ( actualName ) ; } } if ( ids . size ( ) == 0 ) { throw new IllegalStateException ( "None of the selected columns were found in the ORC file." ) ; } LOG . info ( "Set column projection on columns: {} ({})" , ids , names ) ; ColumnProjectionUtils . appendReadColumns ( conf , ids , names ) ; } | Sets which fields are to be read from the ORC file | 371 | 13 |
138,924 | protected void addClassEditors ( BuilderModel model , String cprefix ) { List < ComponentClass > classes = model . getComponentClasses ( ) ; int size = classes . size ( ) ; for ( int ii = 0 ; ii < size ; ii ++ ) { ComponentClass cclass = classes . get ( ii ) ; if ( ! cclass . name . startsWith ( cprefix ) ) { continue ; } List < Integer > ccomps = model . getComponents ( cclass ) ; if ( ccomps . size ( ) > 0 ) { add ( new ClassEditor ( model , cclass , ccomps ) ) ; } else { log . info ( "Not creating editor for empty class " + "[class=" + cclass + "]." ) ; } } } | Adds editor user interface elements for each component class to allow the user to select the desired component . | 165 | 19 |
138,925 | public boolean isListening ( ) throws Exception { try { JSONObject resp = new JSONObject ( Get . get ( API_BASE_URL + ":" + API_PORT , Constants . REQUEST_HEARTBEAT , "" ) ) ; return true ; } catch ( Exception e ) { return false ; } } | Returns true if there is RoboRemoteServer currently listening | 68 | 10 |
138,926 | public JSONArray map ( String query , String method_name , Object ... items ) throws Exception { QueryBuilder builder = new QueryBuilder ( API_PORT ) ; builder . map ( query , method_name , items ) ; return builder . execute ( ) ; } | Used to call a method with a list of arguments | 54 | 10 |
138,927 | public static Tracker parseTracker ( JSONObject object ) throws JSONException { final int id = JsonInput . getInt ( object , "id" ) ; final String name = JsonInput . getStringNotNull ( object , "name" ) ; return new Tracker ( id , name ) ; } | Parses a tracker . | 62 | 6 |
138,928 | public static IssueStatus parseStatus ( JSONObject object ) throws JSONException { final int id = JsonInput . getInt ( object , "id" ) ; final String name = JsonInput . getStringNotNull ( object , "name" ) ; final IssueStatus result = new IssueStatus ( id , name ) ; if ( object . has ( "is_default" ) ) result . setDefaultStatus ( JsonInput . getOptionalBool ( object , "is_default" ) ) ; if ( object . has ( "is_closed" ) ) result . setClosed ( JsonInput . getOptionalBool ( object , "is_closed" ) ) ; return result ; } | Parses a status . | 147 | 6 |
138,929 | public static Project parseMinimalProject ( JSONObject content ) throws JSONException { final Project result = new Project ( ) ; result . setId ( JsonInput . getInt ( content , "id" ) ) ; result . setIdentifier ( JsonInput . getStringOrNull ( content , "identifier" ) ) ; result . setName ( JsonInput . getStringNotNull ( content , "name" ) ) ; return result ; } | Parses a minimal version of a project . | 95 | 10 |
138,930 | public static Project parseProject ( JSONObject content ) throws JSONException { final Project result = new Project ( ) ; result . setId ( JsonInput . getInt ( content , "id" ) ) ; result . setIdentifier ( JsonInput . getStringOrNull ( content , "identifier" ) ) ; result . setName ( JsonInput . getStringNotNull ( content , "name" ) ) ; result . setDescription ( JsonInput . getStringOrEmpty ( content , "description" ) ) ; result . setHomepage ( JsonInput . getStringOrEmpty ( content , "homepage" ) ) ; result . setCreatedOn ( getDateOrNull ( content , "created_on" ) ) ; result . setUpdatedOn ( getDateOrNull ( content , "updated_on" ) ) ; final JSONObject parentProject = JsonInput . getObjectOrNull ( content , "parent" ) ; if ( parentProject != null ) result . setParentId ( JsonInput . getInt ( parentProject , "id" ) ) ; result . setTrackers ( JsonInput . getListOrNull ( content , "trackers" , TRACKER_PARSER ) ) ; return result ; } | Parses a project . | 263 | 6 |
138,931 | public int getRenderPriority ( String action , String component , int orientation ) { // because we expect there to be relatively few priority overrides, we simply search // linearly through the list for the closest match int ocount = ( _overrides != null ) ? _overrides . size ( ) : 0 ; for ( int ii = 0 ; ii < ocount ; ii ++ ) { PriorityOverride over = _overrides . get ( ii ) ; // based on the way the overrides are sorted, the first match // is the most specific and the one we want if ( over . matches ( action , component , orientation ) ) { return over . renderPriority ; } } return renderPriority ; } | Returns the render priority appropriate for the specified action orientation and component . | 150 | 13 |
138,932 | public void addPriorityOverride ( PriorityOverride override ) { if ( _overrides == null ) { _overrides = new ComparableArrayList < PriorityOverride > ( ) ; } _overrides . insertSorted ( override ) ; } | Adds the supplied render priority override record to this component class . | 53 | 12 |
138,933 | public int fringesOn ( int first , int second ) { FringeRecord f1 = _frecs . get ( first ) ; // we better have a fringe record for the first if ( null != f1 ) { // it had better have some tilesets defined if ( f1 . tilesets . size ( ) > 0 ) { FringeRecord f2 = _frecs . get ( second ) ; // and we only fringe if second doesn't exist or has a lower // priority if ( ( null == f2 ) || ( f1 . priority > f2 . priority ) ) { return f1 . priority ; } } } return - 1 ; } | If the first base tileset fringes upon the second return the fringe priority of the first base tileset otherwise return - 1 . | 137 | 26 |
138,934 | public FringeTileSetRecord getFringe ( int baseset , int hashValue ) { FringeRecord f = _frecs . get ( baseset ) ; return f . tilesets . get ( hashValue % f . tilesets . size ( ) ) ; } | Get a random FringeTileSetRecord from amongst the ones listed for the specified base tileset . | 56 | 20 |
138,935 | public Window getWindow ( ) { Component parent = getParent ( ) ; while ( ! ( parent instanceof Window ) && parent != null ) { parent = parent . getParent ( ) ; } return ( Window ) parent ; } | from interface FrameManager . ManagedRoot | 47 | 8 |
138,936 | public String getAttributeString ( String attName ) { Object o = attributes . get ( attName ) ; if ( o == null ) { return null ; } else { return ( String ) o ; } } | Get the value for a given attribute . | 43 | 8 |
138,937 | private void maybeSetProperty ( final String name , final String value ) { if ( System . getProperty ( name ) == null ) { System . setProperty ( name , value ) ; } } | Helper to only set a property if not already set . | 40 | 11 |
138,938 | public void render ( Graphics2D gfx ) { Object oalias = SwingUtil . activateAntiAliasing ( gfx ) ; gfx . setColor ( getBackground ( ) ) ; gfx . fill ( _shape ) ; gfx . setColor ( _outline ) ; gfx . draw ( _shape ) ; SwingUtil . restoreAntiAliasing ( gfx , oalias ) ; if ( _icon != null ) { _icon . paintIcon ( _owner . getTarget ( ) , gfx , _ipos . x , _ipos . y ) ; } gfx . setColor ( Color . BLACK ) ; _label . render ( gfx , _lpos . x , _lpos . y ) ; } | Render the chat glyph with no thought to dirty rectangles or restoring composites . | 157 | 16 |
138,939 | public void translate ( int dx , int dy ) { setLocation ( _bounds . x + dx , _bounds . y + dy ) ; } | Attempt to translate this glyph . | 32 | 6 |
138,940 | public static MisoSceneMetrics getSceneMetrics ( ) { return new MisoSceneMetrics ( config . getValue ( TILE_WIDTH_KEY , DEF_TILE_WIDTH ) , config . getValue ( TILE_HEIGHT_KEY , DEF_TILE_HEIGHT ) , config . getValue ( FINE_GRAN_KEY , DEF_FINE_GRAN ) ) ; } | Creates scene metrics with information obtained from the deployed config file . | 91 | 13 |
138,941 | @ Override public void onCreate ( SQLiteDatabase db ) { try { if ( builder . tables == null ) { throw new SQLiteHelperException ( "The array of String tables can't be null!!" ) ; } executePragma ( db ) ; builder . onCreateCallback . onCreate ( db ) ; } catch ( SQLiteHelperException e ) { Log . e ( this . getClass ( ) . toString ( ) , Log . getStackTraceString ( e ) , e ) ; } } | Called when the database is created for the first time . This is where the creation of tables and the initial population of the tables should happen . | 108 | 29 |
138,942 | @ Override public void onUpgrade ( SQLiteDatabase db , int oldVersion , int newVersion ) { try { if ( builder . tableNames == null ) { throw new SQLiteHelperException ( "The array of String tableNames can't be null!!" ) ; } builder . onUpgradeCallback . onUpgrade ( db , oldVersion , newVersion ) ; } catch ( SQLiteHelperException e ) { Log . e ( this . getClass ( ) . toString ( ) , Log . getStackTraceString ( e ) , e ) ; } } | Called when the database needs to be upgraded . The implementation should use this method to drop tables add tables or do anything else it needs to upgrade to the new schema version . | 116 | 35 |
138,943 | static String getHex ( Color color ) { return String . format ( "#%02x%02x%02x%02x" , color . getRed ( ) , color . getGreen ( ) , color . getBlue ( ) , color . getAlpha ( ) ) ; } | create rgba hex from a java color | 60 | 8 |
138,944 | public List < ConnectionListener > getConnectionListeners ( ) { if ( changes == null ) { return ( List < ConnectionListener > ) Collections . EMPTY_LIST ; } List < EventListener > listeners = changes . getListenerList ( AMQP ) ; if ( ( listeners == null ) || listeners . isEmpty ( ) ) { return ( List < ConnectionListener > ) Collections . EMPTY_LIST ; } ArrayList < ConnectionListener > list = new ArrayList < ConnectionListener > ( ) ; for ( EventListener listener : listeners ) { list . add ( ( ConnectionListener ) listener ) ; } return list ; } | Returns the list of ConnectionListeners registered with this AmqpClient instance . | 129 | 16 |
138,945 | public void connect ( String url , String virtualHost , String username , String password ) { if ( websocket != null ) { throw new IllegalStateException ( "AmqpClient already connected" ) ; } this . readyState = ReadyState . CONNECTING ; this . url = url ; this . userName = username ; this . password = password ; this . virtualHost = virtualHost ; this . hasNegotiated = false ; asyncClient . getStateMachine ( ) . enterState ( "handshaking" , "" , this . url ) ; } | Connect to AMQP Broker via Kaazing Gateway | 117 | 11 |
138,946 | public void disconnect ( ) { if ( readyState == ReadyState . OPEN ) { // readyState should be set to ReadyState.CLOSED ONLY AFTER the // the WebSocket has been successfully closed in // socketClosedHandler(). this . closeConnection ( 0 , "" , 0 , 0 , null , null ) ; } else if ( readyState == ReadyState . CONNECTING ) { socketClosedHandler ( ) ; } } | Disconnects from Amqp Server . | 89 | 9 |
138,947 | public AmqpChannel openChannel ( ) { int id = ++ this . channelCount ; AmqpChannel chan = new AmqpChannel ( id , this ) ; channels . put ( id , chan ) ; return chan ; } | Opens a channel on server . | 52 | 7 |
138,948 | void closedHandler ( Object context , String input , Object frame , String stateName ) { if ( getReadyState ( ) == ReadyState . CLOSED ) { return ; } // TODO: Determine whether channels need to be cleaned up. if ( this . channels . size ( ) != 0 ) { for ( int i = 1 ; i <= this . channels . size ( ) ; i ++ ) { // 1-based AmqpChannel channel = this . channels . get ( i ) ; AmqpFrame f = new AmqpFrame ( ) ; // Close each channel which should result in CLOSE event // to be fired for each of the registered ChannelListener(s). f . setMethodName ( "closeChannel" ) ; f . setChannelId ( ( short ) i ) ; channel . channelClosedHandler ( this , "" , f , "closeChannel" ) ; } } try { // Mark the readyState to be CLOSED. readyState = ReadyState . CLOSED ; // Fire CLOSE event for the ConnectionListener(s) registered // on AmqpClient object. fireOnClosed ( new ConnectionEvent ( this , Kind . CLOSE ) ) ; // If the WebSocket(or ByteSocket) is still not closed, then // invoke the close() method. The callback in this case will be a // a no-op as we have completed the book-keeping here. if ( websocket != null ) { websocket . close ( ) ; } } catch ( Exception e1 ) { throw new IllegalStateException ( e1 ) ; } finally { websocket = null ; } } | should be the order following in all our client implementations . | 337 | 11 |
138,949 | private void socketClosedHandler ( ) { // If the book-keeping has already been completed earlier, then // we should just bail. if ( getReadyState ( ) == ReadyState . CLOSED ) { return ; } // TODO: Determine whether channels need to be cleaned up if ( this . channels . size ( ) != 0 ) { // Iterate over the channels and close them. for ( int i = 1 ; i <= this . channels . size ( ) ; i ++ ) { // 1-based AmqpChannel channel = this . channels . get ( i ) ; AmqpFrame f = new AmqpFrame ( ) ; // Close the channel and ensure that the CLOSE event is // fired on the registered ChannelListener objects. f . setMethodName ( "closeChannel" ) ; f . setChannelId ( ( short ) i ) ; channel . channelClosedHandler ( this , "" , f , "closeChannel" ) ; } } // Mark the readyState as CLOSED. readyState = ReadyState . CLOSED ; // Fire the CLOSE event on the ConnectionListener(s) registered on // the AmqpClient object. fireOnClosed ( new ConnectionEvent ( this , Kind . CLOSE ) ) ; } | closing the channels raising events and such . | 262 | 9 |
138,950 | AmqpClient tuneOkConnection ( int channelMax , int frameMax , int heartbeat ) { this . tuneOkConnection ( channelMax , frameMax , heartbeat , null , null ) ; return this ; } | Sends a TuneOkConnection to server . | 43 | 9 |
138,951 | AmqpClient closeOkConnection ( Continuation callback , ErrorHandler error ) { Object [ ] args = { } ; AmqpBuffer bodyArg = null ; String methodName = "closeOkConnection" ; String methodId = "10" + "50" ; AmqpMethod amqpMethod = MethodLookup . LookupMethod ( methodId ) ; Object [ ] arguments = { this , amqpMethod , this . id , args , bodyArg } ; asyncClient . enqueueAction ( methodName , "write" , arguments , callback , error ) ; return this ; } | Sends a CloseOkConnection to server . | 125 | 9 |
138,952 | private void fireOnClosed ( ConnectionEvent e ) { List < EventListener > listeners = changes . getListenerList ( AMQP ) ; for ( EventListener listener : listeners ) { ConnectionListener amqpListener = ( ConnectionListener ) listener ; amqpListener . onConnectionClose ( e ) ; } } | Occurs when the connection to the AMQP server is closed | 66 | 13 |
138,953 | protected CompositedMirage createCompositedMirage ( int index ) { if ( _sources . length == 1 && _sources [ 0 ] . frames instanceof TileSetFrameImage ) { TileSetFrameImage frames = ( TileSetFrameImage ) _sources [ 0 ] . frames ; Rectangle tbounds = new Rectangle ( ) ; frames . getTrimmedBounds ( _orient , index , tbounds ) ; int x = frames . getXOrigin ( _orient , index ) - tbounds . x ; int y = frames . getYOrigin ( _orient , index ) - tbounds . y ; return new SubmirageForwarder ( frames . getTileMirage ( _orient , index ) , x , y ) ; } return new CompositedVolatileMirage ( index ) ; } | Creates a composited image for the specified frame . | 176 | 11 |
138,954 | protected void createComponent ( int componentId , String cclass , String cname , FrameProvider fprov ) { // look up the component class information ComponentClass clazz = _classes . get ( cclass ) ; if ( clazz == null ) { log . warning ( "Non-existent component class" , "class" , cclass , "name" , cname , "id" , componentId ) ; return ; } // create the component CharacterComponent component = new CharacterComponent ( componentId , cname , clazz , fprov ) ; // stick it into the appropriate tables _components . put ( componentId , component ) ; // we have a hash of lists for mapping components by class/name ArrayList < CharacterComponent > comps = _classComps . get ( cclass ) ; if ( comps == null ) { comps = Lists . newArrayList ( ) ; _classComps . put ( cclass , comps ) ; } if ( ! comps . contains ( component ) ) { comps . add ( component ) ; } else { log . info ( "Requested to register the same component twice?" , "comp" , component ) ; } } | Creates a component and inserts it into the component table . | 248 | 12 |
138,955 | public void setFrames ( MultiFrameImage frames ) { if ( frames == null ) { // log.warning("Someone set up us the null frames!", "sprite", this); return ; } // if these are the same frames we already had, no need to do a bunch of pointless business if ( frames == _frames ) { return ; } // set and init our frames _frames = frames ; _frameIdx = 0 ; layout ( ) ; } | Set the image array used to render the sprite . | 94 | 10 |
138,956 | protected void setFrameIndex ( int frameIdx , boolean forceUpdate ) { // make sure we're displaying a valid frame frameIdx = ( frameIdx % _frames . getFrameCount ( ) ) ; // if this is the same frame we're already displaying and we're // not being forced to update, we can stop now if ( frameIdx == _frameIdx && ! forceUpdate ) { return ; } else { _frameIdx = frameIdx ; } // start with our old bounds Rectangle dirty = new Rectangle ( _bounds ) ; // determine our drawing offsets and rendered rectangle size accomodateFrame ( _frameIdx , _frames . getWidth ( _frameIdx ) , _frames . getHeight ( _frameIdx ) ) ; // add our new bounds dirty . add ( _bounds ) ; // give the dirty rectangle to the region manager if ( _mgr != null ) { _mgr . getRegionManager ( ) . addDirtyRegion ( dirty ) ; } } | Instructs the sprite to display the specified frame index . | 216 | 11 |
138,957 | private MetricGroup up_down_host_ ( String host , boolean up ) { final GroupName group = GroupName . valueOf ( getBasePath ( ) , Tags . valueOf ( singletonMap ( "host" , MetricValue . fromStrValue ( host ) ) ) ) ; return new SimpleMetricGroup ( group , singleton ( up ? UP_METRIC : DOWN_METRIC ) ) ; } | Return a metric group indicating if the host is up or down . | 89 | 13 |
138,958 | public static synchronized JspFactory getDefaultFactory ( ) { if ( deflt == null ) { try { Class factory = Class . forName ( "org.apache.jasper.runtime.JspFactoryImpl" ) ; if ( factory != null ) { deflt = ( JspFactory ) factory . newInstance ( ) ; } } catch ( Exception ex ) { } } return deflt ; } | Returns the default factory for this implementation . | 84 | 8 |
138,959 | public VariableInfo [ ] getVariableInfo ( TagData data ) { VariableInfo [ ] result = null ; TagExtraInfo tei = getTagExtraInfo ( ) ; if ( tei != null ) { result = tei . getVariableInfo ( data ) ; } return result ; } | Information on the scripting objects created by this tag at runtime . This is a convenience method on the associated TagExtraInfo class . | 60 | 25 |
138,960 | @ Nullable private String getProperty ( final String name ) { assert name != null ; ensureConfigured ( ) ; return evaluate ( System . getProperty ( name , props . getProperty ( name ) ) ) ; } | Get the value of a property checking system properties then configuration properties and evaluating the result . | 45 | 17 |
138,961 | public static Collection < Attribute > fromJson ( ObjectNode object ) throws IOException { Collection < Attribute > attributes = new HashSet <> ( ) ; convertJsonObject ( attributes , object , "" , 0 , new HashMap <> ( ) ) ; return attributes ; } | Flattens a raw nested json string representation into a collection of attributes . | 60 | 15 |
138,962 | public static String toJsonString ( Collection < Attribute > attributeCollection , ObjectMapper objectMapper ) throws JsonProcessingException { return objectMapper . writeValueAsString ( toObject ( attributeCollection ) ) ; } | Re - expands a flattened json representation from a collection of attributes back into a raw nested json string . | 49 | 20 |
138,963 | public BaseTile getFringeTile ( MisoSceneModel scene , int col , int row , Map < FringeTile , WeakReference < FringeTile > > fringes , Map < Long , BufferedImage > masks ) { // get the tileset id of the base tile we are considering int underset = adjustTileSetId ( scene . getBaseTileId ( col , row ) >> 16 ) ; // start with a clean temporary fringer map _fringers . clear ( ) ; boolean passable = true ; // walk through our influence tiles for ( int y = row - 1 , maxy = row + 2 ; y < maxy ; y ++ ) { for ( int x = col - 1 , maxx = col + 2 ; x < maxx ; x ++ ) { // we sensibly do not consider ourselves if ( ( x == col ) && ( y == row ) ) { continue ; } // determine the tileset for this tile int btid = scene . getBaseTileId ( x , y ) ; int baseset = adjustTileSetId ( ( btid <= 0 ) ? scene . getDefaultBaseTileSet ( ) : ( btid >> 16 ) ) ; // determine if it fringes on our tile int pri = _fringeconf . fringesOn ( baseset , underset ) ; if ( pri == - 1 ) { continue ; } FringerRec fringer = ( FringerRec ) _fringers . get ( baseset ) ; if ( fringer == null ) { fringer = new FringerRec ( baseset , pri ) ; _fringers . put ( baseset , fringer ) ; } // now turn on the appropriate fringebits fringer . bits |= FLAGMATRIX [ y - row + 1 ] [ x - col + 1 ] ; // See if a tile that fringes on us kills our passability, // but don't count the default base tile against us, as // we allow users to splash in the water. if ( passable && ( btid > 0 ) ) { try { BaseTile bt = ( BaseTile ) _tmgr . getTile ( btid ) ; passable = bt . isPassable ( ) ; } catch ( NoSuchTileSetException nstse ) { log . warning ( "Autofringer couldn't find a base set while attempting to " + "figure passability" , nstse ) ; } } } } // if nothing fringed, we're done int numfringers = _fringers . size ( ) ; if ( numfringers == 0 ) { return null ; } // otherwise compose a FringeTile from the specified fringes FringerRec [ ] frecs = new FringerRec [ numfringers ] ; for ( int ii = 0 , pp = 0 ; ii < 16 ; ii ++ ) { FringerRec rec = ( FringerRec ) _fringers . getValue ( ii ) ; if ( rec != null ) { frecs [ pp ++ ] = rec ; } } return composeFringeTile ( frecs , fringes , TileUtil . getTileHash ( col , row ) , passable , masks ) ; } | Compute and return the fringe tile to be inserted at the specified location . | 682 | 15 |
138,964 | protected FringeTile composeFringeTile ( FringerRec [ ] fringers , Map < FringeTile , WeakReference < FringeTile > > fringes , int hashValue , boolean passable , Map < Long , BufferedImage > masks ) { // sort the array so that higher priority fringers get drawn first QuickSort . sort ( fringers ) ; // Generate an identifier for the fringe tile being created as an array of the keys of its // component tiles in the order they'll be drawn in the fringe tile. List < Long > keys = Lists . newArrayList ( ) ; for ( FringerRec fringer : fringers ) { int [ ] indexes = getFringeIndexes ( fringer . bits ) ; FringeConfiguration . FringeTileSetRecord tsr = _fringeconf . getFringe ( fringer . baseset , hashValue ) ; int fringeset = tsr . fringe_tsid ; for ( int index : indexes ) { // Add a key for this tile as a long containing its base tile, the fringe set it's // working with and the index used in that set. keys . add ( ( ( ( long ) fringer . baseset ) << 32 ) + ( fringeset << 16 ) + index ) ; } } long [ ] fringeId = new long [ keys . size ( ) ] ; for ( int ii = 0 ; ii < fringeId . length ; ii ++ ) { fringeId [ ii ] = keys . get ( ii ) ; } FringeTile frTile = new FringeTile ( fringeId , passable ) ; // If the fringes map contains something with the same fringe identifier, this will pull // it out and we can use it instead. WeakReference < FringeTile > result = fringes . get ( frTile ) ; if ( result != null ) { FringeTile fringe = result . get ( ) ; if ( fringe != null ) { return fringe ; } } // There's no fringe with he same identifier, so we need to create the tile. BufferedImage img = null ; for ( FringerRec fringer : fringers ) { int [ ] indexes = getFringeIndexes ( fringer . bits ) ; FringeConfiguration . FringeTileSetRecord tsr = _fringeconf . getFringe ( fringer . baseset , hashValue ) ; for ( int index : indexes ) { try { img = getTileImage ( img , tsr , fringer . baseset , index , hashValue , masks ) ; } catch ( NoSuchTileSetException nstse ) { log . warning ( "Autofringer couldn't find a needed tileset" , nstse ) ; } } } frTile . setImage ( new BufferedMirage ( img ) ) ; fringes . put ( frTile , new WeakReference < FringeTile > ( frTile ) ) ; return frTile ; } | Compose a FringeTile out of the various fringe images needed . | 614 | 14 |
138,965 | protected BufferedImage getTileImage ( BufferedImage img , FringeConfiguration . FringeTileSetRecord tsr , int baseset , int index , int hashValue , Map < Long , BufferedImage > masks ) throws NoSuchTileSetException { int fringeset = tsr . fringe_tsid ; TileSet fset = _tmgr . getTileSet ( fringeset ) ; if ( ! tsr . mask ) { // oh good, this is easy Tile stamp = fset . getTile ( index ) ; return stampTileImage ( stamp , img , stamp . getWidth ( ) , stamp . getHeight ( ) ) ; } // otherwise, it's a mask.. Long maskkey = Long . valueOf ( ( ( ( long ) baseset ) << 32 ) + ( fringeset << 16 ) + index ) ; BufferedImage mask = masks . get ( maskkey ) ; if ( mask == null ) { BufferedImage fsrc = _tmgr . getTileSet ( fringeset ) . getRawTileImage ( index ) ; BufferedImage bsrc = _tmgr . getTileSet ( baseset ) . getRawTileImage ( 0 ) ; mask = ImageUtil . composeMaskedImage ( _imgr , fsrc , bsrc ) ; masks . put ( maskkey , mask ) ; } return stampTileImage ( mask , img , mask . getWidth ( null ) , mask . getHeight ( null ) ) ; } | Retrieve or compose an image for the specified fringe . | 310 | 11 |
138,966 | protected int [ ] getFringeIndexes ( int bits ) { int index = BITS_TO_INDEX [ bits ] ; if ( index != - 1 ) { int [ ] ret = new int [ 1 ] ; ret [ 0 ] = index ; return ret ; } // otherwise, split the bits into contiguous components // look for a zero and start our first split int start = 0 ; while ( ( ( ( 1 << start ) & bits ) != 0 ) && ( start < NUM_FRINGEBITS ) ) { start ++ ; } if ( start == NUM_FRINGEBITS ) { // we never found an empty fringebit, and since index (above) // was already -1, we have no fringe tile for these bits.. sad. return new int [ 0 ] ; } ArrayList < Integer > indexes = Lists . newArrayList ( ) ; int weebits = 0 ; for ( int ii = ( start + 1 ) % NUM_FRINGEBITS ; ii != start ; ii = ( ii + 1 ) % NUM_FRINGEBITS ) { if ( ( ( 1 << ii ) & bits ) != 0 ) { weebits |= ( 1 << ii ) ; } else if ( weebits != 0 ) { index = BITS_TO_INDEX [ weebits ] ; if ( index != - 1 ) { indexes . add ( index ) ; } weebits = 0 ; } } if ( weebits != 0 ) { index = BITS_TO_INDEX [ weebits ] ; if ( index != - 1 ) { indexes . add ( index ) ; } } int [ ] ret = new int [ indexes . size ( ) ] ; for ( int ii = 0 ; ii < ret . length ; ii ++ ) { ret [ ii ] = indexes . get ( ii ) ; } return ret ; } | Get the fringe index specified by the fringebits . If no index is available try breaking down the bits into contiguous regions of bits and look for indexes for those . | 398 | 34 |
138,967 | public Sound getSound ( String path ) { ClipBuffer buffer = null ; if ( _manager . isInitialized ( ) ) { buffer = _manager . getClip ( _provider , path ) ; } return ( buffer == null ) ? new BlankSound ( ) : new Sound ( this , buffer ) ; } | Obtains an instance of the specified sound which can be positioned played looped and otherwise used to make noise . | 65 | 22 |
138,968 | public void dispose ( ) { reclaimAll ( ) ; for ( PooledSource pooled : _sources ) { pooled . source . delete ( ) ; } _sources . clear ( ) ; // remove from the manager _manager . removeGroup ( this ) ; } | Disposes this sound group freeing up the OpenAL sources with which it is associated . All sounds obtained from this group will no longer be usable and should be discarded . | 55 | 33 |
138,969 | public void reclaimAll ( ) { // make sure any bound sources are released for ( PooledSource pooled : _sources ) { if ( pooled . holder != null ) { pooled . holder . stop ( ) ; pooled . holder . reclaim ( ) ; pooled . holder = null ; } } } | Stops and reclaims all sounds from this sound group but does not free the sources . | 61 | 18 |
138,970 | protected void baseGainChanged ( ) { // notify any sound currently holding a source for ( int ii = 0 , nn = _sources . size ( ) ; ii < nn ; ii ++ ) { Sound holder = _sources . get ( ii ) . holder ; if ( holder != null ) { holder . updateSourceGain ( ) ; } } } | Called by the manager when the base gain has changed . | 77 | 12 |
138,971 | protected void setFrameIndex ( int fidx ) { _fidx = fidx ; _bounds . width = _frames . getWidth ( _fidx ) ; _bounds . height = _frames . getHeight ( _fidx ) ; } | Sets the frame index and updates our dimensions . | 56 | 10 |
138,972 | @ Override public synchronized T read ( T dto ) throws Exception { Cursor cursor = db . query ( transformer . getTableName ( ) , transformer . getFields ( ) , transformer . getWhereClause ( dto ) , null , null , null , null ) ; T object = null ; if ( cursor . moveToFirst ( ) ) { object = transformer . transform ( cursor ) ; } return object ; } | Convenience method for reading rows in the database . | 89 | 11 |
138,973 | @ Override public synchronized Collection < T > readAll ( ) throws Exception { Cursor cursor = db . query ( transformer . getTableName ( ) , transformer . getFields ( ) , null , null , null , null , null ) ; Collection < T > list = getAllCursor ( cursor ) ; return list ; } | Convenience method for reading all rows in the table of database . | 69 | 14 |
138,974 | public static int dot ( Point v1s , Point v1e , Point v2s , Point v2e ) { return ( ( v1e . x - v1s . x ) * ( v2e . x - v2s . x ) + ( v1e . y - v1s . y ) * ( v2e . y - v2s . y ) ) ; } | Computes and returns the dot product of the two vectors . | 86 | 12 |
138,975 | public static int dot ( Point vs , Point v1e , Point v2e ) { return ( ( v1e . x - vs . x ) * ( v2e . x - vs . x ) + ( v1e . y - vs . y ) * ( v2e . y - vs . y ) ) ; } | Computes and returns the dot product of the two vectors . The vectors are assumed to start with the same coordinate and end with different coordinates . | 71 | 28 |
138,976 | public static boolean lineIntersection ( Point2D p1 , Point2D p2 , boolean seg1 , Point2D p3 , Point2D p4 , boolean seg2 , Point2D result ) { // see http://astronomy.swin.edu.au/~pbourke/geometry/lineline2d/ double y43 = p4 . getY ( ) - p3 . getY ( ) ; double x21 = p2 . getX ( ) - p1 . getX ( ) ; double x43 = p4 . getX ( ) - p3 . getX ( ) ; double y21 = p2 . getY ( ) - p1 . getY ( ) ; double denom = y43 * x21 - x43 * y21 ; if ( denom == 0 ) { return false ; } double y13 = p1 . getY ( ) - p3 . getY ( ) ; double x13 = p1 . getX ( ) - p3 . getX ( ) ; double ua = ( x43 * y13 - y43 * x13 ) / denom ; if ( seg1 && ( ( ua < 0 ) || ( ua > 1 ) ) ) { return false ; } if ( seg2 ) { double ub = ( x21 * y13 - y21 * x13 ) / denom ; if ( ( ub < 0 ) || ( ub > 1 ) ) { return false ; } } double x = p1 . getX ( ) + ua * x21 ; double y = p1 . getY ( ) + ua * y21 ; result . setLocation ( x , y ) ; return true ; } | Calculate the intersection of two lines . Either line may be considered as a line segment and the intersecting point is only considered valid if it lies upon the segment . Note that Point extends Point2D . | 366 | 42 |
138,977 | public static Rectangle grow ( Rectangle source , Rectangle target ) { if ( target == null ) { log . warning ( "Can't grow with null rectangle [src=" + source + ", tgt=" + target + "]." , new Exception ( ) ) ; } else if ( source == null ) { source = new Rectangle ( target ) ; } else { source . add ( target ) ; } return source ; } | Adds the target rectangle to the bounds of the source rectangle . If the source rectangle is null a new rectangle is created that is the size of the target rectangle . | 88 | 32 |
138,978 | public static Rectangle getTile ( int width , int height , int tileWidth , int tileHeight , int tileIndex ) { Rectangle bounds = new Rectangle ( ) ; getTile ( width , height , tileWidth , tileHeight , tileIndex , bounds ) ; return bounds ; } | Returns the rectangle containing the specified tile in the supplied larger rectangle . Tiles go from left to right top to bottom . | 59 | 24 |
138,979 | public static void getTile ( int width , int height , int tileWidth , int tileHeight , int tileIndex , Rectangle bounds ) { // figure out from whence to crop the tile int tilesPerRow = width / tileWidth ; // if we got a bogus region, return bogus tile bounds if ( tilesPerRow == 0 ) { bounds . setBounds ( 0 , 0 , width , height ) ; } else { int row = tileIndex / tilesPerRow ; int col = tileIndex % tilesPerRow ; // crop the tile-sized image chunk from the full image bounds . setBounds ( tileWidth * col , tileHeight * row , tileWidth , tileHeight ) ; } } | Fills in the bounds of the specified tile in the supplied larger rectangle . Tiles go from left to right top to bottom . | 144 | 26 |
138,980 | private void setNegotiatedExtensions ( String extensionsHeader ) { if ( ( extensionsHeader == null ) || ( extensionsHeader . trim ( ) . length ( ) == 0 ) ) { _negotiatedExtensions = null ; return ; } String [ ] extns = extensionsHeader . split ( "," ) ; List < String > extnNames = new ArrayList < String > ( ) ; for ( String extn : extns ) { String [ ] properties = extn . split ( ";" ) ; String extnName = properties [ 0 ] . trim ( ) ; if ( ! getEnabledExtensions ( ) . contains ( extnName ) ) { String s = String . format ( "Extension '%s' is not an enabled " + "extension so it should not have been negotiated" , extnName ) ; setException ( new WebSocketException ( s ) ) ; return ; } WebSocketExtension extension = WebSocketExtension . getWebSocketExtension ( extnName ) ; WsExtensionParameterValuesSpiImpl paramValues = _negotiatedParameters . get ( extnName ) ; Collection < Parameter < ? > > anonymousParams = extension . getParameters ( Metadata . ANONYMOUS ) ; // Start from the second(0-based) property to parse the name-value // pairs as the first(or 0th) is the extension name. for ( int i = 1 ; i < properties . length ; i ++ ) { String property = properties [ i ] . trim ( ) ; String [ ] pair = property . split ( "=" ) ; Parameter < ? > parameter = null ; String paramValue = null ; if ( pair . length == 1 ) { // We are dealing with an anonymous parameter. Since the // Collection is actually an ArrayList, we are guaranteed to // iterate the parameters in the definition/creation order. // As there is no parameter name, we will just get the next // anonymous Parameter instance and use it for setting the // value. The onus is on the extension implementor to either // use only named parameters or ensure that the anonymous // parameters are defined in the order in which the server // will send them back during negotiation. parameter = anonymousParams . iterator ( ) . next ( ) ; paramValue = pair [ 0 ] . trim ( ) ; } else { parameter = extension . getParameter ( pair [ 0 ] . trim ( ) ) ; paramValue = pair [ 1 ] . trim ( ) ; } if ( parameter . type ( ) != String . class ) { String paramName = parameter . name ( ) ; String s = String . format ( "Negotiated Extension '%s': " + "Type of parameter '%s' should be String" , extnName , paramName ) ; setException ( new WebSocketException ( s ) ) ; return ; } if ( paramValues == null ) { paramValues = new WsExtensionParameterValuesSpiImpl ( ) ; _negotiatedParameters . put ( extnName , paramValues ) ; } paramValues . setParameterValue ( parameter , paramValue ) ; } extnNames . add ( extnName ) ; } HashSet < String > extnsSet = new HashSet < String > ( extnNames ) ; _negotiatedExtensions = unmodifiableCollection ( extnsSet ) ; } | RFC 3864 format . | 707 | 5 |
138,981 | public static int scrollToIndex ( String listRef , int itemIndex ) throws Exception { int listViewIndex = getListViewIndex ( listRef ) ; if ( itemIndex >= numItemsInList ( listRef ) ) throw new Exception ( "Item index is greater than number of items in the list" ) ; // scroll to the top of this view if we already passed the index being looked for QueryBuilder builder = new QueryBuilder ( ) ; int firstVisiblePosition = builder . map ( "solo" , "getCurrentViews" , "android.widget.ListView" ) . call ( "get" , listViewIndex ) . call ( "getFirstVisiblePosition" ) . execute ( ) . getInt ( 0 ) ; if ( firstVisiblePosition > itemIndex ) scrollToTop ( ) ; boolean scrollDown = true ; // need to get the wanted item onto the screen while ( true ) { builder = new QueryBuilder ( ) ; firstVisiblePosition = builder . map ( "solo" , "getCurrentViews" , "android.widget.ListView" ) . call ( "get" , listViewIndex ) . call ( "getFirstVisiblePosition" ) . execute ( ) . getInt ( 0 ) ; builder = new QueryBuilder ( ) ; int headersViewsCount = builder . map ( "solo" , "getCurrentViews" , "android.widget.ListView" ) . call ( "get" , listViewIndex ) . call ( "getHeaderViewsCount" ) . execute ( ) . getInt ( 0 ) ; firstVisiblePosition = firstVisiblePosition - headersViewsCount ; builder = new QueryBuilder ( ) ; int visibleChildCount = builder . map ( "solo" , "getCurrentViews" , "android.widget.ListView" ) . call ( "get" , listViewIndex ) . call ( "getChildCount" ) . execute ( ) . getInt ( 0 ) ; int wantedPosition = itemIndex - firstVisiblePosition ; if ( wantedPosition >= visibleChildCount ) { // check to see if we can even scroll anymore if ( ! scrollDown ) { break ; } scrollDown = Solo . scrollDownList ( listViewIndex ) ; } else { // return the position return wantedPosition ; } } throw new Exception ( "Could not find item" ) ; } | Scrolls the specified item index onto the screen and returns the offset based on the current visible list | 502 | 19 |
138,982 | public int value ( ) { int end = Math . min ( _history . length , _index ) ; int value = 0 ; for ( int ii = 0 ; ii < end ; ii ++ ) { value += _history [ ii ] ; } return ( end > 0 ) ? ( value / end ) : 0 ; } | Returns the current averaged value . | 67 | 6 |
138,983 | protected Frob loop ( String pkgPath , String key , float pan , byte cmd ) { SoundKey skey = new SoundKey ( cmd , pkgPath , key , 0 , _clipVol , pan ) ; addToPlayQueue ( skey ) ; return skey ; // it is a frob } | Loop the specified sound . | 66 | 5 |
138,984 | protected void addToPlayQueue ( SoundKey skey ) { boolean queued = enqueue ( skey , true ) ; if ( queued ) { if ( _verbose . getValue ( ) ) { log . info ( "Sound request [key=" + skey . key + "]." ) ; } } else /* if (_verbose.getValue()) */ { log . warning ( "SoundManager not playing sound because too many sounds in queue " + "[key=" + skey + "]." ) ; } } | Add the sound clip key to the queue to be played . | 109 | 12 |
138,985 | protected boolean enqueue ( SoundKey key , boolean okToStartNew ) { boolean add ; boolean queued ; synchronized ( _queue ) { if ( key . cmd == PLAY && _queue . size ( ) > MAX_QUEUE_SIZE ) { queued = add = false ; } else { _queue . appendLoud ( key ) ; queued = true ; add = okToStartNew && ( _freeSpoolers == 0 ) && ( _spoolerCount < MAX_SPOOLERS ) ; if ( add ) { _spoolerCount ++ ; } } } // and if we need a new thread, add it if ( add ) { Thread spooler = new Thread ( "narya SoundManager line spooler" ) { @ Override public void run ( ) { spoolerRun ( ) ; } } ; spooler . setDaemon ( true ) ; spooler . start ( ) ; } return queued ; } | Enqueue a new SoundKey . | 204 | 7 |
138,986 | protected void spoolerRun ( ) { while ( true ) { try { SoundKey key ; synchronized ( _queue ) { _freeSpoolers ++ ; key = _queue . get ( MAX_WAIT_TIME ) ; _freeSpoolers -- ; if ( key == null || key . cmd == DIE ) { _spoolerCount -- ; // if dying and there are others to kill, do so if ( key != null && _spoolerCount > 0 ) { _queue . appendLoud ( key ) ; } return ; } } // process the command processKey ( key ) ; } catch ( Exception e ) { log . warning ( e ) ; } } } | This is the primary run method of the sound - playing threads . | 145 | 13 |
138,987 | protected void processKey ( SoundKey key ) throws Exception { switch ( key . cmd ) { case PLAY : case LOOP : playSound ( key ) ; break ; case LOCK : if ( ! isTesting ( ) ) { synchronized ( _clipCache ) { try { getClipData ( key ) ; // preload // copy cached to lock map _lockedClips . put ( key , _clipCache . get ( key ) ) ; } catch ( Exception e ) { // don't whine about LOCK failures unless we are verbosely logging if ( _verbose . getValue ( ) ) { throw e ; } } } } break ; case UNLOCK : synchronized ( _clipCache ) { _lockedClips . remove ( key ) ; } break ; } } | Process the requested command in the specified SoundKey . | 161 | 10 |
138,988 | protected byte [ ] getClipData ( SoundKey key ) throws IOException , UnsupportedAudioFileException { byte [ ] [ ] data ; synchronized ( _clipCache ) { // if we're testing, clear all non-locked sounds every time if ( isTesting ( ) ) { _clipCache . clear ( ) ; } data = _clipCache . get ( key ) ; // see if it's in the locked cache (we first look in the regular // clip cache so that locked clips that are still cached continue // to be moved to the head of the LRU queue) if ( data == null ) { data = _lockedClips . get ( key ) ; } if ( data == null ) { // if there is a test sound, JUST use the test sound. InputStream stream = getTestClip ( key ) ; if ( stream != null ) { data = new byte [ 1 ] [ ] ; data [ 0 ] = StreamUtil . toByteArray ( stream ) ; } else { data = _loader . load ( key . pkgPath , key . key ) ; } _clipCache . put ( key , data ) ; } } return ( data . length > 0 ) ? data [ RandomUtil . getInt ( data . length ) ] : null ; } | Called by spooling threads loads clip data from the resource manager or the cache . | 268 | 18 |
138,989 | protected static void adjustVolume ( Line line , float vol ) { FloatControl control = ( FloatControl ) line . getControl ( FloatControl . Type . MASTER_GAIN ) ; // the only problem is that gain is specified in decibals, which is a logarithmic scale. // Since we want max volume to leave the sample unchanged, our // maximum volume translates into a 0db gain. float gain ; if ( vol == 0f ) { gain = control . getMinimum ( ) ; } else { gain = ( float ) ( ( Math . log ( vol ) / Math . log ( 10.0 ) ) * 20.0 ) ; } control . setValue ( gain ) ; //Log.info("Set gain: " + gain); } | Use the gain control to implement volume . | 158 | 8 |
138,990 | protected static void adjustPan ( Line line , float pan ) { try { FloatControl control = ( FloatControl ) line . getControl ( FloatControl . Type . PAN ) ; control . setValue ( pan ) ; } catch ( Exception e ) { log . debug ( "Cannot set pan on line: " + e ) ; } } | Set the pan value for the specified line . | 70 | 9 |
138,991 | public void tick ( long tickStamp ) { if ( _nextTime == - 1 ) { // First time through _nextTime = tickStamp + _initDelay ; } else if ( tickStamp >= _nextTime ) { // If we're repeating, set the next time to run, otherwise, reset if ( _repeatDelay != 0L ) { _nextTime += _repeatDelay ; } else { _nextTime = - 1 ; cancel ( ) ; } expired ( ) ; } } | documentation inherited from FrameParticipant | 107 | 7 |
138,992 | private AffineTransform getRotationTransform ( ) { double theta ; switch ( _orient ) { case NORTH : default : theta = 0.0 ; break ; case SOUTH : theta = Math . PI ; break ; case EAST : theta = Math . PI * 0.5 ; break ; case WEST : theta = - Math . PI * 0.5 ; break ; case NORTHEAST : theta = Math . PI * 0.25 ; break ; case NORTHWEST : theta = - Math . PI * 0.25 ; break ; case SOUTHEAST : theta = Math . PI * 0.75 ; break ; case SOUTHWEST : theta = - Math . PI * 0.75 ; break ; case NORTHNORTHEAST : theta = - Math . PI * 0.125 ; break ; case NORTHNORTHWEST : theta = Math . PI * 0.125 ; break ; case SOUTHSOUTHEAST : theta = - Math . PI * 0.875 ; break ; case SOUTHSOUTHWEST : theta = Math . PI * 0.875 ; break ; case EASTNORTHEAST : theta = - Math . PI * 0.375 ; break ; case EASTSOUTHEAST : theta = - Math . PI * 0.625 ; break ; case WESTNORTHWEST : theta = Math . PI * 0.375 ; break ; case WESTSOUTHWEST : theta = Math . PI * 0.625 ; break ; } return AffineTransform . getRotateInstance ( theta , ( _ox - _oxoff ) + _frames . getWidth ( _frameIdx ) / 2 , ( _oy - _oyoff ) + _frames . getHeight ( _frameIdx ) / 2 ) ; } | Computes and returns the rotation transform for this sprite . | 394 | 11 |
138,993 | public Stream < Entry < MatchedName , MetricValue > > filter ( Context t ) { return t . getTSData ( ) . getCurrentCollection ( ) . get ( this :: match , x -> true ) . stream ( ) . flatMap ( this :: filterMetricsInTsv ) ; } | Create a stream of TimeSeriesMetricDeltas with values . | 64 | 14 |
138,994 | public static final Color blend ( Color c1 , Color c2 ) { return new Color ( ( c1 . getRed ( ) + c2 . getRed ( ) ) >> 1 , ( c1 . getGreen ( ) + c2 . getGreen ( ) ) >> 1 , ( c1 . getBlue ( ) + c2 . getBlue ( ) ) >> 1 ) ; } | Blends the two supplied colors . | 81 | 7 |
138,995 | public static final Color blend ( Color c1 , Color c2 , float firstperc ) { float p2 = 1.0f - firstperc ; return new Color ( ( int ) ( c1 . getRed ( ) * firstperc + c2 . getRed ( ) * p2 ) , ( int ) ( c1 . getGreen ( ) * firstperc + c2 . getGreen ( ) * p2 ) , ( int ) ( c1 . getBlue ( ) * firstperc + c2 . getBlue ( ) * p2 ) ) ; } | Blends the two supplied colors using the supplied percentage as the amount of the first color to use . | 123 | 20 |
138,996 | protected void setupLogging ( @ Nullable final Level level ) { // install JUL adapter SLF4JBridgeHandler . removeHandlersForRootLogger ( ) ; SLF4JBridgeHandler . install ( ) ; // conifgure gossip bootstrap loggers with target factory Log . configure ( LoggerFactory . getILoggerFactory ( ) ) ; log . debug ( "Logging setup; level: {}" , level ) ; } | Setup logging environment . | 94 | 4 |
138,997 | public void addAnimations ( Animation [ ] anims ) { int acount = anims . length ; for ( int ii = 0 ; ii < acount ; ii ++ ) { addAnimation ( anims [ ii ] ) ; } } | Adds the supplied animations to the animation waiter for observation . | 50 | 11 |
138,998 | public static SoundManager createSoundManager ( RunQueue rqueue ) { if ( _soundmgr != null ) { throw new IllegalStateException ( "A sound manager has already been created." ) ; } _soundmgr = new SoundManager ( rqueue ) ; return _soundmgr ; } | Creates initializes and returns the singleton sound manager instance . | 62 | 13 |
138,999 | public void updateStreams ( float time ) { // iterate backwards through the list so that streams can dispose of themselves during // their update for ( int ii = _streams . size ( ) - 1 ; ii >= 0 ; ii -- ) { _streams . get ( ii ) . update ( time ) ; } // delete any finalized objects deleteFinalizedObjects ( ) ; } | Updates all of the streams controlled by the manager . This should be called once per frame by the application . | 80 | 22 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.