idx
int64
0
165k
question
stringlengths
73
5.81k
target
stringlengths
5
918
150,700
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 ( ...
Create a new DirectByteBuffer from a given address and size . The returned DirectByteBuffer does not release the memory by itself .
150,701
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 .
150,702
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 . rea...
Computes the MD5 value of the input stream
150,703
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
150,704
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 . forma...
Copy the contents of this buffer begginning from the srcOffset to a destination byte array
150,705
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
150,706
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 .
150,707
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 ] ; bb . get ( b , 0 , len ) ; return b ; }
Convert this buffer to a java array .
150,708
public void writeTo ( WritableByteChannel channel ) throws IOException { for ( ByteBuffer buffer : toDirectByteBuffers ( ) ) { channel . write ( buffer ) ; } }
Writes the buffer contents to the given byte channel .
150,709
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
150,710
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 ) ; ...
Read the given source byte array then overwrite this buffer s contents
150,711
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
150,712
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 ( ( i...
Create an LBuffer from a given file .
150,713
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 < li...
Gives an sequence of ByteBuffers of a specified range . Writing to these ByteBuffers modifies the contents of this LBuffer .
150,714
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
150,715
public static EffectiveAssignmentInsnFinder newInstance ( final FieldNode targetVariable , final Collection < ControlFlowBlock > controlFlowBlocks ) { return new EffectiveAssignmentInsnFinder ( checkNotNull ( targetVariable ) , checkNotNull ( controlFlowBlocks ) ) ; }
Static factory method .
150,716
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 Li...
Removes all candidates from this collection which are not associated with an initialising method .
150,717
protected final void verify ( ) { collectInitialisers ( ) ; verifyCandidates ( ) ; verifyInitialisers ( ) ; collectPossibleInitialValues ( ) ; verifyPossibleInitialValues ( ) ; collectEffectiveAssignmentInstructions ( ) ; verifyEffectiveAssignmentInstructions ( ) ; collectAssignmentGuards ( ) ; verifyAssignmentGuards (...
Template method for verification of lazy initialisation .
150,718
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 =...
Merges the hardcoded results of this Configuration with the given Configuration .
150,719
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 .
150,720
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 = fu...
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...
150,721
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 .
150,722
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 ( copy...
Pick arbitrary copying method from available configuration and don t forget to set generic method type if required .
150,723
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 .
150,724
public void setBorderWidth ( int borderWidth ) { this . borderWidth = borderWidth ; if ( paintBorder != null ) paintBorder . setStrokeWidth ( borderWidth ) ; requestLayout ( ) ; invalidate ( ) ; }
Sets the CircularImageView s border width in pixels .
150,725
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 .
150,726
public Bitmap drawableToBitmap ( Drawable drawable ) { if ( drawable == null ) return null ; else if ( drawable instanceof BitmapDrawable ) { Log . i ( TAG , "Bitmap drawable!" ) ; return ( ( BitmapDrawable ) drawable ) . getBitmap ( ) ; } int intrinsicWidth = drawable . getIntrinsicWidth ( ) ; int intrinsicHeight = dr...
Convert a drawable object into a Bitmap .
150,727
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 / ( floa...
Re - initializes the shader texture used to fill in the Circle upon drawing .
150,728
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 .
150,729
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 ; } } } if ( itemWidth == null ) { itemWidth = 0 ; } return ...
very big duct tape
150,730
public final void setOrientation ( int orientation ) { mOrientation = orientation ; mOrientationState = getOrientationStateFromParam ( mOrientation ) ; invalidate ( ) ; if ( mOuterAdapter != null ) { mOuterAdapter . setOrientation ( mOrientation ) ; } }
Sets orientation of loopbar
150,731
@ SuppressWarnings ( "unused" ) public void selectItem ( int position , boolean invokeListeners ) { IOperationItem item = mOuterAdapter . getItem ( position ) ; IOperationItem oldHidedItem = mOuterAdapter . getItem ( mRealHidedPosition ) ; int realPosition = mOuterAdapter . normalizePosition ( position ) ; if ( realPos...
Select item by it s position
150,732
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 . ORIE...
orientation state factory method
150,733
public < T extends ViewGroup . MarginLayoutParams > T setSelectionMargin ( int marginPx , T layoutParams ) { return mSelectionGravityState . setSelectionMargin ( marginPx , layoutParams ) ; }
dispatch to gravity state
150,734
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
150,735
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 ( "ERR...
Main method handles all the setup tasks for DataGenerator a user would normally do themselves
150,736
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
150,737
public static Double getDistanceBetweenCoordinates ( Tuple2 < Double , Double > point1 , Tuple2 < Double , Double > point2 ) { Double xDiff = point1 . _1 ( ) - point2 . _1 ( ) ; Double yDiff = point1 . _2 ( ) - point2 . _2 ( ) ; return Math . sqrt ( xDiff * xDiff + yDiff * yDiff ) ; }
Get distance between geographical coordinates
150,738
public static Double getDistanceWithinThresholdOfCoordinates ( Tuple2 < Double , Double > point1 , Tuple2 < Double , Double > point2 ) { throw new NotImplementedError ( ) ; }
Not implemented .
150,739
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 .
150,740
public static void main ( String [ ] args ) { Map < String , DataTransformer > transformers = new HashMap < String , DataTransformer > ( ) ; transformers . put ( "EQ" , new EquivalenceClassTransformer ( ) ) ; Vector < CustomTagExtension > cte = new Vector < CustomTagExtension > ( ) ; cte . add ( new InLineTransformerEx...
Entry point for the example .
150,741
public static UserStub getStubWithRandomParams ( UserTypeVal userType ) { 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
150,742
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
150,743
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
150,744
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 ( ...
Takes a date and retrieves the next business day
150,745
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
150,746
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 < > ( ) ; ...
Grab random holiday from the equivalence class that falls between the two dates
150,747
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 = Gregorian...
Given a year month and day find the number of occurrences of that day in the month
150,748
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 da...
Convert the holiday format from EquivalenceClassTransformer into a date format
150,749
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
150,750
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
150,751
public void prepareStatus ( ) { globalLineCounter = new AtomicLong ( 0 ) ; time = new AtomicLong ( System . currentTimeMillis ( ) ) ; startTime = System . currentTimeMillis ( ) ; lastCount = 0 ; Thread statusThread = new Thread ( ) { public void run ( ) { while ( true ) { try { Thread . sleep ( 1000 ) ; } catch ( Inter...
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
150,752
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 [ ] operan...
Prepares a Jetty server for communicating with consumers .
150,753
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 .
150,754
private String appendXmlStartTag ( String value ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( "<" ) . append ( value ) . append ( ">" ) ; return sb . toString ( ) ; }
Helper xml start tag writer
150,755
private String appendXmlEndingTag ( String value ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( "</" ) . append ( value ) . append ( ">" ) ; return sb . toString ( ) ; }
Helper xml end tag writer
150,756
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 . getAction...
Searches the model for all variable assignments and makes a default map of those variables setting them to
150,757
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 ( b...
Performs a partial BFS on model until the search frontier reaches the desired bootstrap size
150,758
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 S...
Performs the BFS and gives the results to a distributor to distribute
150,759
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
150,760
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 | ModelExcep...
Sets the SCXML model with a string
150,761
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
150,762
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 ...
Finds all nWise combinations of a set of variables each with a given domain of values
150,763
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 = ne...
Uses current variable assignments and info in an NWiseActionTag to expand on an n wise combinatorial set
150,764
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}" ) ) { int ran = rand . nextInt ( ) ; map . put ( key , String . valueOf ( ran ) ) ; } else if ( value . equa...
Replace known tags in the current data values with actual values as appropriate
150,765
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
150,766
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
150,767
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 ( ) . var...
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
150,768
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 ( )...
Prints the help on the command line
150,769
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 ( re...
Entry point for this example Uses HDFS ToolRunner to wrap processing of
150,770
public static scala . collection . Iterable linkedListToScalaIterable ( LinkedList < ? > linkedList ) { return JavaConverters . asScalaIterableConverter ( linkedList ) . asScala ( ) ; }
Convert a Java LinkedList to a Scala Iterable .
150,771
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 .
150,772
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
150,773
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 .
150,774
public Vector < Graph < UserStub > > generateAllNodeDataTypeGraphCombinationsOfMaxLength ( int length ) { Vector < Graph < UserStub > > graphs = super . generateAllNodeDataTypeGraphCombinationsOfMaxLength ( length ) ; if ( WRITE_STRUCTURES_IN_PARALLEL ) { throw new NotImplementedError ( ) ; } else { int i = 0 ; for ( I...
Build all combinations of graph structures for generic event stubs of a maximum length
150,775
public int consume ( Map < String , String > initialVars ) { this . dataPipe = new DataPipe ( this ) ; for ( Map . Entry < String , String > ent : initialVars . entrySet ( ) ) { dataPipe . getDataMap ( ) . put ( ent . getKey ( ) , ent . getValue ( ) ) ; } for ( DataTransformer dc : dataTransformers ) { dc . transform (...
Consumes a produced result . Calls every transformer in sequence then calls every dataWriter in sequence .
150,776
public Future < String > sendRequest ( final String path , final ReportingHandler reportingHandler ) { return threadPool . submit ( new Callable < String > ( ) { public String call ( ) { String response = getResponse ( path ) ; if ( reportingHandler != null ) { reportingHandler . handleResponse ( response ) ; } return ...
Creates a future that will send a request to the reporting host and call the handler with the response
150,777
public void transform ( DataPipe cr ) { for ( Map . Entry < String , String > entry : cr . getDataMap ( ) . entrySet ( ) ) { String value = entry . getValue ( ) ; if ( value . equals ( "#{customplaceholder}" ) ) { int ran = rand . nextInt ( ) ; entry . setValue ( String . valueOf ( ran ) ) ; } } }
The transform method for this DataTransformer
150,778
public boolean isExit ( ) { if ( currentRow > finalRow ) { 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...
Exit reporting up to distributor using information gained from status reports to the LineCountManager
150,779
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 ....
Drop down item view
150,780
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
150,781
private int getFlagResource ( Country country ) { return getContext ( ) . getResources ( ) . getIdentifier ( "country_" + country . getIso ( ) . toLowerCase ( ) , "drawable" , getContext ( ) . getPackageName ( ) ) ; }
Fetch flag resource by Country
150,782
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 ( ) ; jso...
Fetch JSON from RAW resource
150,783
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 coun...
Import CountryList from RAW resource
150,784
private void init ( AttributeSet attrs ) { inflate ( getContext ( ) , R . layout . intl_phone_input , this ) ; mCountrySpinner = ( Spinner ) findViewById ( R . id . intl_phone_edit__country ) ; mCountrySpinnerAdapter = new CountrySpinnerAdapter ( getContext ( ) ) ; mCountrySpinner . setAdapter ( mCountrySpinnerAdapter ...
Init after constructor
150,785
public void hideKeyboard ( ) { InputMethodManager inputMethodManager = ( InputMethodManager ) getContext ( ) . getApplicationContext ( ) . getSystemService ( Context . INPUT_METHOD_SERVICE ) ; inputMethodManager . hideSoftInputFromWindow ( mPhoneEdit . getWindowToken ( ) , 0 ) ; }
Hide keyboard from phoneEdit field
150,786
public void setDefault ( ) { try { TelephonyManager telephonyManager = ( TelephonyManager ) getContext ( ) . getSystemService ( Context . TELEPHONY_SERVICE ) ; String phone = telephonyManager . getLine1Number ( ) ; if ( phone != null && ! phone . isEmpty ( ) ) { this . setNumber ( phone ) ; } else { String iso = teleph...
Set default value Will try to retrieve phone number from device
150,787
public void setEmptyDefault ( String iso ) { if ( iso == null || iso . isEmpty ( ) ) { iso = DEFAULT_COUNTRY ; } int defaultIdx = mCountries . indexOfIso ( iso ) ; mSelectedCountry = mCountries . get ( defaultIdx ) ; mCountrySpinner . setSelection ( defaultIdx ) ; }
Set default value with
150,788
private void setHint ( ) { if ( mPhoneEdit != null && mSelectedCountry != null && mSelectedCountry . getIso ( ) != null ) { Phonenumber . PhoneNumber phoneNumber = mPhoneUtil . getExampleNumberForType ( mSelectedCountry . getIso ( ) , PhoneNumberUtil . PhoneNumberType . MOBILE ) ; if ( phoneNumber != null ) { mPhoneEdi...
Set hint number for country
150,789
@ SuppressWarnings ( "unused" ) public Phonenumber . PhoneNumber getPhoneNumber ( ) { try { String iso = null ; if ( mSelectedCountry != null ) { iso = mSelectedCountry . getIso ( ) ; } return mPhoneUtil . parse ( mPhoneEdit . getText ( ) . toString ( ) , iso ) ; } catch ( NumberParseException ignored ) { return null ;...
Get PhoneNumber object
150,790
@ SuppressWarnings ( "unused" ) public boolean isValid ( ) { Phonenumber . PhoneNumber phoneNumber = getPhoneNumber ( ) ; return phoneNumber != null && mPhoneUtil . isValidNumber ( phoneNumber ) ; }
Check if number is valid
150,791
@ SuppressWarnings ( "unused" ) public void setError ( CharSequence error , Drawable icon ) { mPhoneEdit . setError ( error , icon ) ; }
Sets an error message that will be displayed in a popup when the EditText has focus along with an icon displayed at the right - hand side .
150,792
public void setOnKeyboardDone ( final IntlPhoneInputListener listener ) { mPhoneEdit . setOnEditorActionListener ( new TextView . OnEditorActionListener ( ) { public boolean onEditorAction ( TextView v , int actionId , KeyEvent event ) { if ( actionId == EditorInfo . IME_ACTION_DONE ) { listener . done ( IntlPhoneInput...
Set keyboard done listener to detect when the user click DONE on his keyboard
150,793
private synchronized Client allocateClient ( int targetPlayer , String description ) throws IOException { Client result = openClients . get ( targetPlayer ) ; if ( result == null ) { final DeviceAnnouncement deviceAnnouncement = DeviceFinder . getInstance ( ) . getLatestAnnouncementFrom ( targetPlayer ) ; if ( deviceAn...
Finds or opens a client to talk to the dbserver on the specified player incrementing its use count .
150,794
private void closeClient ( Client client ) { logger . debug ( "Closing client {}" , client ) ; client . close ( ) ; openClients . remove ( client . targetPlayer ) ; useCounts . remove ( client ) ; timestamps . remove ( client ) ; }
When it is time to actually close a client do so and clean up the related data structures .
150,795
private synchronized void freeClient ( Client client ) { int current = useCounts . get ( client ) ; if ( current > 0 ) { timestamps . put ( client , System . currentTimeMillis ( ) ) ; useCounts . put ( client , current - 1 ) ; if ( ( current == 1 ) && ( idleLimit . get ( ) == 0 ) ) { closeClient ( client ) ; } } else {...
Decrements the client s use count and makes it eligible for closing if it is no longer in use .
150,796
public < T > T invokeWithClientSession ( int targetPlayer , ClientTask < T > task , String description ) throws Exception { if ( ! isRunning ( ) ) { throw new IllegalStateException ( "ConnectionManager is not running, aborting " + description ) ; } final Client client = allocateClient ( targetPlayer , description ) ; t...
Obtain a dbserver client session that can be used to perform some task call that task with the client then release the client .
150,797
@ SuppressWarnings ( "WeakerAccess" ) public int getPlayerDBServerPort ( int player ) { ensureRunning ( ) ; Integer result = dbServerPorts . get ( player ) ; if ( result == null ) { return - 1 ; } return result ; }
Look up the database server port reported by a given player . You should not use this port directly ; instead ask this class for a session to use while you communicate with the database .
150,798
private void requestPlayerDBServerPort ( DeviceAnnouncement announcement ) { Socket socket = null ; try { InetSocketAddress address = new InetSocketAddress ( announcement . getAddress ( ) , DB_SERVER_QUERY_PORT ) ; socket = new Socket ( ) ; socket . connect ( address , socketTimeout . get ( ) ) ; InputStream is = socke...
Query a player to determine the port on which its database server is running .
150,799
private byte [ ] receiveBytes ( InputStream is ) throws IOException { byte [ ] buffer = new byte [ 8192 ] ; int len = ( is . read ( buffer ) ) ; if ( len < 1 ) { throw new IOException ( "receiveBytes read " + len + " bytes." ) ; } return Arrays . copyOf ( buffer , len ) ; }
Receive some bytes from the player we are requesting metadata from .