idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
140,500
protected void handleErrors ( Collection < Throwable > errors , Object event ) { if ( this . globalExceptionHandler == null ) { for ( Throwable error : errors ) { LOG . error ( "Failed to dispatch event {}" , event , error ) ; } } else { this . globalExceptionHandler . handleErrors ( event , errors . toArray ( new Throwable [ errors . size ( ) ] ) ) ; } }
This method is called if errors occurred while dispatching events .
91
12
140,501
public BtrpOperand go ( BtrPlaceTree parent ) { append ( token , "Unhandled token " + token . getText ( ) + " (type=" + token . getType ( ) + ")" ) ; return IgnorableOperand . getInstance ( ) ; }
Parse the root of the tree .
60
8
140,502
public IgnorableOperand ignoreError ( Exception e ) { append ( token , e . getMessage ( ) ) ; return IgnorableOperand . getInstance ( ) ; }
Report an error from an exception for the current token
36
10
140,503
public IgnorableOperand ignoreErrors ( ErrorReporter err ) { errors . getErrors ( ) . addAll ( err . getErrors ( ) ) ; return IgnorableOperand . getInstance ( ) ; }
Add all the error messages included in a reporter .
47
10
140,504
public IgnorableOperand ignoreError ( Token t , String msg ) { append ( t , msg ) ; return IgnorableOperand . getInstance ( ) ; }
Add an error message to a given error
34
8
140,505
public void append ( Token t , String msg ) { errors . append ( t . getLine ( ) , t . getCharPositionInLine ( ) , msg ) ; }
Add an error message related to a given token
36
9
140,506
public T execute ( ) { if ( isWindows ( ) ) { return onWindows ( ) ; } else if ( isMac ( ) ) { return onMac ( ) ; } else if ( isUnix ( ) ) { return onUnix ( ) ; } else if ( isSolaris ( ) ) { return onSolaris ( ) ; } else { throw new IllegalStateException ( "Invalid operating system " + os ) ; } }
Main method that should be executed . This will return the proper result depending on your platform .
90
18
140,507
public BtrpOperand expand ( ) { String head = getChild ( 0 ) . getText ( ) . substring ( 0 , getChild ( 0 ) . getText ( ) . length ( ) - 1 ) ; String tail = getChild ( getChildCount ( ) - 1 ) . getText ( ) . substring ( 1 ) ; BtrpSet res = new BtrpSet ( 1 , BtrpOperand . Type . STRING ) ; for ( int i = 1 ; i < getChildCount ( ) - 1 ; i ++ ) { BtrpOperand op = getChild ( i ) . go ( this ) ; if ( op == IgnorableOperand . getInstance ( ) ) { return op ; } BtrpSet s = ( BtrpSet ) op ; for ( BtrpOperand o : s . getValues ( ) ) { //Compose res . getValues ( ) . add ( new BtrpString ( head + o . toString ( ) + tail ) ) ; } } return res ; }
Expand the enumeration . Variables are not evaluated nor checked
225
13
140,508
public void add ( DepTreeNode child ) { if ( children == null ) { children = new HashMap < String , DepTreeNode > ( ) ; } children . put ( child . getName ( ) , child ) ; child . setParent ( this ) ; }
Add the specified node to this node s children .
56
10
140,509
public void overlay ( DepTreeNode node ) { if ( node . defineDependencies != null || node . requireDependencies != null ) { setDependencies ( node . defineDependencies , node . requireDependencies , node . dependentFeatures , node . lastModified ( ) , node . lastModifiedDep ( ) ) ; } node . uri = uri ; if ( node . getChildren ( ) == null ) { return ; } for ( Map . Entry < String , DepTreeNode > entry : node . getChildren ( ) . entrySet ( ) ) { DepTreeNode existing = getChild ( entry . getKey ( ) ) ; if ( existing == null ) { add ( entry . getValue ( ) ) ; } else { existing . overlay ( entry . getValue ( ) ) ; } } }
Overlay the specified node and its descendants over this node . The specified node will be merged with this node with the dependencies of any nodes from the specified node replacing the dependencies of the corresponding node in this node s tree .
175
44
140,510
public DepTreeNode createOrGet ( String path , URI uri ) { if ( path . startsWith ( "/" ) ) { //$NON-NLS-1$ throw new IllegalArgumentException ( path ) ; } if ( path . length ( ) == 0 ) return this ; String [ ] pathComps = path . split ( "/" ) ; //$NON-NLS-1$ DepTreeNode node = this ; int i = 0 ; for ( String comp : pathComps ) { DepTreeNode childNode = node . getChild ( comp ) ; if ( childNode == null ) { childNode = new DepTreeNode ( comp , i == pathComps . length - 1 ? uri : null ) ; node . add ( childNode ) ; } node = childNode ; i ++ ; } return node ; }
Returns the node at the specified path location within the tree or creates it if it is not already in the tree . Will create any required parent nodes .
179
30
140,511
public void remove ( DepTreeNode child ) { if ( children != null ) { DepTreeNode node = children . get ( child . getName ( ) ) ; if ( node == child ) { children . remove ( child . getName ( ) ) ; } } child . setParent ( null ) ; }
Removes the specified child node
64
6
140,512
public void prune ( ) { if ( children != null ) { List < String > removeList = new ArrayList < String > ( ) ; for ( Entry < String , DepTreeNode > entry : children . entrySet ( ) ) { DepTreeNode child = entry . getValue ( ) ; child . prune ( ) ; if ( ( child . defineDependencies == null && child . requireDependencies == null && child . uri == null ) && ( child . children == null || child . children . isEmpty ( ) ) ) { removeList . add ( entry . getKey ( ) ) ; } } for ( String key : removeList ) { children . remove ( key ) ; } } }
Recursively walks the node tree removing folder nodes that have not children .
150
15
140,513
public void setDependencies ( String [ ] defineDependencies , String [ ] requireDependencies , String [ ] dependentFeatures , long lastModifiedFile , long lastModifiedDep ) { this . defineDependencies = defineDependencies ; this . requireDependencies = requireDependencies ; this . dependentFeatures = dependentFeatures ; this . lastModified = lastModifiedFile ; this . lastModifiedDep = lastModifiedDep ; }
Specifies the dependency list of modules for the module named by this node along with the last modified date of the javascript file that the dependency list was obtained from .
98
32
140,514
private long lastModifiedDepTree ( long lm ) { long result = ( defineDependencies == null && requireDependencies == null ) ? lm : Math . max ( lm , this . lastModifiedDep ) ; if ( children != null ) { for ( Entry < String , DepTreeNode > entry : this . children . entrySet ( ) ) { result = entry . getValue ( ) . lastModifiedDepTree ( result ) ; } } return result ; }
Returns the most recent last modified date for all the dependencies that are descendants of this node including this node .
103
21
140,515
void populateDepMap ( Map < String , DependencyInfo > depMap ) { if ( uri != null ) { depMap . put ( getFullPathName ( ) , new DependencyInfo ( defineDependencies , requireDependencies , dependentFeatures , uri ) ) ; } if ( children != null ) { for ( Entry < String , DepTreeNode > entry : children . entrySet ( ) ) { entry . getValue ( ) . populateDepMap ( depMap ) ; } } }
Populates the provided map with the dependencies keyed by full path name . This is done to facilitate more efficient lookups of the dependencies .
106
28
140,516
private void readObject ( ObjectInputStream in ) throws IOException , ClassNotFoundException { // Call the default implementation to de-serialize our object in . defaultReadObject ( ) ; parent = new WeakReference < DepTreeNode > ( null ) ; // restore parent reference on all children if ( children != null ) { for ( Entry < String , DepTreeNode > entry : children . entrySet ( ) ) { entry . getValue ( ) . setParent ( this ) ; } } }
Method called when this object is de - serialized
103
10
140,517
protected ServiceTracker < IOptions , ? > getOptionsServiceTracker ( BundleContext bundleContext ) throws InvalidSyntaxException { ServiceTracker < IOptions , ? > tracker = new ServiceTracker < IOptions , Object > ( bundleContext , bundleContext . createFilter ( "(&(" + Constants . OBJECTCLASS + "=" + IOptions . class . getName ( ) + //$NON-NLS-1$ //$NON-NLS-2$ ")(name=" + getServletBundleName ( ) + "))" ) , //$NON-NLS-1$ //$NON-NLS-2$ null ) ; tracker . open ( ) ; return tracker ; }
Returns an opened ServiceTracker for the Aggregator options . Aggregator options are created by the bundle activator and are shared by all Aggregator instances created from the same bundle .
153
38
140,518
protected ServiceTracker < IExecutors , ? > getExecutorsServiceTracker ( BundleContext bundleContext ) throws InvalidSyntaxException { ServiceTracker < IExecutors , ? > tracker = new ServiceTracker < IExecutors , Object > ( bundleContext , bundleContext . createFilter ( "(&(" + Constants . OBJECTCLASS + "=" + IExecutors . class . getName ( ) + //$NON-NLS-1$ //$NON-NLS-2$ ")(name=" + getServletBundleName ( ) + "))" ) , //$NON-NLS-1$ //$NON-NLS-2$ null ) ; tracker . open ( ) ; return tracker ; }
Returns an opened ServiceTracker for the Aggregator exectors provider . The executors provider is are created by the bundle activator and is shared by all Aggregator instances created from the same bundle .
163
42
140,519
public String createCacheBundle ( String bundleSymbolicName , String bundleFileName ) throws IOException { final String sourceMethod = "createCacheBundle" ; //$NON-NLS-1$ final boolean isTraceLogging = log . isLoggable ( Level . FINER ) ; if ( isTraceLogging ) { log . entering ( sourceClass , sourceMethod , new Object [ ] { bundleSymbolicName , bundleFileName } ) ; } // Serialize the cache getCacheManager ( ) . serializeCache ( ) ; // De-serialize the control file to obtain the cache control data File controlFile = new File ( getWorkingDirectory ( ) , CacheControl . CONTROL_SERIALIZATION_FILENAME ) ; CacheControl control = null ; ObjectInputStream ois = new ObjectInputStream ( new FileInputStream ( controlFile ) ) ; ; try { control = ( CacheControl ) ois . readObject ( ) ; } catch ( Exception ex ) { throw new IOException ( ex ) ; } finally { IOUtils . closeQuietly ( ois ) ; } if ( control . getInitStamp ( ) != 0 ) { return Messages . AggregatorImpl_3 ; } // create the bundle manifest InputStream is = AggregatorImpl . class . getClassLoader ( ) . getResourceAsStream ( MANIFEST_TEMPLATE ) ; StringWriter writer = new StringWriter ( ) ; CopyUtil . copy ( is , writer ) ; String template = writer . toString ( ) ; String manifest = MessageFormat . format ( template , new Object [ ] { Long . toString ( new Date ( ) . getTime ( ) ) , getContributingBundle ( ) . getHeaders ( ) . get ( "Bundle-Version" ) , //$NON-NLS-1$ bundleSymbolicName , AggregatorUtil . getCacheBust ( this ) } ) ; // create the jar File bundleFile = new File ( bundleFileName ) ; ZipUtil . Packer packer = new ZipUtil . Packer ( ) ; packer . open ( bundleFile ) ; try { packer . packEntryFromStream ( "META-INF/MANIFEST.MF" , new ByteArrayInputStream ( manifest . getBytes ( "UTF-8" ) ) , new Date ( ) . getTime ( ) ) ; //$NON-NLS-1$ //$NON-NLS-2$ packer . packDirectory ( getWorkingDirectory ( ) , JAGGR_CACHE_DIRECTORY ) ; } finally { packer . close ( ) ; } String result = bundleFile . getCanonicalPath ( ) ; if ( isTraceLogging ) { log . exiting ( sourceClass , sourceMethod , result ) ; } return result ; }
Command handler to create a cache primer bundle containing the contents of the cache directory .
614
16
140,520
public String processRequestUrl ( String requestUrl ) throws IOException , ServletException { ConsoleHttpServletRequest req = new ConsoleHttpServletRequest ( getServletConfig ( ) . getServletContext ( ) , requestUrl ) ; OutputStream nulOutputStream = new OutputStream ( ) { @ Override public void write ( int b ) throws IOException { } } ; ConsoleHttpServletResponse resp = new ConsoleHttpServletResponse ( nulOutputStream ) ; doGet ( req , resp ) ; return Integer . toString ( resp . getStatus ( ) ) ; }
Implementation of eponymous console command . Provided to allow cache priming requests to be issued via the server console by automation scripts .
123
26
140,521
public void add ( VMTransitionBuilder b ) { Map < VMState , VMTransitionBuilder > m = vmAMB2 . get ( b . getDestinationState ( ) ) ; for ( VMState src : b . getSourceStates ( ) ) { m . put ( src , b ) ; } }
Add a builder for a VM . Every builder that supports the same transition will be replaced .
66
18
140,522
public boolean remove ( VMTransitionBuilder b ) { Map < VMState , VMTransitionBuilder > m = vmAMB2 . get ( b . getDestinationState ( ) ) ; for ( VMState src : b . getSourceStates ( ) ) { m . remove ( src ) ; } return true ; }
Remove a builder for an action on a VM .
67
10
140,523
public VMTransitionBuilder getBuilder ( VMState srcState , VMState dstState ) { Map < VMState , VMTransitionBuilder > dstCompliant = vmAMB2 . get ( dstState ) ; if ( dstCompliant == null ) { return null ; } return dstCompliant . get ( srcState ) ; }
Get the model builder for a given transition
69
8
140,524
public static TransitionFactory newBundle ( ) { TransitionFactory f = new TransitionFactory ( ) ; f . add ( new BootVM . Builder ( ) ) ; f . add ( new ShutdownVM . Builder ( ) ) ; f . add ( new SuspendVM . Builder ( ) ) ; f . add ( new ResumeVM . Builder ( ) ) ; f . add ( new KillVM . Builder ( ) ) ; f . add ( new RelocatableVM . Builder ( ) ) ; f . add ( new ForgeVM . Builder ( ) ) ; f . add ( new StayAwayVM . BuilderReady ( ) ) ; f . add ( new StayAwayVM . BuilderSleeping ( ) ) ; f . add ( new StayAwayVM . BuilderInit ( ) ) ; f . add ( new BootableNode . Builder ( ) ) ; f . add ( new ShutdownableNode . Builder ( ) ) ; return f ; }
a new factory that embeds the default builders .
197
10
140,525
public int getMaxBW ( Node n1 , Node n2 ) { int max = Integer . MAX_VALUE ; for ( Link inf : getPath ( n1 , n2 ) ) { if ( inf . getCapacity ( ) < max ) { max = inf . getCapacity ( ) ; } Switch sw = inf . getSwitch ( ) ; if ( sw . getCapacity ( ) >= 0 && sw . getCapacity ( ) < max ) { //The >= 0 stays for historical reasons max = sw . getCapacity ( ) ; } } return max ; }
Get the maximal bandwidth available between two nodes .
121
9
140,526
protected List < Link > getFirstPhysicalPath ( List < Link > currentPath , Switch sw , Node dst ) { // Iterate through the current switch's links for ( Link l : net . getConnectedLinks ( sw ) ) { // Wrong link if ( currentPath . contains ( l ) ) { continue ; } // Go through the link currentPath . add ( l ) ; // Check what is after if ( l . getElement ( ) instanceof Node ) { // Node found, path complete if ( l . getElement ( ) . equals ( dst ) ) { return currentPath ; } } else { // Go to the next switch List < Link > recall = getFirstPhysicalPath ( currentPath , l . getSwitch ( ) . equals ( sw ) ? ( Switch ) l . getElement ( ) : l . getSwitch ( ) , dst ) ; // Return the complete path if found if ( ! recall . isEmpty ( ) ) { return recall ; } } // Wrong link, go back currentPath . remove ( currentPath . size ( ) - 1 ) ; } // No path found through this switch return Collections . emptyList ( ) ; }
Recursive method to get the first physical path found from a switch to a destination node .
239
18
140,527
private int loadSlack ( int dim , int bin ) { return p . loads [ dim ] [ bin ] . getUB ( ) - p . loads [ dim ] [ bin ] . getLB ( ) ; }
compute the load slack of a bin
45
8
140,528
private void validate ( ) { if ( ( this . segments . length < 0 ) && ( ! this . snapshot ) ) { throw new IllegalArgumentException ( "segments.length:" + Integer . valueOf ( this . segments . length ) ) ; } for ( int i = 0 ; i < this . segments . length ; i ++ ) { if ( this . segments [ i ] < 0 ) { throw new IllegalArgumentException ( "segments[" + i + "]:" + Integer . valueOf ( this . segments [ i ] ) ) ; } } if ( this . phaseNumber != null ) { if ( this . phaseNumber . intValue ( ) < 0 ) { throw new IllegalArgumentException ( "phaseNumber:" + this . phaseNumber ) ; } if ( this . phase == null ) { throw new IllegalArgumentException ( "phaseNumber (phase==null):" + this . phaseNumber ) ; } if ( ( this . phase == DevelopmentPhase . RELEASE ) && ( this . phaseNumber . intValue ( ) != 0 ) ) { throw new IllegalArgumentException ( "phaseNumber (phase==RELEASE):" + this . phaseNumber ) ; } } }
This method validates the consistency of this version identifier .
251
11
140,529
public static Integer computeGrammarSize ( GrammarRules rules , Integer paaSize ) { // The final grammar's size in BYTES // int res = 0 ; // The final size is the sum of the sizes of all rules // for ( GrammarRuleRecord r : rules ) { String ruleStr = r . getRuleString ( ) ; String [ ] tokens = ruleStr . split ( "\\s+" ) ; int ruleSize = computeRuleSize ( paaSize , tokens ) ; res += ruleSize ; } return res ; }
Computes the size of a normal i . e . unpruned grammar .
115
16
140,530
public static GrammarRules performPruning ( double [ ] ts , GrammarRules grammarRules ) { RulePruningAlgorithm pruner = new RulePruningAlgorithm ( grammarRules , ts . length ) ; pruner . pruneRules ( ) ; return pruner . regularizePrunedRules ( ) ; }
Performs pruning .
70
5
140,531
public static double computeCover ( boolean [ ] cover ) { int covered = 0 ; for ( boolean i : cover ) { if ( i ) { covered ++ ; } } return ( double ) covered / ( double ) cover . length ; }
Compute the covered percentage .
49
6
140,532
private boolean compatible ( int i , int j , Set < Integer > T [ ] [ ] ) { if ( s2comp [ i ] != s2comp [ j ] ) return false ; for ( int k = 0 ; k < nbLabels ; k ++ ) { if ( ! T [ i ] [ k ] . equals ( T [ j ] [ k ] ) ) return false ; } return true ; }
transition in the same components
88
6
140,533
public boolean register ( E e , String name ) { if ( resolve . containsKey ( name ) ) { return false ; } resolve . put ( name , e ) ; rev . put ( e , name ) ; return true ; }
Register the name of an element .
48
7
140,534
@ Override public boolean substituteVM ( VM curId , VM nextId ) { if ( VM . TYPE . equals ( elemId ) ) { if ( rev . containsKey ( nextId ) ) { //the new id already exists. It is a failure scenario. return false ; } String fqn = rev . remove ( curId ) ; if ( fqn != null ) { //new resolution, with the substitution of the old one. rev . put ( ( E ) nextId , fqn ) ; resolve . put ( fqn , ( E ) nextId ) ; } } return true ; }
Re - associate the name of a registered VM to a new VM .
130
14
140,535
@ SuppressWarnings ( "unchecked" ) public static NamingService < VM > getVMNames ( Model mo ) { return ( NamingService < VM > ) mo . getView ( ID + VM . TYPE ) ; }
Get the naming service for the VMs associated to a model .
50
13
140,536
@ SuppressWarnings ( "unchecked" ) public static NamingService < Node > getNodeNames ( Model mo ) { return ( NamingService < Node > ) mo . getView ( ID + Node . TYPE ) ; }
Get the naming service for the nodes associated to a model .
50
12
140,537
public boolean applyEvents ( Hook k , Model i ) { for ( Event n : getEvents ( k ) ) { if ( ! n . apply ( i ) ) { return false ; } } return true ; }
Apply the events attached to a given hook .
44
9
140,538
public boolean addEvent ( Hook k , Event n ) { Set < Event > l = events . get ( k ) ; if ( l == null ) { l = new HashSet <> ( ) ; events . put ( k , l ) ; } return l . add ( n ) ; }
Add an event to the action . The moment the event will be executed depends on its hook .
61
19
140,539
public Set < Event > getEvents ( Hook k ) { Set < Event > l = events . get ( k ) ; return l == null ? Collections . emptySet ( ) : l ; }
Get the events attached to a specific hook .
40
9
140,540
@ Override public void addDim ( int c , int [ ] cUse , IntVar [ ] dUse , int [ ] alias ) { capacities . add ( c ) ; cUsages . add ( cUse ) ; dUsages . add ( dUse ) ; aliases . add ( alias ) ; }
Add a constraint
65
3
140,541
@ Override public boolean beforeSolve ( ReconfigurationProblem r ) { super . beforeSolve ( r ) ; for ( int i = 0 ; i < aliases . size ( ) ; i ++ ) { int capa = capacities . get ( i ) ; int [ ] alias = aliases . get ( i ) ; int [ ] cUse = cUsages . get ( i ) ; int [ ] dUses = new int [ dUsages . get ( i ) . length ] ; for ( IntVar dUseDim : dUsages . get ( i ) ) { dUses [ i ++ ] = dUseDim . getLB ( ) ; } r . getModel ( ) . post ( new AliasedCumulatives ( alias , new int [ ] { capa } , cHosts , new int [ ] [ ] { cUse } , cEnds , dHosts , new int [ ] [ ] { dUses } , dStarts , associations ) ) ; } return true ; }
Get the generated constraints .
216
5
140,542
public static List < ChocoView > resolveDependencies ( Model mo , List < ChocoView > views , Collection < String > base ) throws SchedulerException { Set < String > done = new HashSet <> ( base ) ; List < ChocoView > remaining = new ArrayList <> ( views ) ; List < ChocoView > solved = new ArrayList <> ( ) ; while ( ! remaining . isEmpty ( ) ) { ListIterator < ChocoView > ite = remaining . listIterator ( ) ; boolean blocked = true ; while ( ite . hasNext ( ) ) { ChocoView s = ite . next ( ) ; if ( done . containsAll ( s . getDependencies ( ) ) ) { ite . remove ( ) ; done . add ( s . getIdentifier ( ) ) ; solved . add ( s ) ; blocked = false ; } } if ( blocked ) { throw new SchedulerModelingException ( mo , "Missing dependencies or cyclic dependencies prevent from using: " + remaining ) ; } } return solved ; }
Flatten the views while considering their dependencies . Operations over the views that respect the iteration order satisfies the dependencies .
227
22
140,543
public static List < RuleInterval > getZeroIntervals ( int [ ] coverageArray ) { ArrayList < RuleInterval > res = new ArrayList < RuleInterval > ( ) ; int start = - 1 ; boolean inInterval = false ; int intervalsCounter = - 1 ; // slide over the array from left to the right // for ( int i = 0 ; i < coverageArray . length ; i ++ ) { if ( 0 == coverageArray [ i ] && ! inInterval ) { start = i ; inInterval = true ; } if ( coverageArray [ i ] > 0 && inInterval ) { res . add ( new RuleInterval ( intervalsCounter , start , i , 0 ) ) ; inInterval = false ; intervalsCounter -- ; } } // we need to check for the last interval here // if ( inInterval ) { res . add ( new RuleInterval ( intervalsCounter , start , coverageArray . length , 0 ) ) ; } return res ; }
Run a quick scan along the time series coverage to find a zeroed intervals .
209
16
140,544
public static double getCoverAsFraction ( int seriesLength , GrammarRules rules ) { boolean [ ] coverageArray = new boolean [ seriesLength ] ; for ( GrammarRuleRecord rule : rules ) { if ( 0 == rule . ruleNumber ( ) ) { continue ; } ArrayList < RuleInterval > arrPos = rule . getRuleIntervals ( ) ; for ( RuleInterval saxPos : arrPos ) { int startPos = saxPos . getStart ( ) ; int endPos = saxPos . getEnd ( ) ; for ( int j = startPos ; j < endPos ; j ++ ) { coverageArray [ j ] = true ; } } } int coverSum = 0 ; for ( int i = 0 ; i < seriesLength ; i ++ ) { if ( coverageArray [ i ] ) { coverSum ++ ; } } return ( double ) coverSum / ( double ) seriesLength ; }
Computes which fraction of the time series is covered by the rules set .
192
15
140,545
public static double getMeanRuleCoverage ( int length , GrammarRules rules ) { // get the coverage array // int [ ] coverageArray = new int [ length ] ; for ( GrammarRuleRecord rule : rules ) { if ( 0 == rule . ruleNumber ( ) ) { continue ; } ArrayList < RuleInterval > arrPos = rule . getRuleIntervals ( ) ; for ( RuleInterval saxPos : arrPos ) { int startPos = saxPos . getStart ( ) ; int endPos = saxPos . getEnd ( ) ; for ( int j = startPos ; j < endPos ; j ++ ) { coverageArray [ j ] = coverageArray [ j ] + 1 ; } } } // int minCoverage = 0; // int maxCoverage = 0; int coverageSum = 0 ; for ( int i : coverageArray ) { coverageSum += i ; // if (i < minCoverage) { // minCoverage = i; // } // if (i > maxCoverage) { // maxCoverage = i; // } } return ( double ) coverageSum / ( double ) length ; }
Gets the mean rule coverage .
240
7
140,546
public void removeLayerFromCache ( LayerImpl layer ) { if ( layer . getId ( ) != layerId ) { throw new IllegalStateException ( ) ; } LayerCacheImpl layerCache = layerCacheRef . get ( ) ; if ( layerCache != null ) { layerCache . remove ( layer . getKey ( ) , layer ) ; } }
Convenience method to remove the layer that this class is associated with from the layer cache .
73
19
140,547
public final V put ( K key , V value ) { BinTreeNode < K , V > prev = null ; BinTreeNode < K , V > node = root ; int key_hash_code = key . hashCode ( ) ; while ( node != null ) { prev = node ; if ( key_hash_code < node . keyHashCode ) { node = node . left ; } else { if ( ( key_hash_code > node . keyHashCode ) || ! node . key . equals ( key ) ) { node = node . right ; } else { cachedHashCode -= node . hashCode ( ) ; V temp = node . value ; node . value = value ; cachedHashCode += node . hashCode ( ) ; return temp ; } } } size ++ ; BinTreeNode < K , V > new_node = new BinTreeNode < K , V > ( key , value ) ; cachedHashCode += new_node . hashCode ( ) ; // invalidate the cached hash code if ( prev == null ) { root = new_node ; return null ; } if ( key_hash_code < prev . keyHashCode ) { prev . left = new_node ; } else { prev . right = new_node ; } return null ; }
Associates the specified value with the specified key in this map .
268
14
140,548
private final V remove_semi_leaf ( BinTreeNode < K , V > node , BinTreeNode < K , V > prev , int son , BinTreeNode < K , V > m ) { if ( prev == null ) { root = m ; } else { if ( son == 0 ) prev . left = m ; else prev . right = m ; } return node . value ; }
to the only predecessor of node that could exist .
84
10
140,549
private final V finish_removal ( BinTreeNode < K , V > node , BinTreeNode < K , V > prev , int son , BinTreeNode < K , V > m ) { if ( m != null ) { // set up the links for m m . left = node . left ; m . right = node . right ; } if ( prev == null ) root = m ; else { if ( son == 0 ) prev . left = m ; else prev . right = m ; } return node . value ; }
BinTreeNode that should replace node in the tree .
111
12
140,550
private final BinTreeNode < K , V > extract_next ( BinTreeNode < K , V > node ) { BinTreeNode < K , V > prev = node . right ; BinTreeNode < K , V > curr = prev . left ; if ( curr == null ) { node . right = node . right . right ; return prev ; } while ( curr . left != null ) { prev = curr ; curr = curr . left ; } prev . left = curr . right ; return curr ; }
removes it from that subtree and returns it .
114
11
140,551
public final Collection < V > values ( ) { return new AbstractCollection < V > ( ) { public Iterator < V > iterator ( ) { final Iterator < Map . Entry < K , V > > ite = entryIterator ( ) ; return new Iterator < V > ( ) { public boolean hasNext ( ) { return ite . hasNext ( ) ; } public void remove ( ) { ite . remove ( ) ; } public V next ( ) { return ite . next ( ) . getValue ( ) ; } } ; } public int size ( ) { return size ; } } ; }
Returns an unmodifiable collection view of the values from this map .
128
14
140,552
public final Set < Map . Entry < K , V > > entrySet ( ) { return new AbstractSet < Map . Entry < K , V > > ( ) { public Iterator < Map . Entry < K , V > > iterator ( ) { return entryIterator ( ) ; } public int size ( ) { return size ; } } ; }
Returns an unmodifiable set view of the map entries .
72
12
140,553
public final Set < K > keySet ( ) { return new AbstractSet < K > ( ) { public Iterator < K > iterator ( ) { final Iterator < Map . Entry < K , V > > ite = entryIterator ( ) ; return new Iterator < K > ( ) { public boolean hasNext ( ) { return ite . hasNext ( ) ; } public void remove ( ) { ite . remove ( ) ; } public K next ( ) { return ite . next ( ) . getKey ( ) ; } } ; } public int size ( ) { return size ; } } ; }
Returns an unmodifiable set view of the keys contained in this map .
129
15
140,554
public void processChildren ( Node node ) { for ( Node cursor = node . getFirstChild ( ) ; cursor != null ; cursor = cursor . getNext ( ) ) { if ( cursor . getType ( ) == Token . CALL ) { // The node is a function or method call Node name = cursor . getFirstChild ( ) ; if ( name != null && name . getType ( ) == Token . NAME && // named function call name . getString ( ) . equals ( "define" ) ) { // name is "define" //$NON-NLS-1$ Node param = name . getNext ( ) ; if ( param != null && param . getType ( ) != Token . STRING ) { String expname = name . getProp ( Node . SOURCENAME_PROP ) . toString ( ) ; if ( source != null ) { PositionLocator locator = source . locate ( name . getLineno ( ) , name . getCharno ( ) + 6 ) ; char tok = locator . findNextJSToken ( ) ; // move cursor to the open paren if ( tok == ' ' ) { // Try to insert the module name immediately following the open paren for the // define call because the param location will be off if the argument list is parenthesized. source . insert ( "\"" + expname + "\"," , locator . getLineno ( ) , locator . getCharno ( ) + 1 ) ; //$NON-NLS-1$ //$NON-NLS-2$ } else { // First token following 'define' name is not a paren, so fall back to inserting // before the first parameter. source . insert ( "\"" + expname + "\"," , param . getLineno ( ) , param . getCharno ( ) ) ; //$NON-NLS-1$ //$NON-NLS-2$ } } param . getParent ( ) . addChildBefore ( Node . newString ( expname ) , param ) ; } } } // Recursively call this method to process the child nodes if ( cursor . hasChildren ( ) ) processChildren ( cursor ) ; } }
Recursively called to process AST nodes looking for anonymous define calls . If an anonymous define call is found then change it be a named define call specifying the module name for the file being processed .
472
39
140,555
public List < IntVar > getIncoming ( Node n ) { List < IntVar > l = incoming . get ( n ) ; if ( l == null ) { l = Collections . emptyList ( ) ; } return l ; }
Get the start moment of the movements that terminate on a given node
49
13
140,556
public List < IntVar > getOutgoing ( Node n ) { List < IntVar > l = outgoings . get ( n ) ; if ( l == null ) { l = Collections . emptyList ( ) ; } return l ; }
Get the start moment of the movements that leave from a given node
51
13
140,557
private void checkModel ( Model mo , boolean start ) throws SatConstraintViolationException { for ( SatConstraintChecker < ? > c : checkers ) { if ( start && ! c . startsWith ( mo ) ) { SatConstraint cs = c . getConstraint ( ) ; if ( cs != null ) { throw new DiscreteViolationException ( c . getConstraint ( ) , mo ) ; } } else if ( ! start && ! c . endsWith ( mo ) ) { SatConstraint cs = c . getConstraint ( ) ; if ( cs != null ) { throw new DiscreteViolationException ( c . getConstraint ( ) , mo ) ; } } } }
Check for the validity of a model .
157
8
140,558
private static JSONObject toJSON ( Mapping c ) { JSONObject o = new JSONObject ( ) ; o . put ( "offlineNodes" , nodesToJSON ( c . getOfflineNodes ( ) ) ) ; o . put ( "readyVMs" , vmsToJSON ( c . getReadyVMs ( ) ) ) ; JSONObject ons = new JSONObject ( ) ; for ( Node n : c . getOnlineNodes ( ) ) { JSONObject w = new JSONObject ( ) ; w . put ( "runningVMs" , vmsToJSON ( c . getRunningVMs ( n ) ) ) ; w . put ( "sleepingVMs" , vmsToJSON ( c . getSleepingVMs ( n ) ) ) ; ons . put ( Integer . toString ( n . id ( ) ) , w ) ; } o . put ( "onlineNodes" , ons ) ; return o ; }
Serialise the mapping .
206
5
140,559
public void fillMapping ( Model mo , JSONObject o ) throws JSONConverterException { Mapping c = mo . getMapping ( ) ; for ( Node u : newNodes ( mo , o , "offlineNodes" ) ) { c . addOfflineNode ( u ) ; } for ( VM u : newVMs ( mo , o , "readyVMs" ) ) { c . addReadyVM ( u ) ; } JSONObject ons = ( JSONObject ) o . get ( "onlineNodes" ) ; for ( Map . Entry < String , Object > e : ons . entrySet ( ) ) { int id = Integer . parseInt ( e . getKey ( ) ) ; Node u = mo . newNode ( id ) ; if ( u == null ) { throw JSONConverterException . nodeAlreadyDeclared ( id ) ; } JSONObject on = ( JSONObject ) e . getValue ( ) ; c . addOnlineNode ( u ) ; for ( VM vm : newVMs ( mo , on , "runningVMs" ) ) { c . addRunningVM ( vm , u ) ; } for ( VM vm : newVMs ( mo , on , "sleepingVMs" ) ) { c . addSleepingVM ( vm , u ) ; } } }
Create the elements inside the model and fill the mapping .
281
11
140,560
private static Set < Node > newNodes ( Model mo , JSONObject o , String key ) throws JSONConverterException { checkKeys ( o , key ) ; Object x = o . get ( key ) ; if ( ! ( x instanceof JSONArray ) ) { throw new JSONConverterException ( "array expected at key '" + key + "'" ) ; } Set < Node > s = new HashSet <> ( ( ( JSONArray ) x ) . size ( ) ) ; for ( Object i : ( JSONArray ) x ) { int id = ( Integer ) i ; Node n = mo . newNode ( id ) ; if ( n == null ) { throw JSONConverterException . nodeAlreadyDeclared ( id ) ; } s . add ( n ) ; } return s ; }
Build nodes from a key .
171
6
140,561
private static Set < VM > newVMs ( Model mo , JSONObject o , String key ) throws JSONConverterException { checkKeys ( o , key ) ; Object x = o . get ( key ) ; if ( ! ( x instanceof JSONArray ) ) { throw new JSONConverterException ( "array expected at key '" + key + "'" ) ; } Set < VM > s = new HashSet <> ( ( ( JSONArray ) x ) . size ( ) ) ; for ( Object i : ( JSONArray ) x ) { int id = ( Integer ) i ; VM vm = mo . newVM ( id ) ; if ( vm == null ) { throw JSONConverterException . vmAlreadyDeclared ( id ) ; } s . add ( vm ) ; } return s ; }
Build VMs from a key .
171
7
140,562
public boolean add ( String key , ModuleDepInfo info ) { if ( info == null ) { throw new NullPointerException ( ) ; } boolean modified = false ; ModuleDepInfo existing = get ( key ) ; if ( ! containsKey ( key ) || existing != info ) { if ( existing != null ) { modified = existing . add ( info ) ; } else { super . put ( key , info ) ; modified = true ; } } return modified ; }
Adds the specified pair to the map . If an entry for the key exists then the specified module dep info is added to the existing module dep info .
97
30
140,563
public boolean addAll ( ModuleDeps other ) { boolean modified = false ; for ( Map . Entry < String , ModuleDepInfo > entry : other . entrySet ( ) ) { modified |= add ( entry . getKey ( ) , new ModuleDepInfo ( entry . getValue ( ) ) ) ; } return modified ; }
Adds all of the map entries from other to this map
69
11
140,564
public int minVMAllocation ( int vmIdx , int v ) { int vv = Math . max ( v , vmAllocation . get ( vmIdx ) ) ; vmAllocation . set ( vmIdx , vv ) ; return vv ; }
Change the VM resource allocation .
57
6
140,565
public double capOverbookRatio ( int nIdx , double d ) { if ( d < 1 ) { return ratios . get ( nIdx ) ; } double v = Math . min ( ratios . get ( nIdx ) , d ) ; ratios . set ( nIdx , v ) ; return v ; }
Cap the overbooking ratio for a given node .
69
11
140,566
@ Override public boolean beforeSolve ( ReconfigurationProblem p ) throws SchedulerException { for ( VM vm : source . getMapping ( ) . getAllVMs ( ) ) { int vmId = p . getVM ( vm ) ; int v = getVMAllocation ( vmId ) ; if ( v < 0 ) { int prevUsage = rc . getConsumption ( vm ) ; minVMAllocation ( vmId , prevUsage ) ; } } ChocoView v = rp . getView ( Packing . VIEW_ID ) ; if ( v == null ) { throw SchedulerModelingException . missingView ( rp . getSourceModel ( ) , Packing . VIEW_ID ) ; } IntVar [ ] host = new IntVar [ p . getFutureRunningVMs ( ) . size ( ) ] ; int [ ] demand = new int [ host . length ] ; int i = 0 ; for ( VM vm : p . getFutureRunningVMs ( ) ) { host [ i ] = rp . getVMAction ( vm ) . getDSlice ( ) . getHoster ( ) ; demand [ i ] = getVMAllocation ( p . getVM ( vm ) ) ; i ++ ; } ( ( Packing ) v ) . addDim ( rc . getResourceIdentifier ( ) , virtRcUsage , demand , host ) ; return linkVirtualToPhysicalUsage ( ) ; }
Set the resource usage for each of the VM . If the LB is < 0 the previous consumption is used to maintain the resource usage . Otherwise the usage is set to the variable lower bound .
304
38
140,567
private boolean capHosting ( int nIdx , int min , int nbZeroes ) { Node n = rp . getNode ( nIdx ) ; double capa = getSourceResource ( ) . getCapacity ( n ) * getOverbookRatio ( nIdx ) /*.getLB()*/ ; int card = ( int ) ( capa / min ) + nbZeroes + 1 ; if ( card < source . getMapping ( ) . getRunningVMs ( n ) . size ( ) ) { // This shortcut is required to prevent a filtering issue in the scheduling phase: // At time 0, LocalTaskScheduler will complain and start to backtrack. // TODO: revise the notion of continuous constraint for the cardinality issue. return true ; } try { //Restrict the hosting capacity. rp . getNbRunningVMs ( ) . get ( nIdx ) . updateUpperBound ( card , Cause . Null ) ; } catch ( ContradictionException ex ) { rp . getLogger ( ) . error ( "Unable to cap the hosting capacity of '" + n + " ' to " + card , ex ) ; return false ; } return true ; }
Reduce the cardinality wrt . the worst case scenario .
262
13
140,568
private void checkInitialSatisfaction ( ) { //Seems to me we don't support ratio change for ( Node n : rp . getSourceModel ( ) . getMapping ( ) . getOnlineNodes ( ) ) { int nIdx = rp . getNode ( n ) ; double ratio = getOverbookRatio ( nIdx ) /*.getLB()*/ ; double capa = getSourceResource ( ) . getCapacity ( n ) * ratio ; int usage = 0 ; for ( VM vm : rp . getSourceModel ( ) . getMapping ( ) . getRunningVMs ( n ) ) { usage += getSourceResource ( ) . getConsumption ( vm ) ; if ( usage > capa ) { //Here, the problem is not feasible but we consider an exception //because such a situation does not physically makes sense (one cannot run at 110%) throw new SchedulerModelingException ( rp . getSourceModel ( ) , "Usage of virtual resource " + getResourceIdentifier ( ) + " on node " + n + " (" + usage + ") exceeds its capacity (" + capa + ")" ) ; } } } }
Check if the initial capacity > sum current consumption The ratio is instantiated now so the computation is correct
250
20
140,569
public static TObjectIntMap < VM > getWeights ( ReconfigurationProblem rp , List < CShareableResource > rcs ) { Model mo = rp . getSourceModel ( ) ; int [ ] capa = new int [ rcs . size ( ) ] ; int [ ] cons = new int [ rcs . size ( ) ] ; TObjectIntMap < VM > cost = new TObjectIntHashMap <> ( ) ; for ( Node n : mo . getMapping ( ) . getAllNodes ( ) ) { for ( int i = 0 ; i < rcs . size ( ) ; i ++ ) { capa [ i ] += rcs . get ( i ) . virtRcUsage . get ( rp . getNode ( n ) ) . getUB ( ) * rcs . get ( i ) . ratios . get ( rp . getNode ( n ) ) /*.getLB()*/ ; } } for ( VM v : mo . getMapping ( ) . getAllVMs ( ) ) { for ( int i = 0 ; i < rcs . size ( ) ; i ++ ) { cons [ i ] += rcs . get ( i ) . getVMAllocation ( rp . getVM ( v ) ) ; } } for ( VM v : mo . getMapping ( ) . getAllVMs ( ) ) { double sum = 0 ; for ( int i = 0 ; i < rcs . size ( ) ; i ++ ) { double ratio = 0 ; if ( cons [ i ] > 0 ) { ratio = 1.0 * rcs . get ( i ) . getVMAllocation ( rp . getVM ( v ) ) / capa [ i ] ; } sum += ratio ; } cost . put ( v , ( int ) ( sum * 10000 ) ) ; } return cost ; }
Estimate the weight of each VMs with regards to multiple dimensions . In practice it sums the normalised size of each VM against the total capacity
400
29
140,570
private boolean distinctVMStates ( ) { boolean ok = vms . size ( ) == running . size ( ) + sleeping . size ( ) + ready . size ( ) + killed . size ( ) ; //It is sure there is no solution as a VM cannot have multiple destination state Map < VM , VMState > states = new HashMap <> ( ) ; for ( VM v : running ) { states . put ( v , VMState . RUNNING ) ; } for ( VM v : ready ) { VMState prev = states . put ( v , VMState . READY ) ; if ( prev != null ) { getLogger ( ) . debug ( "multiple destination state for {}: {} and {}" , v , prev , VMState . READY ) ; } } for ( VM v : sleeping ) { VMState prev = states . put ( v , VMState . SLEEPING ) ; if ( prev != null ) { getLogger ( ) . debug ( "multiple destination state for {}: {} and {}" , v , prev , VMState . SLEEPING ) ; } } for ( VM v : killed ) { VMState prev = states . put ( v , VMState . KILLED ) ; if ( prev != null ) { getLogger ( ) . debug ( "multiple destination state for {}: {} and {}" , v , prev , VMState . KILLED ) ; } } return ok ; }
Check if every VM has a single destination state
300
9
140,571
@ Override @ SuppressWarnings ( "squid:S3346" ) public ReconfigurationPlan buildReconfigurationPlan ( Solution s , Model src ) throws SchedulerException { ReconfigurationPlan plan = new DefaultReconfigurationPlan ( src ) ; for ( NodeTransition action : nodeActions ) { action . insertActions ( s , plan ) ; } for ( VMTransition action : vmActions ) { action . insertActions ( s , plan ) ; } assert plan . isApplyable ( ) : "The following plan cannot be applied:\n" + plan ; assert checkConsistency ( s , plan ) ; return plan ; }
Build a plan for a solution .
144
7
140,572
private void defaultHeuristic ( ) { IntStrategy intStrat = Search . intVarSearch ( new FirstFail ( csp ) , new IntDomainMin ( ) , csp . retrieveIntVars ( true ) ) ; SetStrategy setStrat = new SetStrategy ( csp . retrieveSetVars ( ) , new InputOrder <> ( csp ) , new SetDomainMin ( ) , true ) ; RealStrategy realStrat = new RealStrategy ( csp . retrieveRealVars ( ) , new Occurrence <> ( ) , new RealDomainMiddle ( ) ) ; solver . setSearch ( new StrategiesSequencer ( intStrat , realStrat , setStrat ) ) ; }
A naive heuristic to be sure every variables will be instantiated .
154
14
140,573
private void makeCardinalityVariables ( ) { vmsCountOnNodes = new ArrayList <> ( nodes . size ( ) ) ; int nbVMs = vms . size ( ) ; for ( Node n : nodes ) { vmsCountOnNodes . add ( csp . intVar ( makeVarLabel ( "nbVMsOn('" , n , "')" ) , 0 , nbVMs , true ) ) ; } vmsCountOnNodes = Collections . unmodifiableList ( vmsCountOnNodes ) ; }
Create the cardinality variables .
121
6
140,574
@ Override public Iterator < Action > iterator ( ) { Set < Action > sorted = new TreeSet <> ( startFirstComparator ) ; sorted . addAll ( actions ) ; return sorted . iterator ( ) ; }
Iterate over the actions . The action are automatically sorted increasingly by their starting moment .
47
17
140,575
private void addDirectionalEdge ( Edge e ) { if ( edgeAccess . getCapacity ( ) < getEdgeIndex ( edgePos ) + EDGE_SIZE ) edgeAccess . ensureCapacity ( edgeAccess . getCapacity ( ) + INITIAL_EDGE_FILE_SIZE ) ; long fromId = nodIdMapping . get ( e . getFromNodeId ( ) ) ; long toId = nodIdMapping . get ( e . getToNodeId ( ) ) ; long fromIndex = getNodeIndex ( fromId ) ; long toIndex = getNodeIndex ( toId ) ; long edgeIndex = getEdgeIndex ( edgePos ) ; edgeAccess . setLong ( edgeIndex , fromId ) ; edgeAccess . setLong ( edgeIndex + 8 , toId ) ; edgeAccess . setDouble ( edgeIndex + 16 , e . getWeight ( ) ) ; edgeAccess . setLong ( edgeIndex + 24 , nodeAccess . getLong ( fromIndex + 8 ) ) ; edgeAccess . setLong ( edgeIndex + 32 , nodeAccess . getLong ( toIndex + 16 ) ) ; nodeAccess . setLong ( fromIndex + 8 , edgePos ) ; nodeAccess . setLong ( toIndex + 16 , edgePos ) ; edgeAccess . setLong ( 0 , ++ edgePos ) ; }
Add a new directional edge into the graph .
281
9
140,576
public static DefaultConstraintsCatalog newBundle ( ) { DefaultConstraintsCatalog c = new DefaultConstraintsCatalog ( ) ; c . add ( new AmongBuilder ( ) ) ; c . add ( new BanBuilder ( ) ) ; c . add ( new ResourceCapacityBuilder ( ) ) ; c . add ( new RunningCapacityBuilder ( ) ) ; c . add ( new FenceBuilder ( ) ) ; c . add ( new GatherBuilder ( ) ) ; c . add ( new KilledBuilder ( ) ) ; c . add ( new LonelyBuilder ( ) ) ; c . add ( new OfflineBuilder ( ) ) ; c . add ( new OnlineBuilder ( ) ) ; c . add ( new OverbookBuilder ( ) ) ; c . add ( new PreserveBuilder ( ) ) ; c . add ( new QuarantineBuilder ( ) ) ; c . add ( new ReadyBuilder ( ) ) ; c . add ( new RootBuilder ( ) ) ; c . add ( new RunningBuilder ( ) ) ; c . add ( new SleepingBuilder ( ) ) ; c . add ( new SplitBuilder ( ) ) ; c . add ( new SplitAmongBuilder ( ) ) ; c . add ( new SpreadBuilder ( ) ) ; c . add ( new SeqBuilder ( ) ) ; c . add ( new MaxOnlineBuilder ( ) ) ; c . add ( new NoDelayBuilder ( ) ) ; c . add ( new BeforeBuilder ( ) ) ; c . add ( new SerializeBuilder ( ) ) ; c . add ( new SyncBuilder ( ) ) ; return c ; }
Build a catalog with a builder for every constraints in the current BtrPlace bundle .
334
17
140,577
public boolean add ( SatConstraintBuilder c ) { if ( this . builders . containsKey ( c . getIdentifier ( ) ) ) { return false ; } this . builders . put ( c . getIdentifier ( ) , c ) ; return true ; }
Add a constraint builder to the catalog . There must not be another builder with the same identifier in the catalog
56
21
140,578
public int compare ( T o1 , T o2 ) { if ( o1 == o2 ) return 0 ; String str1 = ( o1 == null ) ? "null" : o1 . toString ( ) ; String str2 = ( o2 == null ) ? "null" : o2 . toString ( ) ; return str1 . compareTo ( str2 ) ; }
Compares its two arguments for order . Returns a negative integer zero or a positive integer as the string representation of the first argument is less than equal to or greater to the string representation of the second .
82
40
140,579
public static CaseSyntax of ( Character separator , CaseConversion allCharCase ) { return of ( separator , allCharCase , allCharCase , allCharCase ) ; }
The constructor .
39
3
140,580
protected void registerDefaultDatatypes ( ) { registerStandardDatatype ( String . class ) ; registerStandardDatatype ( Boolean . class ) ; registerStandardDatatype ( Character . class ) ; registerStandardDatatype ( Currency . class ) ; registerCustomDatatype ( Datatype . class ) ; // internal trick... registerNumberDatatypes ( ) ; registerJavaTimeDatatypes ( ) ; registerJavaUtilDateCalendarDatatypes ( ) ; }
Registers the default datatypes .
102
8
140,581
public void setExtraDatatypes ( List < String > datatypeList ) { getInitializationState ( ) . requireNotInitilized ( ) ; for ( String fqn : datatypeList ) { registerCustomDatatype ( fqn ) ; } }
Adds a list of additional datatypes to register . E . g . for easy spring configuration and custom extension .
59
23
140,582
public static CompressionCodec getGzipCodec ( Configuration conf ) { try { return ( CompressionCodec ) ReflectionUtils . newInstance ( conf . getClassByName ( "org.apache.hadoop.io.compress.GzipCodec" ) . asSubclass ( CompressionCodec . class ) , conf ) ; } catch ( ClassNotFoundException e ) { logger . warn ( "GzipCodec could not be instantiated" , e ) ; return null ; } }
Instantiates a Hadoop codec for compressing and decompressing Gzip files . This is the most common compression applied to WARC files .
110
30
140,583
public static boolean isNearMultipleBorders ( @ Nonnull final Point point , @ Nonnull final Territory territory ) { checkDefined ( "point" , point ) ; if ( territory != Territory . AAA ) { final int territoryNumber = territory . getNumber ( ) ; if ( territory . getParentTerritory ( ) != null ) { // There is a parent! check its borders as well... if ( isNearMultipleBorders ( point , territory . getParentTerritory ( ) ) ) { return true ; } } int nrFound = 0 ; final int fromTerritoryRecord = DATA_MODEL . getDataFirstRecord ( territoryNumber ) ; final int uptoTerritoryRecord = DATA_MODEL . getDataLastRecord ( territoryNumber ) ; for ( int territoryRecord = uptoTerritoryRecord ; territoryRecord >= fromTerritoryRecord ; territoryRecord -- ) { if ( ! Data . isRestricted ( territoryRecord ) ) { final Boundary boundary = Boundary . createBoundaryForTerritoryRecord ( territoryRecord ) ; final int xdiv8 = Common . xDivider ( boundary . getLatMicroDegMin ( ) , boundary . getLatMicroDegMax ( ) ) / 4 ; if ( boundary . extendBoundary ( 60 , xdiv8 ) . containsPoint ( point ) ) { if ( ! boundary . extendBoundary ( - 60 , - xdiv8 ) . containsPoint ( point ) ) { nrFound ++ ; if ( nrFound > 1 ) { return true ; } } } } } } return false ; }
Is coordinate near multiple territory borders?
335
7
140,584
public void enqueue ( RepairDigramRecord digramRecord ) { // System.out.println("before == " + this.toString()); // if the same key element is in the queue - something went wrong with tracking... if ( elements . containsKey ( digramRecord . str ) ) { throw new IllegalArgumentException ( "Element with payload " + digramRecord . str + " already exists in the queue..." ) ; } else { // create a new node RepairQueueNode nn = new RepairQueueNode ( digramRecord ) ; // System.out.println(nn.payload); // place it into the queue if it's empty if ( this . elements . isEmpty ( ) ) { this . head = nn ; } // if new node has _higher than_ or _equal to_ the head frequency... this going to be the new head else if ( nn . getFrequency ( ) >= this . head . getFrequency ( ) ) { this . head . prev = nn ; nn . next = this . head ; this . head = nn ; } // in all other cases find an appropriate place in the existing queue, starting from the head else { RepairQueueNode currentNode = head ; while ( null != currentNode . next ) { // the intent is to slide down the list finding a place at new node is greater than a node // a tracking pointer points to... // ABOVE we just checked that at this loop start that the current node is greater than new // node // if ( nn . getFrequency ( ) >= currentNode . getFrequency ( ) ) { RepairQueueNode prevN = currentNode . prev ; prevN . next = nn ; nn . prev = prevN ; currentNode . prev = nn ; nn . next = currentNode ; break ; // the element has been placed } currentNode = currentNode . next ; } // check if loop was broken by the TAIL condition, not by placement if ( null == currentNode . next ) { // so, currentNode points on the tail... if ( nn . getFrequency ( ) >= currentNode . getFrequency ( ) ) { // insert just before... RepairQueueNode prevN = currentNode . prev ; prevN . next = nn ; nn . prev = prevN ; currentNode . prev = nn ; nn . next = currentNode ; } else { // or make a new tail nn . prev = currentNode ; currentNode . next = nn ; } } } // also save the element in the index store this . elements . put ( nn . payload . str , nn ) ; } // System.out.println("before == " + this.toString()); }
Places an element in the queue at the place based on its frequency .
576
15
140,585
public RepairDigramRecord get ( String key ) { RepairQueueNode el = this . elements . get ( key ) ; if ( null != el ) { return el . payload ; } return null ; }
Gets an element in the queue given its key .
42
11
140,586
private void removeNodeFromList ( RepairQueueNode el ) { // the head case // if ( null == el . prev ) { if ( null != el . next ) { this . head = el . next ; this . head . prev = null ; el = null ; } else { // can't happen? yep. if there is only one element exists... this . head = null ; } } // the tail case // else if ( null == el . next ) { if ( null != el . prev ) { el . prev . next = null ; } else { // can't happen? throw new RuntimeException ( "Unrecognized situation here..." ) ; } } // all others // else { el . prev . next = el . next ; el . next . prev = el . prev ; } }
Removes a node from the doubly linked list which backs the queue .
167
15
140,587
public int evaluate ( Model mo , Class < ? extends Action > a , Element e ) throws SchedulerException { ActionDurationEvaluator < Element > ev = durations . get ( a ) ; if ( ev == null ) { throw new SchedulerModelingException ( null , "Unable to estimate the duration of action '" + a . getSimpleName ( ) + "' related to '" + e + "'" ) ; } int d = ev . evaluate ( mo , e ) ; if ( d <= 0 ) { throw new SchedulerModelingException ( null , "The duration for action " + a . getSimpleName ( ) + " over '" + e + "' has been evaluated to a negative value (" + d + "). Unsupported" ) ; } return d ; }
Evaluate the duration of given action on a given element .
167
13
140,588
protected void parseParameter ( String parameter , CliParserState parserState , CliParameterConsumer parameterConsumer ) { if ( parserState . isOptionsComplete ( ) ) { // no more options (e.g. --foo), only arguments from here List < CliArgumentContainer > argumentList = this . cliState . getArguments ( parserState . requireCurrentMode ( this . cliState ) ) ; int argumentIndex = parserState . getArgumentIndex ( ) ; if ( argumentIndex >= argumentList . size ( ) ) { throw new NlsIllegalArgumentException ( parameter ) ; } else { parseArgument ( parserState , parameter , argumentList . get ( argumentIndex ) , parameterConsumer ) ; } } else { CliOptionContainer optionContainer = this . cliState . getOption ( parameter ) ; if ( optionContainer == null ) { // no option found for argument... parseParameterUndefinedOption ( parameter , parserState , parameterConsumer ) ; } else { // mode handling... String modeId = optionContainer . getOption ( ) . mode ( ) ; CliModeObject newMode = this . cliState . getMode ( modeId ) ; if ( newMode == null ) { // should never happen! newMode = new CliModeContainer ( modeId ) ; } if ( parserState . currentMode == null ) { parserState . setCurrentMode ( parameter , newMode ) ; } else if ( ! modeId . equals ( parserState . currentMode . getId ( ) ) ) { // mode already detected, but mode of current option differs... if ( newMode . isDescendantOf ( parserState . currentMode ) ) { // new mode extends current mode parserState . setCurrentMode ( parameter , newMode ) ; } else if ( ! newMode . isAncestorOf ( parserState . currentMode ) ) { // current mode does NOT extend new mode and vice versa // --> incompatible modes throw new CliOptionIncompatibleModesException ( parserState . modeOption , parameter ) ; } } parseOption ( parserState , parameter , optionContainer , parameterConsumer ) ; } } }
This method parses a single command - line argument .
448
11
140,589
private int printHelpOptions ( CliOutputSettings settings , Map < CliOption , CliOptionHelpInfo > option2HelpMap , StringBuilder parameters , Collection < CliOptionContainer > modeOptions ) { int maxOptionColumnWidth = 0 ; for ( CliOptionContainer option : modeOptions ) { CliOption cliOption = option . getOption ( ) ; if ( parameters . length ( ) > 0 ) { parameters . append ( " " ) ; } if ( ! cliOption . required ( ) ) { parameters . append ( "[" ) ; } parameters . append ( cliOption . name ( ) ) ; if ( ! option . getSetter ( ) . getPropertyClass ( ) . equals ( boolean . class ) ) { parameters . append ( " " ) ; parameters . append ( cliOption . operand ( ) ) ; if ( option . isArrayMapOrCollection ( ) ) { CliContainerStyle containerStyle = option . getContainerStyle ( this . cliState . getCliStyle ( ) ) ; switch ( containerStyle ) { case COMMA_SEPARATED : parameters . append ( ",..." ) ; break ; case MULTIPLE_OCCURRENCE : parameters . append ( "*" ) ; break ; default : throw new IllegalCaseException ( CliContainerStyle . class , containerStyle ) ; } } } if ( ! cliOption . required ( ) ) { parameters . append ( "]" ) ; } CliOptionHelpInfo helpInfo = option2HelpMap . get ( cliOption ) ; if ( helpInfo == null ) { helpInfo = new CliOptionHelpInfo ( option , this . dependencies , settings ) ; option2HelpMap . put ( cliOption , helpInfo ) ; } if ( helpInfo . length > maxOptionColumnWidth ) { maxOptionColumnWidth = helpInfo . length ; } } return maxOptionColumnWidth ; }
Prints the options for the help usage output .
403
10
140,590
public boolean contains ( Object o ) { for ( T e : elemArray ) { if ( ( o == e ) || ( ( o != null ) && o . equals ( e ) ) ) { return true ; } } return false ; }
Re - implement the contains method from AbstractSet for speed reasons
51
12
140,591
public Set < Action > getDependencies ( Action a ) { if ( ! demandingNodes . containsKey ( a ) ) { return Collections . emptySet ( ) ; } Node n = demandingNodes . get ( a ) ; Set < Action > allActions = getFreeings ( n ) ; Set < Action > pre = new HashSet <> ( ) ; for ( Action action : allActions ) { if ( ! action . equals ( a ) && a . getStart ( ) >= action . getEnd ( ) ) { pre . add ( action ) ; } } return pre ; }
Get the dependencies for an action .
126
7
140,592
public static boolean isExplodeRequires ( HttpServletRequest request ) { if ( isIncludeRequireDeps ( request ) ) { // don't expand require deps if we're including them in the response. return false ; } boolean result = false ; IAggregator aggr = ( IAggregator ) request . getAttribute ( IAggregator . AGGREGATOR_REQATTRNAME ) ; IOptions options = aggr . getOptions ( ) ; IConfig config = aggr . getConfig ( ) ; Boolean reqattr = TypeUtil . asBoolean ( request . getAttribute ( IHttpTransport . EXPANDREQUIRELISTS_REQATTRNAME ) ) ; result = ( options == null || ! options . isDisableRequireListExpansion ( ) ) && ( config == null || ! isServerExpandedLayers ( request ) ) && reqattr != null && reqattr ; return result ; }
Static class method for determining if require list explosion should be performed .
202
13
140,593
public static boolean isHasFiltering ( HttpServletRequest request ) { IAggregator aggr = ( IAggregator ) request . getAttribute ( IAggregator . AGGREGATOR_REQATTRNAME ) ; IOptions options = aggr . getOptions ( ) ; return ( options != null ) ? ! options . isDisableHasFiltering ( ) : true ; }
Static method for determining if has filtering should be performed .
84
11
140,594
@ Nonnull static Boundary createBoundaryForTerritoryRecord ( final int territoryRecord ) { return new Boundary ( DATA_MODEL . getLatMicroDegMin ( territoryRecord ) , DATA_MODEL . getLonMicroDegMin ( territoryRecord ) , DATA_MODEL . getLatMicroDegMax ( territoryRecord ) , DATA_MODEL . getLonMicroDegMax ( territoryRecord ) ) ; }
You have to use this factory method instead of a ctor .
94
13
140,595
boolean containsPoint ( @ Nonnull final Point p ) { if ( ! p . isDefined ( ) ) { return false ; } final int latMicroDeg = p . getLatMicroDeg ( ) ; if ( ( latMicroDegMin > latMicroDeg ) || ( latMicroDeg >= latMicroDegMax ) ) { return false ; } final int lonMicroDeg = p . getLonMicroDeg ( ) ; // Longitude boundaries can extend (slightly) outside the [-180,180) range. if ( lonMicroDeg < lonMicroDegMin ) { return ( lonMicroDegMin <= ( lonMicroDeg + Point . MICRO_DEG_360 ) ) && ( ( lonMicroDeg + Point . MICRO_DEG_360 ) < lonMicroDegMax ) ; } else if ( lonMicroDeg >= lonMicroDegMax ) { return ( lonMicroDegMin <= ( lonMicroDeg - Point . MICRO_DEG_360 ) ) && ( ( lonMicroDeg - Point . MICRO_DEG_360 ) < lonMicroDegMax ) ; } else { return true ; } }
Check if a point falls within a boundary . Note that the min values are inclusive for a boundary and the max values are exclusive . \
269
27
140,596
public static List < Precedence > newPrecedence ( VM vmBefore , Collection < VM > vmsAfter ) { return newPrecedence ( Collections . singleton ( vmBefore ) , vmsAfter ) ; }
Instantiate discrete constraints to force a set of VMs to migrate after a single one .
47
18
140,597
public static List < Precedence > newPrecedence ( Collection < VM > vmsBefore , VM vmAfter ) { return newPrecedence ( vmsBefore , Collections . singleton ( vmAfter ) ) ; }
Instantiate discrete constraints to force a single VM to migrate after a set of VMs .
47
18
140,598
public static List < Precedence > newPrecedence ( Collection < VM > vmsBefore , Collection < VM > vmsAfter ) { List < Precedence > l = new ArrayList <> ( vmsBefore . size ( ) * vmsAfter . size ( ) ) ; for ( VM vmb : vmsBefore ) { for ( VM vma : vmsAfter ) { l . add ( new Precedence ( vmb , vma ) ) ; } } return l ; }
Instantiate discrete constraints to force a set of VMs to migrate after an other set of VMs .
106
21
140,599
private ESat isConsistent ( ) { int [ ] [ ] l = new int [ nbDims ] [ nbBins ] ; for ( int i = 0 ; i < bins . length ; i ++ ) { if ( bins [ i ] . isInstantiated ( ) ) { for ( int d = 0 ; d < nbDims ; d ++ ) { int v = bins [ i ] . getValue ( ) ; l [ d ] [ v ] += iSizes [ d ] [ i ] ; if ( l [ d ] [ v ] > loads [ d ] [ v ] . getUB ( ) ) { return ESat . FALSE ; } } } } return ESat . TRUE ; }
check the consistency of the constraint .
152
7