idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
7,700
protected JsonWriter property ( String key , Object [ ] array ) throws IOException { return property ( key , Arrays . asList ( array ) ) ; }
Writes an array with the given key name
7,701
protected JsonWriter property ( String key , Iterable < ? > iterable ) throws IOException { Preconditions . checkArgument ( ! inArray ( ) , "Cannot write a property inside an array." ) ; beginArray ( key ) ; for ( Object o : iterable ) { value ( o ) ; } endArray ( ) ; return this ; }
Writes an iterable with the given key name
7,702
protected JsonWriter property ( String key , Iterator < ? > iterator ) throws IOException { return property ( key , Collect . asIterable ( iterator ) ) ; }
Writes an iterator with the given key name
7,703
public JsonWriter property ( String key , Object value ) throws IOException { Preconditions . checkArgument ( ! inArray ( ) , "Cannot write a property inside an array." ) ; writeName ( key ) ; value ( value ) ; return this ; }
Writes a key value pair
7,704
public JsonWriter property ( String key , Map < String , ? > map ) throws IOException { Preconditions . checkArgument ( ! inArray ( ) , "Cannot write a property inside an array." ) ; writeName ( key ) ; value ( map ) ; return this ; }
Writes a map with the given key name
7,705
public JsonWriter value ( Map < String , ? > map ) throws IOException { if ( map == null ) { nullValue ( ) ; } else { boolean inObject = inObject ( ) ; if ( ! inObject ) beginObject ( ) ; for ( Map . Entry < String , ? > entry : map . entrySet ( ) ) { property ( entry . getKey ( ) , entry . getValue ( ) ) ; } if ( ! inObject ) endObject ( ) ; } popIf ( JsonTokenType . NAME ) ; return this ; }
Writes a map
7,706
public JsonWriter value ( Number number ) throws IOException { Preconditions . checkArgument ( inArray ( ) || writeStack . peek ( ) == JsonTokenType . NAME , "Expecting an array or a name, but found " + writeStack . peek ( ) ) ; popIf ( JsonTokenType . NAME ) ; writer . value ( number ) ; return this ; }
Writes a number
7,707
public JsonWriter value ( Object value ) throws IOException { Preconditions . checkArgument ( inArray ( ) || writeStack . peek ( ) == JsonTokenType . NAME , "Expecting an array or a name, but found " + writeStack . peek ( ) ) ; writeObject ( value ) ; popIf ( JsonTokenType . NAME ) ; return this ; }
Writes an array value
7,708
protected JsonWriter writeObject ( Object object ) throws IOException { if ( object == null ) { nullValue ( ) ; } else if ( object instanceof JsonSerializable ) { JsonSerializable structuredSerializable = Cast . as ( object ) ; if ( object instanceof JsonArraySerializable ) { beginArray ( ) ; } else { beginObject ( ) ; } structuredSerializable . toJson ( this ) ; if ( object instanceof JsonArraySerializable ) { endArray ( ) ; } else { endObject ( ) ; } } else if ( object instanceof Number ) { value ( Cast . < Number > as ( object ) ) ; } else if ( object instanceof String ) { value ( Cast . < String > as ( object ) ) ; } else if ( object instanceof Boolean ) { value ( Cast . < Boolean > as ( object ) . toString ( ) ) ; } else if ( object instanceof Enum ) { value ( Cast . < Enum > as ( object ) . name ( ) ) ; } else if ( object instanceof EnumValue ) { value ( Cast . < EnumValue > as ( object ) . name ( ) ) ; } else if ( object instanceof Map ) { value ( Cast . < Map < String , ? > > as ( object ) ) ; } else if ( object . getClass ( ) . isArray ( ) ) { value ( Cast . < Object [ ] > as ( object ) ) ; } else if ( object instanceof Multimap ) { value ( Cast . < Multimap < String , ? > > as ( object ) . asMap ( ) ) ; } else if ( object instanceof Counter ) { value ( Cast . < Counter < String > > as ( object ) . asMap ( ) ) ; } else if ( object instanceof Iterable ) { value ( Cast . < Iterable > as ( object ) ) ; } else if ( object instanceof Iterator ) { value ( Cast . < Iterator > as ( object ) ) ; } else { value ( Convert . convert ( object , String . class ) ) ; } return this ; }
Serializes an object
7,709
private Level mapLogLevel ( final LogLevel logLevel ) { if ( LogLevel . DEBUG . equals ( logLevel ) ) { return Level . DEBUG ; } else if ( LogLevel . TRACE . equals ( logLevel ) ) { return Level . TRACE ; } else if ( LogLevel . INFO . equals ( logLevel ) ) { return Level . INFO ; } else if ( LogLevel . WARN . equals ( logLevel ) ) { return Level . WARN ; } else if ( LogLevel . ERROR . equals ( logLevel ) ) { return Level . ERROR ; } return null ; }
Map the plugin log level to logback log level .
7,710
public URL resolve ( String resource , Class consumer ) { final ClassLoader ccl = Thread . currentThread ( ) . getContextClassLoader ( ) ; final String resourcePath = resolvePath ( resource , consumer ) ; URL contentUrl = null ; if ( ccl != null ) { contentUrl = ccl . getResource ( resourcePath ) ; } if ( contentUrl == null ) { contentUrl = consumer . getResource ( resourcePath ) ; } if ( failOnMissingResource && contentUrl == null ) { throw new AssertionError ( "Resource " + resource + " not found" ) ; } return contentUrl ; }
Resolves a URL of the resource specified using the provided class as hint to start the search . For searching the resource the consumer s classloader is used .
7,711
public < T > void bind ( Class < T > type , SerializerResolver < ? extends T > resolver ) { typeToResolverCache . put ( type , Optional . < SerializerResolver < ? > > of ( resolver ) ) ; boundTypeToResolver . put ( type , resolver ) ; }
Bind a resolver for the given type .
7,712
public void eagerlyInject ( Object target , Field field ) { if ( field . getAnnotation ( Autowired . class ) != null ) { field . setAccessible ( true ) ; Autowired autowired = field . getAnnotation ( Autowired . class ) ; if ( autowired . lazy ( ) == false ) { inject ( target , field ) ; } else { nullify ( target , field ) ; } } }
Eagerly injects the target object s target field . Note that if the field is marked for lazy injection we still inject it but with a null reference . This reference is never seen by user code and is used internally by Iroh to detect when eager injection has delegated the injection process to lazy injection thus preventing multiple injection .
7,713
public void lazilyInject ( Object target , Field field ) { field . setAccessible ( true ) ; if ( isNullified ( target , field ) ) { inject ( target , field ) ; } }
Lazily injects the target object s target field .
7,714
private void inject ( Object target , Field field ) { try { field . set ( target , registrar . resolve ( field ) . getInstance ( ) ) ; } catch ( IllegalArgumentException | IllegalAccessException e ) { throw new IrohException ( e ) ; } }
Performs the actual instance injection .
7,715
private boolean isNullified ( Object target , Field field ) { Class < ? > type = field . getType ( ) ; Object value = null ; try { value = field . get ( target ) ; } catch ( IllegalArgumentException | IllegalAccessException e ) { throw new IrohException ( e ) ; } if ( nulls . containsKey ( type ) ) { if ( nulls . get ( type ) == value ) { return true ; } } return false ; }
Checks whether or not the field value object s reference points to one of our local null object references . If so this indicates that the field was nullified during eager injection and is now eligible for lazy injection .
7,716
private void nullify ( Object target , Field field ) { Class < ? > type = field . getType ( ) ; if ( ! nulls . containsKey ( type ) ) { nulls . put ( type , objenesis . newInstance ( registrar . resolve ( field ) . getType ( ) ) ) ; } try { field . set ( target , nulls . get ( type ) ) ; } catch ( IllegalArgumentException | IllegalAccessException e ) { throw new IrohException ( e ) ; } }
Implements lazy injection by filling in a local null instance of the type required by the field . The original idea was to just define a new location of null itself but Java didn t like that very much so now Iroh will generate a reference for every type it encounters to act as the null for fields of that particular type .
7,717
public static ModelConstants getInstance ( ) throws KbRuntimeException { try { if ( instance == null ) { instance = new ModelConstants ( ) ; } return instance ; } catch ( KbException e ) { throw new KbRuntimeException ( "Once of the private final fields in com.cyc.library.model.ModelConstants could not be instantiated, can not proceed further." , e ) ; } }
This is not part of the KB API
7,718
private boolean isAllowed ( Field field ) { return ClassUtils . isPrimitiveOrWrapper ( field . getType ( ) ) || CharSequence . class . isAssignableFrom ( field . getType ( ) ) || List . class . isAssignableFrom ( field . getType ( ) ) ; }
Verifies if the given field follow the rules .
7,719
private void evaluateObject ( ) { if ( evaluatedClasses . contains ( clazz ) ) { return ; } Field [ ] fields = clazz . getDeclaredFields ( ) ; for ( Field field : fields ) { if ( field . isAnnotationPresent ( ModelField . class ) && ! isAllowed ( field ) ) { throw new RuntimeException ( "Field '" + field . getName ( ) + "' has type '" + field . getType ( ) . getSimpleName ( ) + "' that is not allowed!" ) ; } } evaluatedClasses . add ( clazz ) ; }
Evaluates the object if not yet evaluated .
7,720
private static Fields toFieldEnum ( Field field ) { Class < ? > clazz = field . getType ( ) ; String name = clazz . getSimpleName ( ) . toLowerCase ( ) ; if ( name . equals ( "int" ) || name . equals ( "integer" ) ) { return Fields . INT ; } else if ( name . equals ( "long" ) ) { return Fields . LONG ; } else if ( name . equals ( "float" ) ) { return Fields . FLOAT ; } else if ( name . equals ( "double" ) ) { return Fields . DOUBLE ; } else if ( CharSequence . class . isAssignableFrom ( clazz ) ) { return Fields . STRING ; } else if ( name . equals ( "boolean" ) ) { return Fields . BOOLEAN ; } else if ( clazz . isAssignableFrom ( List . class ) ) { ParameterizedType listType = ( ParameterizedType ) field . getGenericType ( ) ; Class < ? > listClass = ( Class < ? > ) listType . getActualTypeArguments ( ) [ 0 ] ; if ( listClass . toString ( ) . equals ( "class java.lang.String" ) ) { return Fields . LIST ; } } throw new RuntimeException ( "Field not found!" ) ; }
Return a Fields object for a given field s Class .
7,721
public T fromJson ( JSONObject json ) { T object = null ; try { object = clazz . newInstance ( ) ; ( ( Model ) object ) . setContext ( context ) ; Field [ ] fields = clazz . getDeclaredFields ( ) ; try { for ( Field field : fields ) { if ( ! field . isAnnotationPresent ( ModelField . class ) ) { continue ; } String name = field . getName ( ) ; boolean was = field . isAccessible ( ) ; field . setAccessible ( true ) ; switch ( toFieldEnum ( field ) ) { case INT : field . setInt ( object , json . optInt ( name , 0 ) ) ; break ; case LONG : field . setLong ( object , json . optLong ( name , 0 ) ) ; break ; case FLOAT : field . setFloat ( object , json . optLong ( name , 0 ) ) ; break ; case DOUBLE : field . setDouble ( object , json . optDouble ( name , 0 ) ) ; break ; case STRING : field . set ( object , json . opt ( name ) ) ; break ; case BOOLEAN : field . setBoolean ( object , json . optBoolean ( name , false ) ) ; break ; case LIST : JSONArray list = json . optJSONArray ( name ) ; try { if ( list != null ) { List < String > stringList = new ArrayList < > ( ) ; for ( int i = 0 ; i < list . length ( ) ; i ++ ) { stringList . add ( list . getString ( i ) ) ; } field . set ( object , stringList ) ; } } catch ( JSONException e ) { } break ; } field . setAccessible ( was ) ; } } catch ( IllegalAccessException e ) { e . printStackTrace ( ) ; } } catch ( IllegalAccessException | InstantiationException e ) { e . printStackTrace ( ) ; } return object ; }
Analyzes the entire json object and creates a brand - new ... instance from its representation .
7,722
public JSONObject toJson ( ) { JSONObject json = new JSONObject ( ) ; Field [ ] fields = clazz . getDeclaredFields ( ) ; try { for ( Field field : fields ) { if ( ! field . isAnnotationPresent ( ModelField . class ) ) { continue ; } String name = field . getName ( ) ; boolean was = field . isAccessible ( ) ; field . setAccessible ( true ) ; switch ( toFieldEnum ( field ) ) { case INT : json . put ( name , field . getInt ( this ) ) ; break ; case LONG : json . put ( name , field . getLong ( this ) ) ; break ; case FLOAT : json . put ( name , field . getFloat ( this ) ) ; break ; case DOUBLE : json . put ( name , field . getDouble ( this ) ) ; break ; case STRING : json . put ( name , field . get ( this ) ) ; break ; case BOOLEAN : json . put ( name , field . getBoolean ( this ) ) ; break ; case LIST : JSONArray list = new JSONArray ( ) ; List < String > stringList = ( List < String > ) field . get ( this ) ; if ( stringList != null ) { for ( String value : stringList ) { list . put ( value ) ; } } json . put ( name , list ) ; break ; } field . setAccessible ( was ) ; } } catch ( IllegalAccessException | JSONException e ) { e . printStackTrace ( ) ; } return json ; }
Analyzes the entire object and creates a brand - new json ... representation .
7,723
protected SharedPreferences loadSharedPreferences ( String namespace ) { if ( context == null ) { throw new NoContextFoundException ( ) ; } return context . getSharedPreferences ( clazz . getPackage ( ) . getName ( ) + "." + clazz . getName ( ) + "." + namespace , Context . MODE_PRIVATE ) ; }
Loads a reference to the SharedPreferences for a given ... namespace .
7,724
private List < String > getObjectList ( ) { if ( cachedIds != null ) return cachedIds ; SharedPreferences prefs = loadSharedPreferences ( "objectList" ) ; String list = prefs . getString ( "list" , null ) ; cachedIds = ( list == null ) ? new ArrayList < String > ( ) : new ArrayList < > ( Arrays . asList ( list . split ( "," ) ) ) ; return cachedIds ; }
Get a list of objects ids .
7,725
private void addObject ( ) { SharedPreferences prefs = loadSharedPreferences ( "objectList" ) ; List < String > objects = getObjectList ( ) ; objects . add ( getId ( ) ) ; prefs . edit ( ) . putString ( "list" , StringUtils . join ( objects , "," ) ) . commit ( ) ; }
Adds the object to the ids list .
7,726
private boolean removeObject ( ) { SharedPreferences prefs = loadSharedPreferences ( "objectList" ) ; List < String > objects = getObjectList ( ) ; int index = objects . indexOf ( getId ( ) ) ; if ( index == ArrayUtils . INDEX_NOT_FOUND ) return false ; objects . remove ( getId ( ) ) ; if ( objects . size ( ) == 0 ) { prefs . edit ( ) . putString ( "list" , null ) . commit ( ) ; } else { prefs . edit ( ) . putString ( "list" , StringUtils . join ( objects , "," ) ) . commit ( ) ; } return true ; }
Removes the object from the ids list .
7,727
public synchronized void save ( ) { SharedPreferences prefs = loadSharedPreferences ( "object" ) ; if ( find ( getId ( ) ) == null ) { addObject ( ) ; modelListenerHandler . execOnUpdateListeners ( this , OnUpdateListener . Status . CREATED ) ; if ( cache && cachedObjects != null ) { cachedObjects . add ( ( T ) this ) ; } } else { modelListenerHandler . execOnUpdateListeners ( this , OnUpdateListener . Status . UPDATED ) ; } prefs . edit ( ) . putString ( String . valueOf ( getId ( ) ) , toJson ( ) . toString ( ) ) . commit ( ) ; }
Saves the current object .
7,728
public synchronized boolean remove ( ) { SharedPreferences prefs = loadSharedPreferences ( "object" ) ; if ( find ( getId ( ) ) != null ) { if ( ! removeObject ( ) ) return false ; modelListenerHandler . execOnUpdateListeners ( this , OnUpdateListener . Status . REMOVED ) ; prefs . edit ( ) . putString ( String . valueOf ( getId ( ) ) , null ) . commit ( ) ; return true ; } return false ; }
Removes the current object .
7,729
public T find ( String id ) { SharedPreferences prefs = loadSharedPreferences ( "object" ) ; JSONObject object = null ; try { String json = prefs . getString ( String . valueOf ( id ) , null ) ; if ( json == null ) return null ; object = new JSONObject ( json ) ; } catch ( JSONException e ) { e . printStackTrace ( ) ; } return fromJson ( object ) ; }
Find a specific object from its id .
7,730
public List < T > findAll ( ) { if ( cache && cachedObjects != null ) { return cachedObjects ; } List < String > ids = getObjectList ( ) ; List < T > listT = new ArrayList < > ( ) ; for ( String id : ids ) { listT . add ( find ( id ) ) ; } if ( cache ) { cachedObjects = listT ; } return listT ; }
Find all objects of type T .
7,731
public void showHelp ( ) { System . err . println ( applicationDescription ) ; System . err . println ( "===============================================" ) ; Map < NamedOption , String > optionNames = new HashMap < > ( ) ; optionSet . forEach ( option -> { String out = Stream . concat ( Stream . of ( option . getAliasSpecifications ( ) ) , Stream . of ( option . getSpecification ( ) ) ) . sorted ( ( s1 , s2 ) -> Integer . compare ( s1 . length ( ) , s2 . length ( ) ) ) . collect ( Collectors . joining ( ", " ) ) ; if ( option . isRequired ( ) ) { out += " *" ; } optionNames . put ( option , out ) ; } ) ; int maxArgName = optionNames . values ( ) . stream ( ) . mapToInt ( String :: length ) . max ( ) . orElse ( 10 ) ; optionNames . entrySet ( ) . stream ( ) . sorted ( Map . Entry . comparingByValue ( ) ) . forEach ( entry -> { String arg = entry . getValue ( ) ; boolean insertSpace = ! arg . startsWith ( "--" ) ; if ( insertSpace ) { System . err . print ( " " ) ; } System . err . printf ( "%1$-" + maxArgName + "s\t" , arg ) ; System . err . println ( entry . getKey ( ) . getDescription ( ) ) ; } ) ; System . err . println ( "===============================================" ) ; System . err . println ( "* = Required" ) ; }
Prints help to standard error showing the application description if set and the list of valid command line arguments with those required arguments marked with an asterisk .
7,732
public Set < Map . Entry < String , String > > getSetEntries ( ) { Set < Map . Entry < String , String > > entries = optionSet . stream ( ) . filter ( this :: isSet ) . map ( no -> Tuple2 . of ( no . getName ( ) , Convert . convert ( no . getValue ( ) , String . class ) ) ) . collect ( Collectors . toSet ( ) ) ; entries . addAll ( unamedOptions . entrySet ( ) ) ; return entries ; }
Gets options and values for everything passed in to the command line including unamed options .
7,733
public static Set < String > readStopwords ( BufferedReader reader ) throws IOException { HashSet < String > words = new HashSet < String > ( ) ; String nextLine ; while ( ( ( nextLine = reader . readLine ( ) ) != null ) ) { words . add ( nextLine . trim ( ) . toLowerCase ( ) ) ; } return words ; }
Read stopwords in memory from a file one per line . Stopwords are converted to lowercase when read .
7,734
public static Map < String , Double > readIdfs ( BufferedReader reader , int N ) throws IOException { HashMap < String , Double > idfs = new HashMap < String , Double > ( ) ; String nextLine ; while ( ( ( nextLine = reader . readLine ( ) ) != null ) ) { String [ ] parts = nextLine . split ( "\\t+" ) ; checkArgument ( parts . length >= 2 ) ; Double df = Double . parseDouble ( parts [ 1 ] ) ; idfs . put ( parts [ 0 ] , Math . log ( 1.0 + N / df ) ) ; } return idfs ; }
Computes inverse document frequencies as a map of Strings to Doubles from a tab separated file of term document frequencies .
7,735
public static int getNumberOfLines ( Reader in ) throws IOException { LineNumberReader lnr = new LineNumberReader ( in ) ; lnr . skip ( Long . MAX_VALUE ) ; in . close ( ) ; return lnr . getLineNumber ( ) ; }
Computes the number of files in the input Reader .
7,736
public static double getDistanceTo ( ShanksSimulation simulation , PercipientShanksAgent agent , Object o ) { Location agentLocation = agent . getCurrentLocation ( ) ; if ( agentLocation . is3DLocation ( ) ) { try { ContinuousPortrayal3D devicesPortrayal = ( ContinuousPortrayal3D ) simulation . getScenarioPortrayal ( ) . getPortrayals ( ) . get ( Scenario3DPortrayal . MAIN_DISPLAY_ID ) . get ( ScenarioPortrayal . DEVICES_PORTRAYAL ) ; Continuous3D devicesField = ( Continuous3D ) devicesPortrayal . getField ( ) ; Double3D objectLocation = devicesField . getObjectLocationAsDouble3D ( o ) ; return agentLocation . getLocation3D ( ) . distance ( objectLocation ) ; } catch ( DuplicatedPortrayalIDException e ) { e . printStackTrace ( ) ; } catch ( ScenarioNotFoundException e ) { e . printStackTrace ( ) ; } catch ( ShanksException e ) { e . printStackTrace ( ) ; } } if ( agentLocation . is2DLocation ( ) ) { try { ContinuousPortrayal2D devicesPortrayal = ( ContinuousPortrayal2D ) simulation . getScenarioPortrayal ( ) . getPortrayals ( ) . get ( Scenario2DPortrayal . MAIN_DISPLAY_ID ) . get ( ScenarioPortrayal . DEVICES_PORTRAYAL ) ; Continuous2D devicesField = ( Continuous2D ) devicesPortrayal . getField ( ) ; Double2D objectLocation = devicesField . getObjectLocation ( o ) ; return agentLocation . getLocation2D ( ) . distance ( objectLocation ) ; } catch ( DuplicatedPortrayalIDException e ) { e . printStackTrace ( ) ; } catch ( ScenarioNotFoundException e ) { e . printStackTrace ( ) ; } catch ( ShanksException e ) { e . printStackTrace ( ) ; } } return Double . MAX_VALUE ; }
Get the distance from the agent to an object in the simulation
7,737
public static Location getObjectLocation ( ShanksSimulation simulation , PercipientShanksAgent agent , Object object ) { try { if ( agent . getCurrentLocation ( ) . is3DLocation ( ) ) { ContinuousPortrayal3D devicesPortrayal ; devicesPortrayal = ( ContinuousPortrayal3D ) simulation . getScenarioPortrayal ( ) . getPortrayals ( ) . get ( Scenario3DPortrayal . MAIN_DISPLAY_ID ) . get ( ScenarioPortrayal . DEVICES_PORTRAYAL ) ; Continuous3D devicesField = ( Continuous3D ) devicesPortrayal . getField ( ) ; Double3D loc = devicesField . getObjectLocation ( object ) ; return new Location ( loc ) ; } else if ( agent . getCurrentLocation ( ) . is2DLocation ( ) ) { ContinuousPortrayal2D devicesPortrayal = ( ContinuousPortrayal2D ) simulation . getScenarioPortrayal ( ) . getPortrayals ( ) . get ( Scenario2DPortrayal . MAIN_DISPLAY_ID ) . get ( ScenarioPortrayal . DEVICES_PORTRAYAL ) ; Continuous2D devicesField = ( Continuous2D ) devicesPortrayal . getField ( ) ; Double2D loc = devicesField . getObjectLocation ( object ) ; return new Location ( loc ) ; } } catch ( DuplicatedPortrayalIDException e ) { e . printStackTrace ( ) ; } catch ( ScenarioNotFoundException e ) { e . printStackTrace ( ) ; } catch ( ShanksException e ) { e . printStackTrace ( ) ; } return null ; }
Get the location of an object in the simulation
7,738
public static Location getRandomObjectLocationInPerceptionRange ( ShanksSimulation simulation , PercipientShanksAgent agent ) { Location agentLocation = agent . getCurrentLocation ( ) ; try { if ( agentLocation . is3DLocation ( ) ) { ContinuousPortrayal3D devicesPortrayal = ( ContinuousPortrayal3D ) simulation . getScenarioPortrayal ( ) . getPortrayals ( ) . get ( Scenario3DPortrayal . MAIN_DISPLAY_ID ) . get ( ScenarioPortrayal . DEVICES_PORTRAYAL ) ; Continuous3D devicesField = ( Continuous3D ) devicesPortrayal . getField ( ) ; Bag objects = devicesField . getObjectsWithinDistance ( agentLocation . getLocation3D ( ) , agent . getPerceptionRange ( ) , false ) ; if ( objects . size ( ) == 1 && objects . get ( 0 ) . equals ( agent ) ) { return null ; } Object o ; Double3D newTarget = null ; do { int size = objects . size ( ) ; o = objects . get ( simulation . random . nextInt ( size ) ) ; newTarget = devicesField . getObjectLocation ( o ) ; } while ( o . equals ( agent ) ) ; return new Location ( newTarget ) ; } else if ( agentLocation . is2DLocation ( ) ) { ContinuousPortrayal2D devicesPortrayal = ( ContinuousPortrayal2D ) simulation . getScenarioPortrayal ( ) . getPortrayals ( ) . get ( Scenario2DPortrayal . MAIN_DISPLAY_ID ) . get ( ScenarioPortrayal . DEVICES_PORTRAYAL ) ; Continuous2D devicesField = ( Continuous2D ) devicesPortrayal . getField ( ) ; Bag objects = devicesField . getObjectsWithinDistance ( agentLocation . getLocation2D ( ) , agent . getPerceptionRange ( ) , false ) ; Object o ; Double2D newTarget = null ; do { int size = objects . size ( ) ; o = objects . get ( simulation . random . nextInt ( size ) ) ; newTarget = devicesField . getObjectLocation ( o ) ; } while ( o . equals ( agent ) ) ; return new Location ( newTarget ) ; } } catch ( Exception e ) { e . printStackTrace ( ) ; } return null ; }
Get a random object location in the perception range of the agent .
7,739
public static Bag getAllObjects ( ShanksSimulation simulation , PercipientShanksAgent agent ) { Location agentLocation = agent . getCurrentLocation ( ) ; if ( agentLocation . is3DLocation ( ) ) { try { ContinuousPortrayal3D devicesPortrayal = ( ContinuousPortrayal3D ) simulation . getScenarioPortrayal ( ) . getPortrayals ( ) . get ( Scenario3DPortrayal . MAIN_DISPLAY_ID ) . get ( ScenarioPortrayal . DEVICES_PORTRAYAL ) ; Continuous3D devicesField = ( Continuous3D ) devicesPortrayal . getField ( ) ; Bag objects = devicesField . getAllObjects ( ) ; return objects ; } catch ( DuplicatedPortrayalIDException e ) { e . printStackTrace ( ) ; } catch ( ScenarioNotFoundException e ) { e . printStackTrace ( ) ; } catch ( ShanksException e ) { e . printStackTrace ( ) ; } } else if ( agentLocation . is2DLocation ( ) ) { try { ContinuousPortrayal2D devicesPortrayal = ( ContinuousPortrayal2D ) simulation . getScenarioPortrayal ( ) . getPortrayals ( ) . get ( Scenario2DPortrayal . MAIN_DISPLAY_ID ) . get ( ScenarioPortrayal . DEVICES_PORTRAYAL ) ; Continuous2D devicesField = ( Continuous2D ) devicesPortrayal . getField ( ) ; Bag objects = devicesField . getAllObjects ( ) ; return objects ; } catch ( DuplicatedPortrayalIDException e ) { e . printStackTrace ( ) ; } catch ( ScenarioNotFoundException e ) { e . printStackTrace ( ) ; } catch ( ShanksException e ) { e . printStackTrace ( ) ; } } return null ; }
To obtain all objects in the simulation
7,740
public static byte [ ] hash ( byte [ ] data , String alg ) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest . getInstance ( alg ) ; return md . digest ( data ) ; }
Hashes data with the specified hashing algorithm .
7,741
public static byte [ ] md2Hash ( String data , Charset charset ) throws NoSuchAlgorithmException { return md2Hash ( data . getBytes ( charset ) ) ; }
Hashes a string using the MD2 algorithm .
7,742
public static String md2Hex ( String data , Charset charset ) throws NoSuchAlgorithmException { return md2Hex ( data . getBytes ( charset ) ) ; }
Hashes a string using the MD2 algorithm . Returns a hexadecimal result .
7,743
public static byte [ ] md5Hash ( String data , Charset charset ) throws NoSuchAlgorithmException { return md5Hash ( data . getBytes ( charset ) ) ; }
Hashes a string using the MD5 algorithm .
7,744
public static String md5Hex ( String data , Charset charset ) throws NoSuchAlgorithmException { return md5Hex ( data . getBytes ( charset ) ) ; }
Hashes a string using the MD5 algorithm . Returns a hexadecimal result .
7,745
public static byte [ ] sha1Hash ( String data , Charset charset ) throws NoSuchAlgorithmException { return sha1Hash ( data . getBytes ( charset ) ) ; }
Hashes a string using the SHA - 1 algorithm .
7,746
public static String sha1Hex ( String data , Charset charset ) throws NoSuchAlgorithmException { return sha1Hex ( data . getBytes ( charset ) ) ; }
Hashes a string using the SHA - 1 algorithm . Returns a hexadecimal result .
7,747
public static byte [ ] sha224Hash ( String data , Charset charset ) throws NoSuchAlgorithmException { return sha224Hash ( data . getBytes ( charset ) ) ; }
Hashes a string using the SHA - 224 algorithm .
7,748
public static String sha224Hex ( String data , Charset charset ) throws NoSuchAlgorithmException { return sha224Hex ( data . getBytes ( charset ) ) ; }
Hashes a string using the SHA - 224 algorithm . Returns a hexadecimal result .
7,749
public static byte [ ] sha256Hash ( String data , Charset charset ) throws NoSuchAlgorithmException { return sha256Hash ( data . getBytes ( charset ) ) ; }
Hashes a string using the SHA - 256 algorithm .
7,750
public static String sha256Hex ( String data , Charset charset ) throws NoSuchAlgorithmException { return sha256Hex ( data . getBytes ( charset ) ) ; }
Hashes a string using the SHA - 256 algorithm . Returns a hexadecimal result .
7,751
public static byte [ ] sha384Hash ( String data , Charset charset ) throws NoSuchAlgorithmException { return sha384Hash ( data . getBytes ( charset ) ) ; }
Hashes a string using the SHA - 384 algorithm .
7,752
public static String sha384Hex ( String data , Charset charset ) throws NoSuchAlgorithmException { return sha384Hex ( data . getBytes ( charset ) ) ; }
Hashes a string using the SHA - 384 algorithm . Returns a hexadecimal result .
7,753
public static byte [ ] sha512Hash ( String data , Charset charset ) throws NoSuchAlgorithmException { return sha512Hash ( data . getBytes ( charset ) ) ; }
Hashes a string using the SHA - 512 algorithm .
7,754
public static String sha512Hex ( String data , Charset charset ) throws NoSuchAlgorithmException { return sha512Hex ( data . getBytes ( charset ) ) ; }
Hashes a string using the SHA - 512 algorithm . Returns a hexadecimal result .
7,755
public static String ceylonRepoPath ( final String groupId , final String artifactId , final String version , final String classifier , final String extension ) { StringBuilder path = new StringBuilder ( STRING_BUILDER_SIZE ) ; path . append ( formatAsDirectory ( groupId ) ) . append ( PATH_SEPARATOR ) ; path . append ( artifactId ) . append ( PATH_SEPARATOR ) ; path . append ( version ) . append ( PATH_SEPARATOR ) ; path . append ( ceylonModuleName ( groupId , artifactId , version , classifier , extension ) ) ; return path . toString ( ) ; }
Determines the relative path of a module atifact within a Ceylon repo .
7,756
public static String ceylonModuleName ( final String groupId , final String artifactId , final String version , final String classifier , final String extension ) { if ( version == null || "" . equals ( version ) || version . contains ( "-" ) ) { throw new IllegalArgumentException ( " Null, empty, or '-' is not allowed in version" ) ; } StringBuilder name = new StringBuilder ( STRING_BUILDER_SIZE ) ; name . append ( ceylonModuleBaseName ( groupId , artifactId ) ) . append ( ARTIFACT_SEPARATOR ) . append ( version ) ; if ( extension != null ) { name . append ( GROUP_SEPARATOR ) . append ( extension ) ; } else { name . append ( GROUP_SEPARATOR ) . append ( "car" ) ; } return name . toString ( ) ; }
Comes up with a Ceylon module name based on Maven coordinates .
7,757
public static String calculateChecksum ( final File installedFile ) throws MojoExecutionException { int bufsize = CHECKSUM_BUFFER_SIZE ; byte [ ] buffer = new byte [ bufsize ] ; FileInputStream fis = null ; BufferedInputStream bis = null ; String checksum = null ; try { MessageDigest sha1 = MessageDigest . getInstance ( "SHA-1" ) ; fis = new FileInputStream ( installedFile ) ; sha1 . reset ( ) ; int size = fis . read ( buffer , 0 , bufsize ) ; while ( size >= 0 ) { sha1 . update ( buffer , 0 , size ) ; size = fis . read ( buffer , 0 , bufsize ) ; } checksum = String . format ( "%040x" , new BigInteger ( 1 , sha1 . digest ( ) ) ) ; } catch ( Exception e ) { throw new MojoExecutionException ( "Failed to calculate digest checksum for " + installedFile , e ) ; } finally { IOUtil . close ( bis ) ; IOUtil . close ( fis ) ; } if ( checksum != null ) { return checksum ; } else { throw new MojoExecutionException ( "Failed to calculate digest checksum for " + installedFile ) ; } }
Calculates the SHA1 checksum for a file using a crude method .
7,758
public static void extractFile ( final ZipInputStream in , final File outdir , final String name ) throws IOException { byte [ ] buffer = new byte [ BUFFER_SIZE ] ; BufferedOutputStream out = new BufferedOutputStream ( new FileOutputStream ( new File ( outdir , name ) ) ) ; int count = - 1 ; while ( ( count = in . read ( buffer ) ) != - 1 ) { out . write ( buffer , 0 , count ) ; } out . close ( ) ; }
Extracts a single file from a zip archive .
7,759
public static void mkdirs ( final File outdir , final String path ) { File d = new File ( outdir , path ) ; if ( ! d . exists ( ) ) { d . mkdirs ( ) ; } }
Creates directories from an existing file to an additional path .
7,760
public static String dirpart ( final String path ) { int s = path . lastIndexOf ( File . separatorChar ) ; if ( s != - 1 ) { return path . substring ( 0 , s ) ; } else { return null ; } }
Returns the directory part of path string .
7,761
public static void addSoftEvidences ( BayesianReasonerShanksAgent agent , HashMap < String , HashMap < String , Double > > softEvidences ) throws ShanksException { ShanksAgentBayesianReasoningCapability . addSoftEvidences ( agent . getBayesianNetwork ( ) , softEvidences ) ; }
Add a set of soft - evidences to the Bayesian network to reason with it .
7,762
public static String normalize ( String val ) { if ( val == null || val . trim ( ) . length ( ) == 0 ) return null ; return val . trim ( ) ; }
Normalizes the given string by trimming it if non - null and returning null if null or empty .
7,763
public static String validate ( String name , String value , int maxLen ) throws IllegalArgumentException { String normVal = normalize ( value ) ; if ( normVal == null ) { throw new IllegalArgumentException ( "A value must be specified for" + " '" + name + "'" ) ; } else if ( normVal . length ( ) > maxLen ) { throw new IllegalArgumentException ( "The value specified for" + " '" + name + "' was too long. It must not exceed" + " " + maxLen + " characters." ) ; } return normVal ; }
Checks that the given value s normalized length is in the allowed range .
7,764
public static String validate ( String name , String value , String [ ] validValues ) throws IllegalArgumentException { String normVal = validate ( name , value , Integer . MAX_VALUE ) ; StringBuilder s = new StringBuilder ( ) ; for ( int i = 0 ; i < validValues . length ; i ++ ) { if ( i > 0 ) { s . append ( ", " ) ; } s . append ( "'" ) ; s . append ( validValues [ i ] ) ; s . append ( "'" ) ; if ( normVal . equals ( validValues [ i ] ) ) return normVal ; } throw new IllegalArgumentException ( "One of the following values must" + " be specified for '" + name + "': [ " + s . toString ( ) + " ]" ) ; }
Checks that the given value s normalized form is one of the allowed values .
7,765
public void changeProperty ( String propertyName , Object propertyValue ) throws ShanksException { this . properties . put ( propertyName , propertyValue ) ; this . checkStatus ( ) ; }
If the property exists this method changes it . If not this method creates it .
7,766
public List < String > getPossibleStates ( ) { List < String > copy = new ArrayList < String > ( ) ; for ( String possibleStatus : states . keySet ( ) ) { copy . add ( possibleStatus ) ; } return copy ; }
This method only returns a copy of the list if you modify the copy the internal list of PossibleStates will be not modified . To interact with the real list use addPossibleStatus and removePossibleStatus methods
7,767
public final void addParser ( final ParserConfig parser ) { Contract . requireArgNotNull ( "parser" , parser ) ; if ( parsers == null ) { parsers = new Parsers ( ) ; } parsers . addParser ( parser ) ; }
Adds a parser to the configuration . If the list of parsers does not exist it will be created .
7,768
public final Folder findTargetFolder ( final String generatorName , final String artifactName ) throws ProjectNameNotDefinedException , ArtifactNotFoundException , FolderNameNotDefinedException , GeneratorNotFoundException , ProjectNotFoundException , FolderNotFoundException { Contract . requireArgNotNull ( "generatorName" , generatorName ) ; Contract . requireArgNotNull ( "artifactName" , artifactName ) ; return findTargetFolder ( generatorName , artifactName , null ) ; }
Returns a target directory for a given combination of generator name and artifact name .
7,769
public final Folder findTargetFolder ( final String generatorName , final String artifactName , final String targetPath ) throws ProjectNameNotDefinedException , ArtifactNotFoundException , FolderNameNotDefinedException , GeneratorNotFoundException , ProjectNotFoundException , FolderNotFoundException { Contract . requireArgNotNull ( "generatorName" , generatorName ) ; Contract . requireArgNotNull ( "artifactName" , artifactName ) ; final GeneratorConfig generator = generators . findByName ( generatorName ) ; int idx = generator . getArtifacts ( ) . indexOf ( new Artifact ( artifactName ) ) ; if ( idx < 0 ) { throw new ArtifactNotFoundException ( generatorName , artifactName ) ; } final Artifact artifact = generator . getArtifacts ( ) . get ( idx ) ; final String projectName ; final String folderName ; final String targetPattern ; final Target target = artifact . findTargetFor ( targetPath ) ; if ( target == null ) { projectName = artifact . getDefProject ( ) ; folderName = artifact . getDefFolder ( ) ; targetPattern = null ; } else { projectName = target . getDefProject ( ) ; folderName = target . getDefFolder ( ) ; targetPattern = target . getPattern ( ) ; } if ( projectName == null ) { throw new ProjectNameNotDefinedException ( generatorName , artifactName , targetPattern ) ; } if ( folderName == null ) { throw new FolderNameNotDefinedException ( generatorName , artifactName , targetPattern ) ; } idx = projects . indexOf ( new Project ( projectName , "dummy" ) ) ; if ( idx < 0 ) { throw new ProjectNotFoundException ( generatorName , artifactName , targetPattern , projectName ) ; } final Project project = projects . get ( idx ) ; idx = project . getFolders ( ) . indexOf ( new Folder ( folderName , "NotUsed" ) ) ; if ( idx < 0 ) { throw new FolderNotFoundException ( generatorName , artifactName , targetPattern , projectName , folderName ) ; } return project . getFolders ( ) . get ( idx ) ; }
Returns a target directory for a given combination of generator name artifact name and target sub path .
7,770
public final List < GeneratorConfig > findGeneratorsForParser ( final String parserName ) { Contract . requireArgNotNull ( "parserName" , parserName ) ; final List < GeneratorConfig > list = new ArrayList < > ( ) ; final List < GeneratorConfig > gcList = generators . getList ( ) ; for ( final GeneratorConfig gc : gcList ) { if ( gc . getParser ( ) . equals ( parserName ) ) { list . add ( gc ) ; } } return list ; }
Find all generators that are connected to a given parser .
7,771
public static SrcGen4JConfig createMavenStyleSingleProject ( final SrcGen4JContext context , final String projectName , final File rootDir ) { Contract . requireArgNotNull ( "context" , context ) ; Contract . requireArgNotNull ( ROOT_DIR_VAR , rootDir ) ; FileExistsValidator . requireArgValid ( ROOT_DIR_VAR , rootDir ) ; IsDirectoryValidator . requireArgValid ( ROOT_DIR_VAR , rootDir ) ; Contract . requireArgNotNull ( "projectName" , projectName ) ; final SrcGen4JConfig config = new SrcGen4JConfig ( ) ; final List < Project > projects = new ArrayList < > ( ) ; final Project project = new Project ( projectName , "." ) ; project . setMaven ( true ) ; projects . add ( project ) ; config . setProjects ( projects ) ; config . init ( context , rootDir ) ; return config ; }
Creates a new configuration with a single project and a Maven directory structure .
7,772
public final void addTarget ( final Target target ) { Contract . requireArgNotNull ( "target" , target ) ; if ( targets == null ) { targets = new ArrayList < > ( ) ; } targets . add ( target ) ; }
Adds a target to the list . If the list does not exist it s created .
7,773
public final void resolve ( Number value ) { future . complete ( new Tree ( ( Tree ) null , null , value ) ) ; }
Resolves the value of the current Promise with the given numeric value .
7,774
public final void resolve ( String value ) { future . complete ( new Tree ( ( Tree ) null , null , value ) ) ; }
Resolves the value of the current Promise with the given text .
7,775
public final void resolve ( Date value ) { future . complete ( new Tree ( ( Tree ) null , null , value ) ) ; }
Resolves the value of the current Promise with the given date .
7,776
public final void resolve ( UUID value ) { future . complete ( new Tree ( ( Tree ) null , null , value ) ) ; }
Resolves the value of the current Promise with the given UUID .
7,777
public final void resolve ( InetAddress value ) { future . complete ( new Tree ( ( Tree ) null , null , value ) ) ; }
Resolves the value of the current Promise with the given InetAddress .
7,778
public static < T > Source < T > empty ( ) { return new AbstractSource < T > ( ) { public T computeNext ( ) { return endOfData ( ) ; } } ; }
Gets an empty source .
7,779
public static < T > Source < T > from ( T ... items ) { return from ( Arrays . asList ( items ) ) ; }
Gets a source from the given items .
7,780
public static < T > Source < T > from ( Collection < T > collection ) { return from ( collection . iterator ( ) ) ; }
Gets a source from the items in the given collection .
7,781
public static < T > Source < T > from ( final Iterator < T > iterator ) { return new AbstractSource < T > ( ) { protected T computeNext ( ) throws IOException { if ( iterator . hasNext ( ) ) { return iterator . next ( ) ; } return endOfData ( ) ; } } ; }
Gets a source from the items in the given iterator .
7,782
public static ExceptionDescriptor parseStackTrace ( final Collection < String > lines ) { if ( ( lines == null ) || lines . isEmpty ( ) ) { throw new IllegalArgumentException ( "No stack trace provided." ) ; } try { final Builder b = new Builder ( ) ; final Collection < ExceptionLine > parsedLines = new ExceptionParser ( ) . parse ( lines ) ; parsedLines . forEach ( b :: addLine ) ; return b . build ( ) ; } catch ( final ExceptionParseException e ) { return null ; } }
Take a chunk of log and try to parse an exception out of it .
7,783
public static String get ( Bundle bundle ) { String applicationPath = ApplicationPath . get ( bundle ) ; if ( applicationPath == null ) { return null ; } if ( ! hasHalDocs ( bundle ) ) { return null ; } return get ( applicationPath ) ; }
Gets documentation URI path .
7,784
public static boolean hasHalDocs ( Bundle bundle ) { return bundle . getResource ( ServiceModelReader . DOCS_CLASSPATH_PREFIX + "/" + ServiceModelReader . SERVICE_DOC_FILE ) != null ; }
Checks if the given bundle has documentation metadata stored as resource .
7,785
public static File getClassJar ( Class clazz ) { File file = null ; try { file = new File ( clazz . getProtectionDomain ( ) . getCodeSource ( ) . getLocation ( ) . toURI ( ) ) ; } catch ( URISyntaxException e ) { } return file ; }
Gets the jar file a class is contained in .
7,786
public static List < String > listZipContents ( File zipFile , String path ) throws IOException { List < String > names = new ArrayList < > ( ) ; if ( zipFile . isFile ( ) ) { ZipFile zip = null ; try { zip = new ZipFile ( zipFile ) ; Enumeration < ? extends ZipEntry > entries = zip . entries ( ) ; while ( entries . hasMoreElements ( ) ) { ZipEntry entry = entries . nextElement ( ) ; String name = entry . getName ( ) ; if ( ! entry . isDirectory ( ) && name . startsWith ( path ) ) { names . add ( name ) ; } } } finally { close ( zip ) ; } } return names ; }
Lists the contents of a zip file . Only looks in the supplied path within the zip file .
7,787
public int getFieldCount ( ) { int result = 0 ; for ( Argument a : arguments ) { if ( a instanceof FactoryDefinition . SerializedArgument ) { result ++ ; } } return result ; }
Get the number of fields this factory covers .
7,788
public int getScore ( Map < String , Object > data ) { if ( ! hasSerializedFields ) { return 0 ; } int score = 0 ; for ( Argument arg : arguments ) { if ( arg instanceof FactoryDefinition . SerializedArgument ) { if ( data . containsKey ( ( ( SerializedArgument ) arg ) . name ) ) { score ++ ; } } } return score ; }
Get a score for this factory based on the given data . The higher the score the more arguments were found .
7,789
@ SuppressWarnings ( "unchecked" ) public T create ( Map < String , Object > data ) { Object [ ] args = new Object [ arguments . length ] ; for ( int i = 0 , n = args . length ; i < n ; i ++ ) { args [ i ] = arguments [ i ] . getValue ( data ) ; } try { return ( T ) raw . newInstance ( args ) ; } catch ( IllegalArgumentException e ) { throw new SerializationException ( "Unable to create; " + e . getMessage ( ) , e ) ; } catch ( InstantiationException e ) { throw new SerializationException ( "Unable to create; " + e . getMessage ( ) , e ) ; } catch ( IllegalAccessException e ) { throw new SerializationException ( "Unable to create; " + e . getMessage ( ) , e ) ; } catch ( InvocationTargetException e ) { throw new SerializationException ( "Unable to create; " + e . getCause ( ) . getMessage ( ) , e . getCause ( ) ) ; } }
Create a new instance using the given deserialized data . The data is only used if this factory has any serialized fields .
7,790
@ SuppressWarnings ( "unchecked" ) public T create ( Object [ ] args ) { for ( int i = 0 , n = args . length ; i < n ; i ++ ) { if ( arguments [ i ] instanceof FactoryDefinition . InjectedArgument ) { args [ i ] = arguments [ i ] . getValue ( null ) ; } } try { return ( T ) raw . newInstance ( args ) ; } catch ( IllegalArgumentException e ) { throw new SerializationException ( "Unable to create; " + e . getMessage ( ) , e ) ; } catch ( InstantiationException e ) { throw new SerializationException ( "Unable to create; " + e . getMessage ( ) , e ) ; } catch ( IllegalAccessException e ) { throw new SerializationException ( "Unable to create; " + e . getMessage ( ) , e ) ; } catch ( InvocationTargetException e ) { throw new SerializationException ( "Unable to create; " + e . getCause ( ) . getMessage ( ) , e . getCause ( ) ) ; } }
Create a new instance using a plain arguments array .
7,791
public void addTimeChart ( String chartID , String xAxisLabel , String yAxisLabel ) throws ShanksException { if ( ! this . timeCharts . containsKey ( chartID ) ) { TimeSeriesChartGenerator chart = new TimeSeriesChartGenerator ( ) ; chart . setTitle ( chartID ) ; chart . setXAxisLabel ( xAxisLabel ) ; chart . setYAxisLabel ( yAxisLabel ) ; this . timeCharts . put ( chartID , chart ) ; } else { throw new DuplicatedChartIDException ( chartID ) ; } }
Add a chart to the simulation
7,792
public void addDataToDataSerieInTimeChart ( String chartID , String dataSerieID , double x , double y ) throws ShanksException { if ( this . containsDataSerieInTimeChart ( chartID , dataSerieID ) ) { this . timeChartData . get ( chartID ) . get ( dataSerieID ) . add ( x , y , true ) ; } else { try { this . addDataSerieToTimeChart ( chartID , dataSerieID ) ; this . timeChartData . get ( chartID ) . get ( dataSerieID ) . add ( x , y , true ) ; } catch ( DuplicatedDataSerieIDException e ) { e . printStackTrace ( ) ; } } }
Add a datum in the chart
7,793
public void addScatterPlot ( String scatterID , String xAxisLabel , String yAxisLabel ) throws ShanksException { if ( ! this . timeCharts . containsKey ( scatterID ) ) { ScatterPlotGenerator scatter = new ScatterPlotGenerator ( ) ; scatter . setTitle ( scatterID ) ; scatter . setXAxisLabel ( xAxisLabel ) ; scatter . setYAxisLabel ( yAxisLabel ) ; this . scatterPlots . put ( scatterID , scatter ) ; } else { throw new DuplicatedChartIDException ( scatterID ) ; } }
Add a ScatterPlot to the simulation
7,794
public void addDataSerieToScatterPlot ( String scatterID , double [ ] [ ] dataSerie ) { if ( this . scatterPlots . containsKey ( scatterID ) ) { this . scatterPlotsData . put ( scatterID , dataSerie ) ; this . scatterPlots . get ( scatterID ) . addSeries ( ( double [ ] [ ] ) this . scatterPlotsData . get ( scatterID ) , scatterID , null ) ; } }
Sets the data for the scatterPlot . Should be used only the first time . Use updateDataSerieOnScaterPlot to change the data
7,795
public void updateDataSerieOnScatterPlot ( String scatterID , int index , double [ ] [ ] dataSerie ) { if ( this . scatterPlots . containsKey ( scatterID ) ) { if ( this . scatterPlotsData . containsKey ( scatterID ) ) { double [ ] [ ] current = this . scatterPlotsData . get ( scatterID ) ; this . scatterPlotsData . put ( scatterID , concatenateArrays ( current , dataSerie ) ) ; } else { addDataSerieToScatterPlot ( scatterID , dataSerie ) ; return ; } this . scatterPlots . get ( scatterID ) . updateSeries ( index , this . scatterPlotsData . get ( scatterID ) ) ; } }
Updates the data in the scatterPlot
7,796
public void addHistogram ( String histogramID , String xAxisLabel , String yAxisLabel ) throws ShanksException { if ( ! this . histograms . containsKey ( histogramID ) ) { HistogramGenerator histogram = new HistogramGenerator ( ) ; histogram . setTitle ( histogramID ) ; histogram . setXAxisLabel ( xAxisLabel ) ; histogram . setYAxisLabel ( yAxisLabel ) ; this . histograms . put ( histogramID , histogram ) ; } else { throw new DuplicatedChartIDException ( histogramID ) ; } }
Add a histogram to the simulation
7,797
public void setHistogramRange ( String histogramID , int lower , int upper ) { if ( this . histograms . containsKey ( histogramID ) ) this . histograms . get ( histogramID ) . setYAxisRange ( lower , upper ) ; }
Set the histogram range to be displayed
7,798
public void removeDataSerieFromHistogram ( String histogramID , int index ) { if ( this . histograms . containsKey ( histogramID ) ) { this . histograms . get ( histogramID ) . removeSeries ( index ) ; } }
Deletes a certain series of data from the histogram . The index will be the order of the histogram .
7,799
private double [ ] [ ] concatenateArrays ( double [ ] [ ] first , double [ ] [ ] second ) { double [ ] [ ] result = new double [ first . length ] [ first [ 0 ] . length + second [ 0 ] . length ] ; for ( int i = 0 ; i < first . length ; i ++ ) { for ( int j = 0 ; j < ( first [ i ] . length + second [ i ] . length ) ; j ++ ) { if ( j < first [ i ] . length ) { result [ i ] [ j ] = first [ i ] [ j ] ; } else { result [ i ] [ j ] = second [ i ] [ j - first [ i ] . length ] ; } } } return result ; }
Concatenate two two dimensional arrays . Both arrays must have the same dimensions .