idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
150,400
private void readZookeeperConfig ( ) { try ( CuratorFramework curator = CuratorUtil . newAppCurator ( config ) ) { curator . start ( ) ; accumuloInstance = new String ( curator . getData ( ) . forPath ( ZookeeperPath . CONFIG_ACCUMULO_INSTANCE_NAME ) , StandardCharsets . UTF_8 ) ; accumuloInstanceID = new String ( curator . getData ( ) . forPath ( ZookeeperPath . CONFIG_ACCUMULO_INSTANCE_ID ) , StandardCharsets . UTF_8 ) ; fluoApplicationID = new String ( curator . getData ( ) . forPath ( ZookeeperPath . CONFIG_FLUO_APPLICATION_ID ) , StandardCharsets . UTF_8 ) ; table = new String ( curator . getData ( ) . forPath ( ZookeeperPath . CONFIG_ACCUMULO_TABLE ) , StandardCharsets . UTF_8 ) ; observers = ObserverUtil . load ( curator ) ; config = FluoAdminImpl . mergeZookeeperConfig ( config ) ; // make sure not to include config passed to env, only want config from zookeeper appConfig = config . getAppConfiguration ( ) ; } catch ( Exception e ) { throw new IllegalStateException ( e ) ; } }
Read configuration from zookeeper
291
6
150,401
@ Override public void close ( ) { status = TrStatus . CLOSED ; try { node . close ( ) ; } catch ( IOException e ) { log . error ( "Failed to close ephemeral node" ) ; throw new IllegalStateException ( e ) ; } }
Closes the transactor node by removing its node in Zookeeper
60
14
150,402
private static Map < String , Set < String > > expand ( Map < String , Set < String > > viewToPropNames ) { Set < String > baseProps = viewToPropNames . get ( PropertyView . BASE_VIEW ) ; if ( baseProps == null ) { baseProps = ImmutableSet . of ( ) ; } if ( ! SquigglyConfig . isFilterImplicitlyIncludeBaseFieldsInView ( ) ) { // make an exception for full view Set < String > fullView = viewToPropNames . get ( PropertyView . FULL_VIEW ) ; if ( fullView != null ) { fullView . addAll ( baseProps ) ; } return viewToPropNames ; } for ( Map . Entry < String , Set < String > > entry : viewToPropNames . entrySet ( ) ) { String viewName = entry . getKey ( ) ; Set < String > propNames = entry . getValue ( ) ; if ( ! PropertyView . BASE_VIEW . equals ( viewName ) ) { propNames . addAll ( baseProps ) ; } } return viewToPropNames ; }
apply the base fields to other views if configured to do so .
241
13
150,403
public List < SquigglyNode > parse ( String filter ) { filter = StringUtils . trim ( filter ) ; if ( StringUtils . isEmpty ( filter ) ) { return Collections . emptyList ( ) ; } // get it from the cache if we can List < SquigglyNode > cachedNodes = CACHE . getIfPresent ( filter ) ; if ( cachedNodes != null ) { return cachedNodes ; } SquigglyExpressionLexer lexer = ThrowingErrorListener . overwrite ( new SquigglyExpressionLexer ( new ANTLRInputStream ( filter ) ) ) ; SquigglyExpressionParser parser = ThrowingErrorListener . overwrite ( new SquigglyExpressionParser ( new CommonTokenStream ( lexer ) ) ) ; Visitor visitor = new Visitor ( ) ; List < SquigglyNode > nodes = Collections . unmodifiableList ( visitor . visit ( parser . parse ( ) ) ) ; CACHE . put ( filter , nodes ) ; return nodes ; }
Parse a filter expression .
218
6
150,404
public static < E > Collection < E > collectify ( ObjectMapper mapper , Object source , Class < ? extends Collection > targetCollectionType , Class < E > targetElementType ) { CollectionType collectionType = mapper . getTypeFactory ( ) . constructCollectionType ( targetCollectionType , targetElementType ) ; return objectify ( mapper , convertToCollection ( source ) , collectionType ) ; }
Convert an object to a collection .
86
8
150,405
public static List < Map < String , Object > > listify ( ObjectMapper mapper , Object source ) { return ( List < Map < String , Object > > ) collectify ( mapper , source , List . class ) ; }
Convert an object to a list of maps .
50
10
150,406
public static < E > List < E > listify ( ObjectMapper mapper , Object source , Class < E > targetElementType ) { return ( List < E > ) collectify ( mapper , source , List . class , targetElementType ) ; }
Convert an object to a list .
55
8
150,407
public static Object objectify ( ObjectMapper mapper , Object source ) { return objectify ( mapper , source , Object . class ) ; }
Converts an object to an object with squiggly filters applied .
31
14
150,408
public static < T > T objectify ( ObjectMapper mapper , Object source , JavaType targetType ) { try { return mapper . readValue ( mapper . writeValueAsBytes ( source ) , targetType ) ; } catch ( RuntimeException e ) { throw e ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } }
Converts an object to an instance of the target type .
76
12
150,409
public static Set < Map < String , Object > > setify ( ObjectMapper mapper , Object source ) { return ( Set < Map < String , Object > > ) collectify ( mapper , source , Set . class ) ; }
Convert an object to a set of maps .
50
10
150,410
public static < E > Set < E > setify ( ObjectMapper mapper , Object source , Class < E > targetElementType ) { return ( Set < E > ) collectify ( mapper , source , Set . class , targetElementType ) ; }
Convert an object to a set .
55
8
150,411
public static String stringify ( ObjectMapper mapper , Object object ) { try { return mapper . writeValueAsString ( object ) ; } catch ( JsonProcessingException e ) { throw new IllegalArgumentException ( e ) ; } }
Takes an object and converts it to a string .
53
11
150,412
private Path getPath ( PropertyWriter writer , JsonStreamContext sc ) { LinkedList < PathElement > elements = new LinkedList <> ( ) ; if ( sc != null ) { elements . add ( new PathElement ( writer . getName ( ) , sc . getCurrentValue ( ) ) ) ; sc = sc . getParent ( ) ; } while ( sc != null ) { if ( sc . getCurrentName ( ) != null && sc . getCurrentValue ( ) != null ) { elements . addFirst ( new PathElement ( sc . getCurrentName ( ) , sc . getCurrentValue ( ) ) ) ; } sc = sc . getParent ( ) ; } return new Path ( elements ) ; }
create a path structure representing the object graph
152
8
150,413
private boolean pathMatches ( Path path , SquigglyContext context ) { List < SquigglyNode > nodes = context . getNodes ( ) ; Set < String > viewStack = null ; SquigglyNode viewNode = null ; int pathSize = path . getElements ( ) . size ( ) ; int lastIdx = pathSize - 1 ; for ( int i = 0 ; i < pathSize ; i ++ ) { PathElement element = path . getElements ( ) . get ( i ) ; if ( viewNode != null && ! viewNode . isSquiggly ( ) ) { Class beanClass = element . getBeanClass ( ) ; if ( beanClass != null && ! Map . class . isAssignableFrom ( beanClass ) ) { Set < String > propertyNames = getPropertyNamesFromViewStack ( element , viewStack ) ; if ( ! propertyNames . contains ( element . getName ( ) ) ) { return false ; } } } else if ( nodes . isEmpty ( ) ) { return false ; } else { SquigglyNode match = findBestSimpleNode ( element , nodes ) ; if ( match == null ) { match = findBestViewNode ( element , nodes ) ; if ( match != null ) { viewNode = match ; viewStack = addToViewStack ( viewStack , viewNode ) ; } } else if ( match . isAnyShallow ( ) ) { viewNode = match ; } else if ( match . isAnyDeep ( ) ) { return true ; } if ( match == null ) { if ( isJsonUnwrapped ( element ) ) { continue ; } return false ; } if ( match . isNegated ( ) ) { return false ; } nodes = match . getChildren ( ) ; if ( i < lastIdx && nodes . isEmpty ( ) && ! match . isEmptyNested ( ) && SquigglyConfig . isFilterImplicitlyIncludeBaseFields ( ) ) { nodes = BASE_VIEW_NODES ; } } } return true ; }
perform the actual matching
436
5
150,414
public static SortedMap < String , Object > asMap ( ) { SortedMap < String , Object > metrics = Maps . newTreeMap ( ) ; METRICS_SOURCE . applyMetrics ( metrics ) ; return metrics ; }
Gets the metrics as a map whose keys are the metric name and whose values are the metric values .
50
21
150,415
public static ByteBuffer newDirectByteBuffer ( long addr , int size , Object att ) { dbbCC . setAccessible ( true ) ; Object b = null ; try { b = dbbCC . newInstance ( new Long ( addr ) , new Integer ( size ) , att ) ; return ByteBuffer . class . cast ( b ) ; } catch ( Exception e ) { throw new IllegalStateException ( String . format ( "Failed to create DirectByteBuffer: %s" , e . getMessage ( ) ) ) ; } }
Create a new DirectByteBuffer from a given address and size . The returned DirectByteBuffer does not release the memory by itself .
113
26
150,416
public void releaseAll ( ) { synchronized ( this ) { Object [ ] refSet = allocatedMemoryReferences . values ( ) . toArray ( ) ; if ( refSet . length != 0 ) { logger . finer ( "Releasing allocated memory regions" ) ; } for ( Object ref : refSet ) { release ( ( MemoryReference ) ref ) ; } } }
Release all memory addresses taken by this allocator . Be careful in using this method since all of the memory addresses become invalid .
76
25
150,417
public static String md5sum ( InputStream input ) throws IOException { InputStream in = new BufferedInputStream ( input ) ; try { MessageDigest digest = java . security . MessageDigest . getInstance ( "MD5" ) ; DigestInputStream digestInputStream = new DigestInputStream ( in , digest ) ; while ( digestInputStream . read ( ) >= 0 ) { } OutputStream md5out = new ByteArrayOutputStream ( ) ; md5out . write ( digest . digest ( ) ) ; return md5out . toString ( ) ; } catch ( NoSuchAlgorithmException e ) { throw new IllegalStateException ( "MD5 algorithm is not available: " + e . getMessage ( ) ) ; } finally { in . close ( ) ; } }
Computes the MD5 value of the input stream
166
10
150,418
public void fill ( long offset , long length , byte value ) { unsafe . setMemory ( address ( ) + offset , length , value ) ; }
Fill the buffer of the specified range with a given value
31
11
150,419
public void copyTo ( int srcOffset , byte [ ] destArray , int destOffset , int size ) { int cursor = destOffset ; for ( ByteBuffer bb : toDirectByteBuffers ( srcOffset , size ) ) { int bbSize = bb . remaining ( ) ; if ( ( cursor + bbSize ) > destArray . length ) throw new ArrayIndexOutOfBoundsException ( String . format ( "cursor + bbSize = %,d" , cursor + bbSize ) ) ; bb . get ( destArray , cursor , bbSize ) ; cursor += bbSize ; } }
Copy the contents of this buffer begginning from the srcOffset to a destination byte array
134
17
150,420
public void copyTo ( long srcOffset , LBufferAPI dest , long destOffset , long size ) { unsafe . copyMemory ( address ( ) + srcOffset , dest . address ( ) + destOffset , size ) ; }
Copy the contents of this buffer to the destination LBuffer
47
11
150,421
public LBuffer slice ( long from , long to ) { if ( from > to ) throw new IllegalArgumentException ( String . format ( "invalid range %,d to %,d" , from , to ) ) ; long size = to - from ; LBuffer b = new LBuffer ( size ) ; copyTo ( from , b , 0 , size ) ; return b ; }
Extract a slice [ from to ) of this buffer . This methods creates a copy of the specified region .
82
22
150,422
public byte [ ] toArray ( ) { if ( size ( ) > Integer . MAX_VALUE ) throw new IllegalStateException ( "Cannot create byte array of more than 2GB" ) ; int len = ( int ) size ( ) ; ByteBuffer bb = toDirectByteBuffer ( 0L , len ) ; byte [ ] b = new byte [ len ] ; // Copy data to the array bb . get ( b , 0 , len ) ; return b ; }
Convert this buffer to a java array .
100
9
150,423
public void writeTo ( WritableByteChannel channel ) throws IOException { for ( ByteBuffer buffer : toDirectByteBuffers ( ) ) { channel . write ( buffer ) ; } }
Writes the buffer contents to the given byte channel .
39
11
150,424
public void writeTo ( File file ) throws IOException { FileChannel channel = new FileOutputStream ( file ) . getChannel ( ) ; try { writeTo ( channel ) ; } finally { channel . close ( ) ; } }
Dump the buffer contents to a file
48
8
150,425
public int readFrom ( byte [ ] src , int srcOffset , long destOffset , int length ) { int readLen = ( int ) Math . min ( src . length - srcOffset , Math . min ( size ( ) - destOffset , length ) ) ; ByteBuffer b = toDirectByteBuffer ( destOffset , readLen ) ; b . position ( 0 ) ; b . put ( src , srcOffset , readLen ) ; return readLen ; }
Read the given source byte array then overwrite this buffer s contents
96
12
150,426
public int readFrom ( ByteBuffer src , long destOffset ) { if ( src . remaining ( ) + destOffset >= size ( ) ) throw new BufferOverflowException ( ) ; int readLen = src . remaining ( ) ; ByteBuffer b = toDirectByteBuffer ( destOffset , readLen ) ; b . position ( 0 ) ; b . put ( src ) ; return readLen ; }
Reads the given source byte buffer into this buffer at the given offset
83
14
150,427
public static LBuffer loadFrom ( File file ) throws IOException { FileChannel fin = new FileInputStream ( file ) . getChannel ( ) ; long fileSize = fin . size ( ) ; if ( fileSize > Integer . MAX_VALUE ) throw new IllegalArgumentException ( "Cannot load from file more than 2GB: " + file ) ; LBuffer b = new LBuffer ( ( int ) fileSize ) ; long pos = 0L ; WritableChannelWrap ch = new WritableChannelWrap ( b ) ; while ( pos < fileSize ) { pos += fin . transferTo ( 0 , fileSize , ch ) ; } return b ; }
Create an LBuffer from a given file .
141
9
150,428
public ByteBuffer [ ] toDirectByteBuffers ( long offset , long size ) { long pos = offset ; long blockSize = Integer . MAX_VALUE ; long limit = offset + size ; int numBuffers = ( int ) ( ( size + ( blockSize - 1 ) ) / blockSize ) ; ByteBuffer [ ] result = new ByteBuffer [ numBuffers ] ; int index = 0 ; while ( pos < limit ) { long blockLength = Math . min ( limit - pos , blockSize ) ; result [ index ++ ] = UnsafeUtil . newDirectByteBuffer ( address ( ) + pos , ( int ) blockLength , this ) . order ( ByteOrder . nativeOrder ( ) ) ; pos += blockLength ; } return result ; }
Gives an sequence of ByteBuffers of a specified range . Writing to these ByteBuffers modifies the contents of this LBuffer .
159
28
150,429
public String getWrappingHint ( String fieldName ) { if ( isEmpty ( ) ) { return "" ; } return String . format ( " You can use this expression: %s(%s(%s))" , formatMethod ( wrappingMethodOwnerName , wrappingMethodName , "" ) , formatMethod ( copyMethodOwnerName , copyMethodName , copyTypeParameterName ) , fieldName ) ; }
For given field name get the actual hint message
86
9
150,430
public static EffectiveAssignmentInsnFinder newInstance ( final FieldNode targetVariable , final Collection < ControlFlowBlock > controlFlowBlocks ) { return new EffectiveAssignmentInsnFinder ( checkNotNull ( targetVariable ) , checkNotNull ( controlFlowBlocks ) ) ; }
Static factory method .
59
4
150,431
public Collection < FieldNode > removeAndGetCandidatesWithoutInitialisingMethod ( ) { final List < FieldNode > result = new ArrayList < FieldNode > ( ) ; for ( final Map . Entry < FieldNode , Initialisers > entry : candidatesAndInitialisers . entrySet ( ) ) { final Initialisers setters = entry . getValue ( ) ; final List < MethodNode > initialisingMethods = setters . getMethods ( ) ; if ( initialisingMethods . isEmpty ( ) ) { result . add ( entry . getKey ( ) ) ; } } for ( final FieldNode unassociatedVariable : result ) { candidatesAndInitialisers . remove ( unassociatedVariable ) ; } return result ; }
Removes all candidates from this collection which are not associated with an initialising method .
148
17
150,432
protected final void verify ( ) { collectInitialisers ( ) ; verifyCandidates ( ) ; verifyInitialisers ( ) ; collectPossibleInitialValues ( ) ; verifyPossibleInitialValues ( ) ; collectEffectiveAssignmentInstructions ( ) ; verifyEffectiveAssignmentInstructions ( ) ; collectAssignmentGuards ( ) ; verifyAssignmentGuards ( ) ; end ( ) ; }
Template method for verification of lazy initialisation .
80
9
150,433
protected void mergeHardcodedResultsFrom ( Configuration otherConfiguration ) { Map < Dotted , AnalysisResult > resultsMap = hardcodedResults . build ( ) . stream ( ) . collect ( Collectors . toMap ( r -> r . className , r -> r ) ) ; resultsMap . putAll ( otherConfiguration . hardcodedResults ( ) ) ; hardcodedResults = ImmutableSet . < AnalysisResult > builder ( ) . addAll ( resultsMap . values ( ) ) ; }
Merges the hardcoded results of this Configuration with the given Configuration .
101
14
150,434
protected void mergeImmutableContainerTypesFrom ( Configuration otherConfiguration ) { Set < Dotted > union = Sets . union ( hardcodedImmutableContainerClasses . build ( ) , otherConfiguration . immutableContainerClasses ( ) ) ; hardcodedImmutableContainerClasses = ImmutableSet . < Dotted > builder ( ) . addAll ( union ) ; }
Merges the immutable container types of this Configuration with the given Configuration .
75
14
150,435
protected final void hardcodeValidCopyMethod ( Class < ? > fieldType , String fullyQualifiedMethodName , Class < ? > argType ) { if ( argType == null || fieldType == null || fullyQualifiedMethodName == null ) { throw new IllegalArgumentException ( "All parameters must be supplied - no nulls" ) ; } String className = fullyQualifiedMethodName . substring ( 0 , fullyQualifiedMethodName . lastIndexOf ( "." ) ) ; String methodName = fullyQualifiedMethodName . substring ( fullyQualifiedMethodName . lastIndexOf ( "." ) + 1 ) ; String desc = null ; try { if ( MethodIs . aConstructor ( methodName ) ) { Constructor < ? > ctor = Class . forName ( className ) . getDeclaredConstructor ( argType ) ; desc = Type . getConstructorDescriptor ( ctor ) ; } else { Method method = Class . forName ( className ) . getMethod ( methodName , argType ) ; desc = Type . getMethodDescriptor ( method ) ; } } catch ( NoSuchMethodException e ) { rethrow ( "No such method" , e ) ; } catch ( SecurityException e ) { rethrow ( "Security error" , e ) ; } catch ( ClassNotFoundException e ) { rethrow ( "Class not found" , e ) ; } CopyMethod copyMethod = new CopyMethod ( dotted ( className ) , methodName , desc ) ; hardcodeValidCopyMethod ( fieldType , copyMethod ) ; }
Hardcode a copy method as being valid . This should be used to tell Mutability Detector about a method which copies a collection and when the copy can be wrapped in an immutable wrapper we can consider the assignment immutable . Useful for allowing Mutability Detector to correctly work with other collections frameworks such as Google Guava . Reflection is used to obtain the method s descriptor and to verify the method s existence .
334
82
150,436
public static AliasFinder newInstance ( final String variableName , final ControlFlowBlock controlFlowBlockToExamine ) { checkArgument ( ! variableName . isEmpty ( ) ) ; return new AliasFinder ( variableName , checkNotNull ( controlFlowBlockToExamine ) ) ; }
Creates a new instance of this class .
64
9
150,437
private void generateCopyingPart ( WrappingHint . Builder builder ) { ImmutableCollection < CopyMethod > copyMethods = ImmutableMultimap . < String , CopyMethod > builder ( ) . putAll ( configuration . FIELD_TYPE_TO_COPY_METHODS ) . putAll ( userDefinedCopyMethods ) . build ( ) . get ( typeAssignedToField ) ; if ( copyMethods . isEmpty ( ) ) { throw new WrappingHintGenerationException ( ) ; } CopyMethod firstSuitable = copyMethods . iterator ( ) . next ( ) ; builder . setCopyMethodOwnerName ( firstSuitable . owner . toString ( ) ) . setCopyMethodName ( firstSuitable . name ) ; if ( firstSuitable . isGeneric && typeSignature != null ) { CollectionField withRemovedWildcards = CollectionField . from ( typeAssignedToField , typeSignature ) . transformGenericTree ( GenericType :: withoutWildcard ) ; builder . setCopyTypeParameterName ( formatTypeParameter ( withRemovedWildcards . asSimpleString ( ) ) ) ; } }
Pick arbitrary copying method from available configuration and don t forget to set generic method type if required .
236
19
150,438
private void generateWrappingPart ( WrappingHint . Builder builder ) { builder . setWrappingMethodOwnerName ( configuration . UNMODIFIABLE_METHOD_OWNER ) . setWrappingMethodName ( configuration . FIELD_TYPE_TO_UNMODIFIABLE_METHOD . get ( typeAssignedToField ) ) ; }
Pick arbitrary wrapping method . No generics should be set .
73
12
150,439
public void setBorderWidth ( int borderWidth ) { this . borderWidth = borderWidth ; if ( paintBorder != null ) paintBorder . setStrokeWidth ( borderWidth ) ; requestLayout ( ) ; invalidate ( ) ; }
Sets the CircularImageView s border width in pixels .
50
13
150,440
public void setShadow ( float radius , float dx , float dy , int color ) { shadowRadius = radius ; shadowDx = dx ; shadowDy = dy ; shadowColor = color ; updateShadow ( ) ; }
Enables a dark shadow for this CircularImageView . If the radius is set to 0 the shadow is removed .
47
24
150,441
public Bitmap drawableToBitmap ( Drawable drawable ) { if ( drawable == null ) // Don't do anything without a proper drawable return null ; else if ( drawable instanceof BitmapDrawable ) { // Use the getBitmap() method instead if BitmapDrawable Log . i ( TAG , "Bitmap drawable!" ) ; return ( ( BitmapDrawable ) drawable ) . getBitmap ( ) ; } int intrinsicWidth = drawable . getIntrinsicWidth ( ) ; int intrinsicHeight = drawable . getIntrinsicHeight ( ) ; if ( ! ( intrinsicWidth > 0 && intrinsicHeight > 0 ) ) return null ; try { // Create Bitmap object out of the drawable Bitmap bitmap = Bitmap . createBitmap ( intrinsicWidth , intrinsicHeight , Bitmap . Config . ARGB_8888 ) ; Canvas canvas = new Canvas ( bitmap ) ; drawable . setBounds ( 0 , 0 , canvas . getWidth ( ) , canvas . getHeight ( ) ) ; drawable . draw ( canvas ) ; return bitmap ; } catch ( OutOfMemoryError e ) { // Simply return null of failed bitmap creations Log . e ( TAG , "Encountered OutOfMemoryError while generating bitmap!" ) ; return null ; } }
Convert a drawable object into a Bitmap .
282
11
150,442
public void updateBitmapShader ( ) { if ( image == null ) return ; shader = new BitmapShader ( image , Shader . TileMode . CLAMP , Shader . TileMode . CLAMP ) ; if ( canvasSize != image . getWidth ( ) || canvasSize != image . getHeight ( ) ) { Matrix matrix = new Matrix ( ) ; float scale = ( float ) canvasSize / ( float ) image . getWidth ( ) ; matrix . setScale ( scale , scale ) ; shader . setLocalMatrix ( matrix ) ; } }
Re - initializes the shader texture used to fill in the Circle upon drawing .
118
16
150,443
public void refreshBitmapShader ( ) { shader = new BitmapShader ( Bitmap . createScaledBitmap ( image , canvasSize , canvasSize , false ) , Shader . TileMode . CLAMP , Shader . TileMode . CLAMP ) ; }
Reinitializes the shader texture used to fill in the Circle upon drawing .
58
15
150,444
private int calcItemWidth ( RecyclerView rvCategories ) { if ( itemWidth == null || itemWidth == 0 ) { for ( int i = 0 ; i < rvCategories . getChildCount ( ) ; i ++ ) { itemWidth = rvCategories . getChildAt ( i ) . getWidth ( ) ; if ( itemWidth != 0 ) { break ; } } } // in case of call before view was created if ( itemWidth == null ) { itemWidth = 0 ; } return itemWidth ; }
very big duct tape
114
4
150,445
public final void setOrientation ( int orientation ) { mOrientation = orientation ; mOrientationState = getOrientationStateFromParam ( mOrientation ) ; invalidate ( ) ; if ( mOuterAdapter != null ) { mOuterAdapter . setOrientation ( mOrientation ) ; } }
Sets orientation of loopbar
72
6
150,446
@ SuppressWarnings ( "unused" ) public void selectItem ( int position , boolean invokeListeners ) { IOperationItem item = mOuterAdapter . getItem ( position ) ; IOperationItem oldHidedItem = mOuterAdapter . getItem ( mRealHidedPosition ) ; int realPosition = mOuterAdapter . normalizePosition ( position ) ; //do nothing if position not changed if ( realPosition == mCurrentItemPosition ) { return ; } int itemToShowAdapterPosition = position - realPosition + mRealHidedPosition ; item . setVisible ( false ) ; startSelectedViewOutAnimation ( position ) ; mOuterAdapter . notifyRealItemChanged ( position ) ; mRealHidedPosition = realPosition ; oldHidedItem . setVisible ( true ) ; mFlContainerSelected . requestLayout ( ) ; mOuterAdapter . notifyRealItemChanged ( itemToShowAdapterPosition ) ; mCurrentItemPosition = realPosition ; if ( invokeListeners ) { notifyItemClickListeners ( realPosition ) ; } if ( BuildConfig . DEBUG ) { Log . i ( TAG , "clicked on position =" + position ) ; } }
Select item by it s position
254
6
150,447
public IOrientationState getOrientationStateFromParam ( int orientation ) { switch ( orientation ) { case Orientation . ORIENTATION_HORIZONTAL_BOTTOM : return new OrientationStateHorizontalBottom ( ) ; case Orientation . ORIENTATION_HORIZONTAL_TOP : return new OrientationStateHorizontalTop ( ) ; case Orientation . ORIENTATION_VERTICAL_LEFT : return new OrientationStateVerticalLeft ( ) ; case Orientation . ORIENTATION_VERTICAL_RIGHT : return new OrientationStateVerticalRight ( ) ; default : return new OrientationStateHorizontalBottom ( ) ; } }
orientation state factory method
143
5
150,448
@ Override public < T extends ViewGroup . MarginLayoutParams > T setSelectionMargin ( int marginPx , T layoutParams ) { return mSelectionGravityState . setSelectionMargin ( marginPx , layoutParams ) ; }
dispatch to gravity state
58
5
150,449
public int consume ( Map < String , String > initialVars ) { int result = 0 ; for ( int i = 0 ; i < repeatNumber ; i ++ ) { result += super . consume ( initialVars ) ; } return result ; }
Overridden consume method . Corresponding parent method will be called necessary number of times
52
16
150,450
public static void main ( String [ ] args ) { String modelFile = "" ; String outputFile = "" ; int numberOfRows = 0 ; try { modelFile = args [ 0 ] ; outputFile = args [ 1 ] ; numberOfRows = Integer . valueOf ( args [ 2 ] ) ; } catch ( IndexOutOfBoundsException | NumberFormatException e ) { System . out . println ( "ERROR! Invalid command line arguments, expecting: <scxml model file> " + "<desired csv output file> <desired number of output rows>" ) ; return ; } FileInputStream model = null ; try { model = new FileInputStream ( modelFile ) ; } catch ( FileNotFoundException e ) { System . out . println ( "ERROR! Model file not found" ) ; return ; } SCXMLEngine engine = new SCXMLEngine ( ) ; engine . setModelByInputFileStream ( model ) ; engine . setBootstrapMin ( 5 ) ; DataConsumer consumer = new DataConsumer ( ) ; CSVFileWriter writer ; try { writer = new CSVFileWriter ( outputFile ) ; } catch ( IOException e ) { System . out . println ( "ERROR! Can not write to output csv file" ) ; return ; } consumer . addDataWriter ( writer ) ; DefaultDistributor dist = new DefaultDistributor ( ) ; dist . setThreadCount ( 5 ) ; dist . setMaxNumberOfLines ( numberOfRows ) ; dist . setDataConsumer ( consumer ) ; engine . process ( dist ) ; writer . closeCSVFile ( ) ; System . out . println ( "COMPLETE!" ) ; }
Main method handles all the setup tasks for DataGenerator a user would normally do themselves
357
17
150,451
public static Tuple2 < Double , Double > getRandomGeographicalLocation ( ) { return new Tuple2 <> ( ( double ) ( RandomHelper . randWithConfiguredSeed ( ) . nextInt ( 999 ) + 1 ) / 100 , ( double ) ( RandomHelper . randWithConfiguredSeed ( ) . nextInt ( 999 ) + 1 ) / 100 ) ; }
Get random geographical location
82
4
150,452
public static Double getDistanceBetweenCoordinates ( Tuple2 < Double , Double > point1 , Tuple2 < Double , Double > point2 ) { // sqrt( (x2-x1)^2 + (y2-y2)^2 ) Double xDiff = point1 . _1 ( ) - point2 . _1 ( ) ; Double yDiff = point1 . _2 ( ) - point2 . _2 ( ) ; return Math . sqrt ( xDiff * xDiff + yDiff * yDiff ) ; }
Get distance between geographical coordinates
117
5
150,453
public static Double getDistanceWithinThresholdOfCoordinates ( Tuple2 < Double , Double > point1 , Tuple2 < Double , Double > point2 ) { throw new NotImplementedError ( ) ; }
Not implemented .
47
3
150,454
public static Boolean areCoordinatesWithinThreshold ( Tuple2 < Double , Double > point1 , Tuple2 < Double , Double > point2 ) { return getDistanceBetweenCoordinates ( point1 , point2 ) < COORDINATE_THRESHOLD ; }
Whether or not points are within some threshold .
60
9
150,455
public static void main ( String [ ] args ) { //Adding custom equivalence class generation transformer - NOTE this will get applied during graph traversal--> //MODEL USAGE EXAMPLE: <assign name="var_out_V1_2" expr="%ssn"/> <dg:transform name="EQ"/> Map < String , DataTransformer > transformers = new HashMap < String , DataTransformer > ( ) ; transformers . put ( "EQ" , new EquivalenceClassTransformer ( ) ) ; Vector < CustomTagExtension > cte = new Vector < CustomTagExtension > ( ) ; cte . add ( new InLineTransformerExtension ( transformers ) ) ; Engine engine = new SCXMLEngine ( cte ) ; //will default to samplemachine, but you could specify a different file if you choose to InputStream is = CmdLine . class . getResourceAsStream ( "/" + ( args . length == 0 ? "samplemachine" : args [ 0 ] ) + ".xml" ) ; engine . setModelByInputFileStream ( is ) ; // Usually, this should be more than the number of threads you intend to run engine . setBootstrapMin ( 1 ) ; //Prepare the consumer with the proper writer and transformer DataConsumer consumer = new DataConsumer ( ) ; consumer . addDataTransformer ( new SampleMachineTransformer ( ) ) ; //Adding custom equivalence class generation transformer - NOTE this will get applied post data generation. //MODEL USAGE EXAMPLE: <dg:assign name="var_out_V2" set="%regex([0-9]{3}[A-Z0-9]{5})"/> consumer . addDataTransformer ( new EquivalenceClassTransformer ( ) ) ; consumer . addDataWriter ( new DefaultWriter ( System . out , new String [ ] { "var_1_1" , "var_1_2" , "var_1_3" , "var_1_4" , "var_1_5" , "var_1_6" , "var_1_7" , "var_2_1" , "var_2_2" , "var_2_3" , "var_2_4" , "var_2_5" , "var_2_6" , "var_2_7" , "var_2_8" } ) ) ; //Prepare the distributor DefaultDistributor defaultDistributor = new DefaultDistributor ( ) ; defaultDistributor . setThreadCount ( 1 ) ; defaultDistributor . setDataConsumer ( consumer ) ; Logger . getLogger ( "org.apache" ) . setLevel ( Level . WARN ) ; engine . process ( defaultDistributor ) ; }
Entry point for the example .
608
6
150,456
public static UserStub getStubWithRandomParams ( UserTypeVal userType ) { // Java coerces the return type as a Tuple2 of Objects -- but it's declared as a Tuple2 of Doubles! // Oh the joys of type erasure. Tuple2 < Double , Double > tuple = SocialNetworkUtilities . getRandomGeographicalLocation ( ) ; return new UserStub ( userType , new Tuple2 <> ( ( Double ) tuple . _1 ( ) , ( Double ) tuple . _2 ( ) ) , SocialNetworkUtilities . getRandomIsSecret ( ) ) ; }
Get random stub matching this user type
132
7
150,457
public void writeOutput ( DataPipe cr ) { String [ ] nextLine = new String [ cr . getDataMap ( ) . entrySet ( ) . size ( ) ] ; int count = 0 ; for ( Map . Entry < String , String > entry : cr . getDataMap ( ) . entrySet ( ) ) { nextLine [ count ] = entry . getValue ( ) ; count ++ ; } csvFile . writeNext ( nextLine ) ; }
Prints one line to the csv file
98
9
150,458
public boolean isHoliday ( String dateString ) { boolean isHoliday = false ; for ( Holiday date : EquivalenceClassTransformer . HOLIDAYS ) { if ( convertToReadableDate ( date . forYear ( Integer . parseInt ( dateString . substring ( 0 , 4 ) ) ) ) . equals ( dateString ) ) { isHoliday = true ; } } return isHoliday ; }
Checks if the date is a holiday
89
8
150,459
public String getNextDay ( String dateString , boolean onlyBusinessDays ) { DateTimeFormatter parser = ISODateTimeFormat . date ( ) ; DateTime date = parser . parseDateTime ( dateString ) . plusDays ( 1 ) ; Calendar cal = Calendar . getInstance ( ) ; cal . setTime ( date . toDate ( ) ) ; if ( onlyBusinessDays ) { if ( cal . get ( Calendar . DAY_OF_WEEK ) == 1 || cal . get ( Calendar . DAY_OF_WEEK ) == 7 || isHoliday ( date . toString ( ) . substring ( 0 , 10 ) ) ) { return getNextDay ( date . toString ( ) . substring ( 0 , 10 ) , true ) ; } else { return parser . print ( date ) ; } } else { return parser . print ( date ) ; } }
Takes a date and retrieves the next business day
185
11
150,460
public Date toDate ( String dateString ) { Date date = null ; DateFormat df = new SimpleDateFormat ( "yyyy-MM-dd" ) ; try { date = df . parse ( dateString ) ; } catch ( ParseException ex ) { System . out . println ( ex . fillInStackTrace ( ) ) ; } return date ; }
Takes a String and converts it to a Date
77
10
150,461
public String getRandomHoliday ( String earliest , String latest ) { String dateString = "" ; DateTimeFormatter parser = ISODateTimeFormat . date ( ) ; DateTime earlyDate = parser . parseDateTime ( earliest ) ; DateTime lateDate = parser . parseDateTime ( latest ) ; List < Holiday > holidays = new LinkedList <> ( ) ; int min = Integer . parseInt ( earlyDate . toString ( ) . substring ( 0 , 4 ) ) ; int max = Integer . parseInt ( lateDate . toString ( ) . substring ( 0 , 4 ) ) ; int range = max - min + 1 ; int randomYear = ( int ) ( Math . random ( ) * range ) + min ; for ( Holiday s : EquivalenceClassTransformer . HOLIDAYS ) { holidays . add ( s ) ; } Collections . shuffle ( holidays ) ; for ( Holiday holiday : holidays ) { dateString = convertToReadableDate ( holiday . forYear ( randomYear ) ) ; if ( toDate ( dateString ) . after ( toDate ( earliest ) ) && toDate ( dateString ) . before ( toDate ( latest ) ) ) { break ; } } return dateString ; }
Grab random holiday from the equivalence class that falls between the two dates
261
14
150,462
public int numOccurrences ( int year , int month , int day ) { DateTimeFormatter parser = ISODateTimeFormat . date ( ) ; DateTime date = parser . parseDateTime ( year + "-" + month + "-" + "01" ) ; Calendar cal = Calendar . getInstance ( ) ; cal . setTime ( date . toDate ( ) ) ; GregorianChronology calendar = GregorianChronology . getInstance ( ) ; DateTimeField field = calendar . dayOfMonth ( ) ; int days = 0 ; int count = 0 ; int num = field . getMaximumValue ( new LocalDate ( year , month , day , calendar ) ) ; while ( days < num ) { if ( cal . get ( Calendar . DAY_OF_WEEK ) == day ) { count ++ ; } date = date . plusDays ( 1 ) ; cal . setTime ( date . toDate ( ) ) ; days ++ ; } return count ; }
Given a year month and day find the number of occurrences of that day in the month
206
17
150,463
public String convertToReadableDate ( Holiday holiday ) { DateTimeFormatter parser = ISODateTimeFormat . date ( ) ; if ( holiday . isInDateForm ( ) ) { String month = Integer . toString ( holiday . getMonth ( ) ) . length ( ) < 2 ? "0" + holiday . getMonth ( ) : Integer . toString ( holiday . getMonth ( ) ) ; String day = Integer . toString ( holiday . getDayOfMonth ( ) ) . length ( ) < 2 ? "0" + holiday . getDayOfMonth ( ) : Integer . toString ( holiday . getDayOfMonth ( ) ) ; return holiday . getYear ( ) + "-" + month + "-" + day ; } else { /* * 5 denotes the final occurrence of the day in the month. Need to find actual * number of occurrences */ if ( holiday . getOccurrence ( ) == 5 ) { holiday . setOccurrence ( numOccurrences ( holiday . getYear ( ) , holiday . getMonth ( ) , holiday . getDayOfWeek ( ) ) ) ; } DateTime date = parser . parseDateTime ( holiday . getYear ( ) + "-" + holiday . getMonth ( ) + "-" + "01" ) ; Calendar calendar = Calendar . getInstance ( ) ; calendar . setTime ( date . toDate ( ) ) ; int count = 0 ; while ( count < holiday . getOccurrence ( ) ) { if ( calendar . get ( Calendar . DAY_OF_WEEK ) == holiday . getDayOfWeek ( ) ) { count ++ ; if ( count == holiday . getOccurrence ( ) ) { break ; } } date = date . plusDays ( 1 ) ; calendar . setTime ( date . toDate ( ) ) ; } return date . toString ( ) . substring ( 0 , 10 ) ; } }
Convert the holiday format from EquivalenceClassTransformer into a date format
396
16
150,464
public synchronized String requestBlock ( String name ) { if ( blocks . isEmpty ( ) ) { return "exit" ; } remainingBlocks . decrementAndGet ( ) ; return blocks . poll ( ) . createResponse ( ) ; }
Returns a description a block of work or exit if no more blocks exist
49
14
150,465
public String makeReport ( String name , String report ) { long increment = Long . valueOf ( report ) ; long currentLineCount = globalLineCounter . addAndGet ( increment ) ; if ( currentLineCount >= maxScenarios ) { return "exit" ; } else { return "ok" ; } }
Handles reports by consumers
66
5
150,466
public void prepareStatus ( ) { globalLineCounter = new AtomicLong ( 0 ) ; time = new AtomicLong ( System . currentTimeMillis ( ) ) ; startTime = System . currentTimeMillis ( ) ; lastCount = 0 ; // Status thread regularly reports on what is happening Thread statusThread = new Thread ( ) { public void run ( ) { while ( true ) { try { Thread . sleep ( 1000 ) ; } catch ( InterruptedException e ) { System . out . println ( "Status thread interrupted" ) ; } long thisTime = System . currentTimeMillis ( ) ; long currentCount = globalLineCounter . get ( ) ; if ( thisTime - time . get ( ) > 1000 ) { long oldTime = time . get ( ) ; time . set ( thisTime ) ; double avgRate = 1000.0 * currentCount / ( thisTime - startTime ) ; double instRate = 1000.0 * ( currentCount - lastCount ) / ( thisTime - oldTime ) ; lastCount = currentCount ; System . out . println ( currentCount + " AvgRage:" + ( ( int ) avgRate ) + " lines/sec instRate:" + ( ( int ) instRate ) + " lines/sec Unassigned Work: " + remainingBlocks . get ( ) + " blocks" ) ; } } } } ; statusThread . start ( ) ; }
Establishes a thread that on one second intervals reports the number of remaining WorkBlocks enqueued and the total number of lines written and reported by consumers
293
31
150,467
public void prepareServer ( ) { try { server = new Server ( 0 ) ; jettyHandler = new AbstractHandler ( ) { public void handle ( String target , Request req , HttpServletRequest request , HttpServletResponse response ) throws IOException , ServletException { response . setContentType ( "text/plain" ) ; String [ ] operands = request . getRequestURI ( ) . split ( "/" ) ; String name = "" ; String command = "" ; String value = "" ; //operands[0] = "", request starts with a "/" if ( operands . length >= 2 ) { name = operands [ 1 ] ; } if ( operands . length >= 3 ) { command = operands [ 2 ] ; } if ( operands . length >= 4 ) { value = operands [ 3 ] ; } if ( command . equals ( "report" ) ) { //report a number of lines written response . getWriter ( ) . write ( makeReport ( name , value ) ) ; } else if ( command . equals ( "request" ) && value . equals ( "block" ) ) { //request a new block of work response . getWriter ( ) . write ( requestBlock ( name ) ) ; } else if ( command . equals ( "request" ) && value . equals ( "name" ) ) { //request a new name to report with response . getWriter ( ) . write ( requestName ( ) ) ; } else { //non recognized response response . getWriter ( ) . write ( "exit" ) ; } ( ( Request ) request ) . setHandled ( true ) ; } } ; server . setHandler ( jettyHandler ) ; // Select any available port server . start ( ) ; Connector [ ] connectors = server . getConnectors ( ) ; NetworkConnector nc = ( NetworkConnector ) connectors [ 0 ] ; listeningPort = nc . getLocalPort ( ) ; hostName = InetAddress . getLocalHost ( ) . getHostName ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } }
Prepares a Jetty server for communicating with consumers .
445
11
150,468
public String getXmlFormatted ( Map < String , String > dataMap ) { StringBuilder sb = new StringBuilder ( ) ; for ( String var : outTemplate ) { sb . append ( appendXmlStartTag ( var ) ) ; sb . append ( dataMap . get ( var ) ) ; sb . append ( appendXmlEndingTag ( var ) ) ; } return sb . toString ( ) ; }
Given an array of variable names returns an Xml String of values .
94
14
150,469
private String appendXmlStartTag ( String value ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( "<" ) . append ( value ) . append ( ">" ) ; return sb . toString ( ) ; }
Helper xml start tag writer
53
5
150,470
private String appendXmlEndingTag ( String value ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( "</" ) . append ( value ) . append ( ">" ) ; return sb . toString ( ) ; }
Helper xml end tag writer
55
5
150,471
private Map < String , String > fillInitialVariables ( ) { Map < String , TransitionTarget > targets = model . getChildren ( ) ; Set < String > variables = new HashSet <> ( ) ; for ( TransitionTarget target : targets . values ( ) ) { OnEntry entry = target . getOnEntry ( ) ; List < Action > actions = entry . getActions ( ) ; for ( Action action : actions ) { if ( action instanceof Assign ) { String variable = ( ( Assign ) action ) . getName ( ) ; variables . add ( variable ) ; } else if ( action instanceof SetAssignExtension . SetAssignTag ) { String variable = ( ( SetAssignExtension . SetAssignTag ) action ) . getName ( ) ; variables . add ( variable ) ; } } } Map < String , String > result = new HashMap <> ( ) ; for ( String variable : variables ) { result . put ( variable , "" ) ; } return result ; }
Searches the model for all variable assignments and makes a default map of those variables setting them to
214
20
150,472
public List < PossibleState > bfs ( int min ) throws ModelException { List < PossibleState > bootStrap = new LinkedList <> ( ) ; TransitionTarget initial = model . getInitialTarget ( ) ; PossibleState initialState = new PossibleState ( initial , fillInitialVariables ( ) ) ; bootStrap . add ( initialState ) ; while ( bootStrap . size ( ) < min ) { PossibleState state = bootStrap . remove ( 0 ) ; TransitionTarget nextState = state . nextState ; if ( nextState . getId ( ) . equalsIgnoreCase ( "end" ) ) { throw new ModelException ( "Could not achieve required bootstrap without reaching end state" ) ; } //run every action in series List < Map < String , String > > product = new LinkedList <> ( ) ; product . add ( new HashMap <> ( state . variables ) ) ; OnEntry entry = nextState . getOnEntry ( ) ; List < Action > actions = entry . getActions ( ) ; for ( Action action : actions ) { for ( CustomTagExtension tagExtension : tagExtensionList ) { if ( tagExtension . getTagActionClass ( ) . isInstance ( action ) ) { product = tagExtension . pipelinePossibleStates ( action , product ) ; } } } //go through every transition and see which of the products are valid, adding them to the list List < Transition > transitions = nextState . getTransitionsList ( ) ; for ( Transition transition : transitions ) { String condition = transition . getCond ( ) ; TransitionTarget target = ( ( List < TransitionTarget > ) transition . getTargets ( ) ) . get ( 0 ) ; for ( Map < String , String > p : product ) { Boolean pass ; if ( condition == null ) { pass = true ; } else { //scrub the context clean so we may use it to evaluate transition conditional Context context = this . getRootContext ( ) ; context . reset ( ) ; //set up new context for ( Map . Entry < String , String > e : p . entrySet ( ) ) { context . set ( e . getKey ( ) , e . getValue ( ) ) ; } //evaluate condition try { pass = ( Boolean ) this . getEvaluator ( ) . eval ( context , condition ) ; } catch ( SCXMLExpressionException ex ) { pass = false ; } } //transition condition satisfied, add to bootstrap list if ( pass ) { PossibleState result = new PossibleState ( target , p ) ; bootStrap . add ( result ) ; } } } } return bootStrap ; }
Performs a partial BFS on model until the search frontier reaches the desired bootstrap size
564
18
150,473
public void process ( SearchDistributor distributor ) { List < PossibleState > bootStrap ; try { bootStrap = bfs ( bootStrapMin ) ; } catch ( ModelException e ) { bootStrap = new LinkedList <> ( ) ; } List < Frontier > frontiers = new LinkedList <> ( ) ; for ( PossibleState p : bootStrap ) { SCXMLFrontier dge = new SCXMLFrontier ( p , model , tagExtensionList ) ; frontiers . add ( dge ) ; } distributor . distribute ( frontiers ) ; }
Performs the BFS and gives the results to a distributor to distribute
128
14
150,474
public void setModelByInputFileStream ( InputStream inputFileStream ) { try { this . model = SCXMLParser . parse ( new InputSource ( inputFileStream ) , null , customActionsFromTagExtensions ( ) ) ; this . setStateMachine ( this . model ) ; } catch ( IOException | SAXException | ModelException e ) { e . printStackTrace ( ) ; } }
Sets the SCXML model with an InputStream
88
11
150,475
public void setModelByText ( String model ) { try { InputStream is = new ByteArrayInputStream ( model . getBytes ( ) ) ; this . model = SCXMLParser . parse ( new InputSource ( is ) , null , customActionsFromTagExtensions ( ) ) ; this . setStateMachine ( this . model ) ; } catch ( IOException | SAXException | ModelException e ) { e . printStackTrace ( ) ; } }
Sets the SCXML model with a string
99
10
150,476
public List < Set < String > > makeNWiseTuples ( String [ ] variables , int nWise ) { List < Set < String >> completeTuples = new ArrayList <> ( ) ; makeNWiseTuplesHelper ( completeTuples , variables , 0 , new HashSet < String > ( ) , nWise ) ; return completeTuples ; }
Produces all tuples of size n chosen from a list of variable names
78
15
150,477
public List < Map < String , String > > produceNWise ( int nWise , String [ ] coVariables , Map < String , String [ ] > variableDomains ) { List < Set < String >> tuples = makeNWiseTuples ( coVariables , nWise ) ; List < Map < String , String > > testCases = new ArrayList <> ( ) ; for ( Set < String > tuple : tuples ) { testCases . addAll ( expandTupleIntoTestCases ( tuple , variableDomains ) ) ; } return testCases ; }
Finds all nWise combinations of a set of variables each with a given domain of values
127
19
150,478
public List < Map < String , String > > pipelinePossibleStates ( NWiseAction action , List < Map < String , String > > possibleStateList ) { String [ ] coVariables = action . getCoVariables ( ) . split ( "," ) ; int n = Integer . valueOf ( action . getN ( ) ) ; List < Map < String , String > > newPossibleStateList = new ArrayList <> ( ) ; for ( Map < String , String > possibleState : possibleStateList ) { Map < String , String [ ] > variableDomains = new HashMap <> ( ) ; Map < String , String > defaultVariableValues = new HashMap <> ( ) ; for ( String variable : coVariables ) { String variableMetaInfo = possibleState . get ( variable ) ; String [ ] variableDomain = variableMetaInfo . split ( "," ) ; variableDomains . put ( variable , variableDomain ) ; defaultVariableValues . put ( variable , variableDomain [ 0 ] ) ; } List < Map < String , String > > nWiseCombinations = produceNWise ( n , coVariables , variableDomains ) ; for ( Map < String , String > nWiseCombination : nWiseCombinations ) { Map < String , String > newPossibleState = new HashMap <> ( possibleState ) ; newPossibleState . putAll ( defaultVariableValues ) ; newPossibleState . putAll ( nWiseCombination ) ; newPossibleStateList . add ( newPossibleState ) ; } } return newPossibleStateList ; }
Uses current variable assignments and info in an NWiseActionTag to expand on an n wise combinatorial set
340
23
150,479
public void transform ( DataPipe cr ) { Map < String , String > map = cr . getDataMap ( ) ; for ( String key : map . keySet ( ) ) { String value = map . get ( key ) ; if ( value . equals ( "#{customplaceholder}" ) ) { // Generate a random number int ran = rand . nextInt ( ) ; map . put ( key , String . valueOf ( ran ) ) ; } else if ( value . equals ( "#{divideBy2}" ) ) { String i = map . get ( "var_out_V3" ) ; String result = String . valueOf ( Integer . valueOf ( i ) / 2 ) ; map . put ( key , result ) ; } } }
Replace known tags in the current data values with actual values as appropriate
161
14
150,480
@ Override public void processOutput ( Map < String , String > resultsMap ) { queue . add ( resultsMap ) ; if ( queue . size ( ) > 10000 ) { log . info ( "Queue size " + queue . size ( ) + ", waiting" ) ; try { Thread . sleep ( 500 ) ; } catch ( InterruptedException ex ) { log . info ( "Interrupted " , ex ) ; } } }
Stores the output from a Frontier into the queue pausing and waiting if the given queue is too large
90
21
150,481
public void writeOutput ( DataPipe cr ) { try { context . write ( NullWritable . get ( ) , new Text ( cr . getPipeDelimited ( outTemplate ) ) ) ; } catch ( Exception e ) { throw new RuntimeException ( "Exception occurred while writing to Context" , e ) ; } }
Write to a context . Uses NullWritable for key so that only value of output string is ultimately written
69
21
150,482
public Map < String , String > decompose ( Frontier frontier , String modelText ) { if ( ! ( frontier instanceof SCXMLFrontier ) ) { return null ; } TransitionTarget target = ( ( SCXMLFrontier ) frontier ) . getRoot ( ) . nextState ; Map < String , String > variables = ( ( SCXMLFrontier ) frontier ) . getRoot ( ) . variables ; Map < String , String > decomposition = new HashMap < String , String > ( ) ; decomposition . put ( "target" , target . getId ( ) ) ; StringBuilder packedVariables = new StringBuilder ( ) ; for ( Map . Entry < String , String > variable : variables . entrySet ( ) ) { packedVariables . append ( variable . getKey ( ) ) ; packedVariables . append ( "::" ) ; packedVariables . append ( variable . getValue ( ) ) ; packedVariables . append ( ";" ) ; } decomposition . put ( "variables" , packedVariables . toString ( ) ) ; decomposition . put ( "model" , modelText ) ; return decomposition ; }
Takes a model and an SCXMLFrontier and decomposes the Frontier into a Map of Strings to Strings These strings can be sent over a network to get a Frontier past a gap
243
40
150,483
public static void printHelp ( final Options options ) { Collection < Option > c = options . getOptions ( ) ; System . out . println ( "Command line options are:" ) ; int longestLongOption = 0 ; for ( Option op : c ) { if ( op . getLongOpt ( ) . length ( ) > longestLongOption ) { longestLongOption = op . getLongOpt ( ) . length ( ) ; } } longestLongOption += 2 ; String spaces = StringUtils . repeat ( " " , longestLongOption ) ; for ( Option op : c ) { System . out . print ( "\t-" + op . getOpt ( ) + " --" + op . getLongOpt ( ) ) ; if ( op . getLongOpt ( ) . length ( ) < spaces . length ( ) ) { System . out . print ( spaces . substring ( op . getLongOpt ( ) . length ( ) ) ) ; } else { System . out . print ( " " ) ; } System . out . println ( op . getDescription ( ) ) ; } }
Prints the help on the command line
227
8
150,484
public static void main ( String [ ] args ) { CmdLine cmd = new CmdLine ( ) ; Configuration conf = new Configuration ( ) ; int res = 0 ; try { res = ToolRunner . run ( conf , cmd , args ) ; } catch ( Exception e ) { System . err . println ( "Error while running MR job" ) ; e . printStackTrace ( ) ; } System . exit ( res ) ; }
Entry point for this example Uses HDFS ToolRunner to wrap processing of
92
14
150,485
public static scala . collection . Iterable linkedListToScalaIterable ( LinkedList < ? > linkedList ) { return JavaConverters . asScalaIterableConverter ( linkedList ) . asScala ( ) ; }
Convert a Java LinkedList to a Scala Iterable .
53
13
150,486
public static < T > T flattenOption ( scala . Option < T > option ) { if ( option . isEmpty ( ) ) { return null ; } else { return option . get ( ) ; } }
Flattens an option into its value or else null which is not great but is usually more convenient in Java .
45
23
150,487
public List < Map < String , String > > pipelinePossibleStates ( Assign action , List < Map < String , String > > possibleStateList ) { for ( Map < String , String > possibleState : possibleStateList ) { possibleState . put ( action . getName ( ) , action . getExpr ( ) ) ; } return possibleStateList ; }
Assigns one variable to one value
77
8
150,488
public JSONObject getJsonFormatted ( Map < String , String > dataMap ) { JSONObject oneRowJson = new JSONObject ( ) ; for ( int i = 0 ; i < outTemplate . length ; i ++ ) { oneRowJson . put ( outTemplate [ i ] , dataMap . get ( outTemplate [ i ] ) ) ; } return oneRowJson ; }
Given an array of variable names returns a JsonObject of values .
84
14
150,489
public Vector < Graph < UserStub > > generateAllNodeDataTypeGraphCombinationsOfMaxLength ( int length ) { Vector < Graph < UserStub >> graphs = super . generateAllNodeDataTypeGraphCombinationsOfMaxLength ( length ) ; if ( WRITE_STRUCTURES_IN_PARALLEL ) { // Left as an exercise to the student. throw new NotImplementedError ( ) ; } else { int i = 0 ; for ( Iterator < Graph < UserStub > > iter = graphs . toIterator ( ) ; iter . hasNext ( ) ; ) { Graph < UserStub > graph = iter . next ( ) ; graph . setGraphId ( "S_" + ++ i + "_" + graph . allNodes ( ) . size ( ) ) ; graph . writeDotFile ( outDir + graph . graphId ( ) + ".gv" , false , ALSO_WRITE_AS_PNG ) ; } System . out . println ( "Wrote " + i + " graph files in DOT format to " + outDir + "" ) ; } return graphs ; }
Build all combinations of graph structures for generic event stubs of a maximum length
238
15
150,490
public int consume ( Map < String , String > initialVars ) { this . dataPipe = new DataPipe ( this ) ; // Set initial variables for ( Map . Entry < String , String > ent : initialVars . entrySet ( ) ) { dataPipe . getDataMap ( ) . put ( ent . getKey ( ) , ent . getValue ( ) ) ; } // Call transformers for ( DataTransformer dc : dataTransformers ) { dc . transform ( dataPipe ) ; } // Call writers for ( DataWriter oneOw : dataWriters ) { try { oneOw . writeOutput ( dataPipe ) ; } catch ( Exception e ) { //NOPMD log . error ( "Exception in DataWriter" , e ) ; } } return 1 ; }
Consumes a produced result . Calls every transformer in sequence then calls every dataWriter in sequence .
170
19
150,491
public Future < String > sendRequest ( final String path , final ReportingHandler reportingHandler ) { return threadPool . submit ( new Callable < String > ( ) { @ Override public String call ( ) { String response = getResponse ( path ) ; if ( reportingHandler != null ) { reportingHandler . handleResponse ( response ) ; } return response ; } } ) ; }
Creates a future that will send a request to the reporting host and call the handler with the response
78
20
150,492
public void transform ( DataPipe cr ) { for ( Map . Entry < String , String > entry : cr . getDataMap ( ) . entrySet ( ) ) { String value = entry . getValue ( ) ; if ( value . equals ( "#{customplaceholder}" ) ) { // Generate a random number int ran = rand . nextInt ( ) ; entry . setValue ( String . valueOf ( ran ) ) ; } } }
The transform method for this DataTransformer
94
8
150,493
public boolean isExit ( ) { if ( currentRow > finalRow ) { //request new block of work String newBlock = this . sendRequestSync ( "this/request/block" ) ; LineCountManager . LineCountBlock block = new LineCountManager . LineCountBlock ( 0 , 0 ) ; if ( newBlock . contains ( "exit" ) ) { getExitFlag ( ) . set ( true ) ; makeReport ( true ) ; return true ; } else { block . buildFromResponse ( newBlock ) ; } currentRow = block . getStart ( ) ; finalRow = block . getStop ( ) ; } else { //report the number of lines written makeReport ( false ) ; if ( exit . get ( ) ) { getExitFlag ( ) . set ( true ) ; return true ; } } return false ; }
Exit reporting up to distributor using information gained from status reports to the LineCountManager
176
16
150,494
@ Override public View getDropDownView ( int position , View convertView , ViewGroup parent ) { final ViewHolder viewHolder ; if ( convertView == null ) { convertView = mLayoutInflater . inflate ( R . layout . item_country , parent , false ) ; viewHolder = new ViewHolder ( ) ; viewHolder . mImageView = ( ImageView ) convertView . findViewById ( R . id . intl_phone_edit__country__item_image ) ; viewHolder . mNameView = ( TextView ) convertView . findViewById ( R . id . intl_phone_edit__country__item_name ) ; viewHolder . mDialCode = ( TextView ) convertView . findViewById ( R . id . intl_phone_edit__country__item_dialcode ) ; convertView . setTag ( viewHolder ) ; } else { viewHolder = ( ViewHolder ) convertView . getTag ( ) ; } Country country = getItem ( position ) ; viewHolder . mImageView . setImageResource ( getFlagResource ( country ) ) ; viewHolder . mNameView . setText ( country . getName ( ) ) ; viewHolder . mDialCode . setText ( String . format ( "+%s" , country . getDialCode ( ) ) ) ; return convertView ; }
Drop down item view
301
4
150,495
@ Override public View getView ( int position , View convertView , ViewGroup parent ) { Country country = getItem ( position ) ; if ( convertView == null ) { convertView = new ImageView ( getContext ( ) ) ; } ( ( ImageView ) convertView ) . setImageResource ( getFlagResource ( country ) ) ; return convertView ; }
Drop down selected view
77
4
150,496
private int getFlagResource ( Country country ) { return getContext ( ) . getResources ( ) . getIdentifier ( "country_" + country . getIso ( ) . toLowerCase ( ) , "drawable" , getContext ( ) . getPackageName ( ) ) ; }
Fetch flag resource by Country
62
6
150,497
private static String getJsonFromRaw ( Context context , int resource ) { String json ; try { InputStream inputStream = context . getResources ( ) . openRawResource ( resource ) ; int size = inputStream . available ( ) ; byte [ ] buffer = new byte [ size ] ; inputStream . read ( buffer ) ; inputStream . close ( ) ; json = new String ( buffer , "UTF-8" ) ; } catch ( IOException ex ) { ex . printStackTrace ( ) ; return null ; } return json ; }
Fetch JSON from RAW resource
115
6
150,498
public static CountryList getCountries ( Context context ) { if ( mCountries != null ) { return mCountries ; } mCountries = new CountryList ( ) ; try { JSONArray countries = new JSONArray ( getJsonFromRaw ( context , R . raw . countries ) ) ; for ( int i = 0 ; i < countries . length ( ) ; i ++ ) { try { JSONObject country = ( JSONObject ) countries . get ( i ) ; mCountries . add ( new Country ( country . getString ( "name" ) , country . getString ( "iso2" ) , country . getInt ( "dialCode" ) ) ) ; } catch ( JSONException e ) { e . printStackTrace ( ) ; } } } catch ( JSONException e ) { e . printStackTrace ( ) ; } return mCountries ; }
Import CountryList from RAW resource
185
6
150,499
private void init ( AttributeSet attrs ) { inflate ( getContext ( ) , R . layout . intl_phone_input , this ) ; /**+ * Country spinner */ mCountrySpinner = ( Spinner ) findViewById ( R . id . intl_phone_edit__country ) ; mCountrySpinnerAdapter = new CountrySpinnerAdapter ( getContext ( ) ) ; mCountrySpinner . setAdapter ( mCountrySpinnerAdapter ) ; mCountries = CountriesFetcher . getCountries ( getContext ( ) ) ; mCountrySpinnerAdapter . addAll ( mCountries ) ; mCountrySpinner . setOnItemSelectedListener ( mCountrySpinnerListener ) ; setFlagDefaults ( attrs ) ; /** * Phone text field */ mPhoneEdit = ( EditText ) findViewById ( R . id . intl_phone_edit__phone ) ; mPhoneEdit . addTextChangedListener ( mPhoneNumberWatcher ) ; setDefault ( ) ; setEditTextDefaults ( attrs ) ; }
Init after constructor
225
3