idx
int64
0
41.2k
question
stringlengths
74
4.04k
target
stringlengths
7
750
37,000
public static double daleChallScore ( String strText ) { strText = cleanText ( strText ) ; int intDifficultWordCount = 0 ; List < String > arrWords = ( new WhitespaceTokenizer ( ) ) . tokenize ( strText ) ; int intWordCount = arrWords . size ( ) ; for ( int i = 0 ; i < intWordCount ; ++ i ) { if ( ! DALECHALL_WORDLIST . contains ( arrWords . get ( i ) ) ) { ++ intDifficultWordCount ; } } int intSentenceCount = sentenceCount ( strText ) ; double percentageOfDifficultWords = intDifficultWordCount / ( double ) intWordCount ; double score = 0.1579 * ( 100 * percentageOfDifficultWords ) + 0.0496 * ( intWordCount / ( double ) intSentenceCount ) ; if ( percentageOfDifficultWords > 0.05 ) { score += 3.6365 ; } return score ; }
Returns the Dale Chall Score of the text .
37,001
public static double daleChallGrade ( String strText ) { double score = daleChallScore ( strText ) ; if ( score < 5.0 ) { return 2.5 ; } else if ( score < 6.0 ) { return 5.5 ; } else if ( score < 7.0 ) { return 7.5 ; } else if ( score < 8.0 ) { return 9.5 ; } else if ( score < 9.0 ) { return 11.5 ; } else if ( score < 10.0 ) { return 14.0 ; } else { return 16.0 ; } }
Returns the Dale Chall Grade of the text .
37,002
public static double spacheScore ( String strText ) { strText = cleanText ( strText ) ; int intUniqueUnfamiliarWordCount = 0 ; Set < String > arrWords = new HashSet < > ( ( new WhitespaceTokenizer ( ) ) . tokenize ( strText ) ) ; for ( String word : arrWords ) { if ( ! SPACHE_WORDLIST . contains ( word ) ) { ++ intUniqueUnfamiliarWordCount ; } } int intSentenceCount = sentenceCount ( strText ) ; int intWordCount = wordCount ( strText ) ; return 0.121 * intWordCount / ( double ) intSentenceCount + 0.082 * intUniqueUnfamiliarWordCount + 0.659 ; }
Returns the Spache Score of the text .
37,003
private static int sentenceCount ( String strText ) { int numberOfDots = PHPMethods . substr_count ( strText , '.' ) ; if ( strText . charAt ( strText . length ( ) - 1 ) != '.' ) { ++ numberOfDots ; } return Math . max ( 1 , numberOfDots ) ; }
Returns sentence count for text .
37,004
private static String cleanText ( String strText ) { strText = HTMLParser . unsafeRemoveAllTags ( strText ) ; strText = strText . toLowerCase ( Locale . ENGLISH ) ; strText = StringCleaner . unifyTerminators ( strText ) ; strText = strText . replaceAll ( " [0-9]+ " , " " ) ; strText = StringCleaner . removeExtraSpaces ( strText ) ; return strText ; }
Trims removes line breaks multiple spaces and generally cleans text before processing .
37,005
private static double averageWordsPerSentence ( String strText ) { int intSentenceCount = sentenceCount ( strText ) ; int intWordCount = wordCount ( strText ) ; return ( intWordCount / ( double ) intSentenceCount ) ; }
Returns average words per sentence for text .
37,006
private static int totalSyllables ( String strText ) { int intSyllableCount = 0 ; List < String > arrWords = ( new WhitespaceTokenizer ( ) ) . tokenize ( strText ) ; int intWordCount = arrWords . size ( ) ; for ( int i = 0 ; i < intWordCount ; ++ i ) { intSyllableCount += syllableCount ( arrWords . get ( i ) ) ; } return intSyllableCount ; }
Returns total syllable count for text .
37,007
private static double averageSyllablesPerWord ( String strText ) { int intSyllableCount = totalSyllables ( strText ) ; int intWordCount = wordCount ( strText ) ; return ( intSyllableCount / ( double ) intWordCount ) ; }
Returns average syllables per word for text .
37,008
private static int wordsWithThreeSyllables ( String strText ) { int intLongWordCount = 0 ; List < String > arrWords = ( new WhitespaceTokenizer ( ) ) . tokenize ( strText ) ; int intWordCount = arrWords . size ( ) ; for ( int i = 0 ; i < intWordCount ; ++ i ) { if ( syllableCount ( arrWords . get ( i ) ) > 2 ) { ++ intLongWordCount ; } } return intLongWordCount ; }
Returns the number of words with more than three syllables .
37,009
private static double percentageWordsWithThreeSyllables ( String strText ) { int intWordCount = wordCount ( strText ) ; int intLongWordCount = wordsWithThreeSyllables ( strText ) ; double percentage = ( ( intLongWordCount / ( double ) intWordCount ) * 100.0 ) ; return percentage ; }
Returns the percentage of words with more than three syllables .
37,010
public static int similarityChars ( String txt1 , String txt2 ) { int sim = similar_char ( txt1 , txt1 . length ( ) , txt2 , txt2 . length ( ) ) ; return sim ; }
Checks the similarity of two strings and returns the number of matching chars in both strings .
37,011
public static double similarityPercentage ( String txt1 , String txt2 ) { double sim = similarityChars ( txt1 , txt2 ) ; return sim * 200.0 / ( txt1 . length ( ) + txt2 . length ( ) ) ; }
Checks the similarity of two strings and returns their similarity percentage .
37,012
public String extract ( String html , CETR . Parameters parameters ) { html = clearText ( html ) ; List < String > rows = extractRows ( html ) ; List < Integer > selectedRowIds = selectRows ( rows , parameters ) ; StringBuilder sb = new StringBuilder ( html . length ( ) ) ; for ( Integer rowId : selectedRowIds ) { String row = rows . get ( rowId ) ; row = StringCleaner . removeExtraSpaces ( HTMLParser . extractText ( row ) ) ; if ( row . isEmpty ( ) ) { continue ; } sb . append ( row ) . append ( " " ) ; } return sb . toString ( ) . trim ( ) ; }
Extracts the main content for an HTML page .
37,013
public static byte [ ] serialize ( Object obj ) { try ( ByteArrayOutputStream bos = new ByteArrayOutputStream ( ) ; ObjectOutputStream oos = new ObjectOutputStream ( bos ) ) { oos . writeObject ( obj ) ; return bos . toByteArray ( ) ; } catch ( IOException ex ) { throw new UncheckedIOException ( ex ) ; } }
Serialized the Object to byte array .
37,014
public static Object deserialize ( byte [ ] arr ) { try ( InputStream bis = new ByteArrayInputStream ( arr ) ; ObjectInputStream ois = new ObjectInputStream ( bis ) ) { return ois . readObject ( ) ; } catch ( IOException ex ) { throw new UncheckedIOException ( ex ) ; } catch ( ClassNotFoundException ex ) { throw new RuntimeException ( ex ) ; } }
Deserializes the byte array .
37,015
public static AssociativeArray copy2Unmodifiable ( AssociativeArray original ) { Map < Object , Object > internalData = new LinkedHashMap < > ( ) ; internalData . putAll ( original . internalData ) ; internalData = Collections . unmodifiableMap ( internalData ) ; return new AssociativeArray ( internalData ) ; }
Copies the provided AssociativeArray and builds a new which is unmodifiable .
37,016
public final void overwrite ( Map < Object , Object > data ) { internalData . clear ( ) ; internalData . putAll ( data ) ; }
Overwrites the contents of the internal data of this object with the ones of the provided map .
37,017
public final void multiplyValues ( double multiplier ) { for ( Map . Entry < Object , Object > entry : internalData . entrySet ( ) ) { Double previousValue = TypeInference . toDouble ( entry . getValue ( ) ) ; if ( previousValue == null ) { continue ; } internalData . put ( entry . getKey ( ) , previousValue * multiplier ) ; } }
Multiplies the values of the object with a particular multiplier . All the columns of this object should be numeric or boolean or else an exception is thrown .
37,018
@ SuppressWarnings ( "unchecked" ) public FlatDataList toFlatDataList ( ) { Collection < Object > values = internalData . values ( ) ; List < Object > list ; if ( values instanceof List < ? > ) { list = ( List < Object > ) values ; } else { list = new ArrayList ( values ) ; } return new FlatDataList ( list ) ; }
Returns a FlatDataList with the values of the internal map . The method might require to copy the data .
37,019
public void save ( String storageName ) { storageEngine . saveObject ( "data" , data ) ; storageEngine . rename ( storageName ) ; data = storageEngine . loadObject ( "data" , Data . class ) ; stored = true ; }
Saves the Dataframe to disk .
37,020
public void clear ( ) { data . yDataType = null ; data . atomicNextAvailableRecordId . set ( 0 ) ; data . xDataTypes . clear ( ) ; data . records . clear ( ) ; }
Clears all the internal Records of the Dataframe . The Dataframe can be used after you clear it .
37,021
public boolean remove ( Object o ) { Integer id = indexOf ( ( Record ) o ) ; if ( id == null ) { return false ; } remove ( id ) ; return true ; }
Removes the first occurrence of the specified element from this Dataframe if it is present and it does not update the metadata .
37,022
public boolean retainAll ( Collection < ? > c ) { boolean modified = false ; for ( Map . Entry < Integer , Record > e : entries ( ) ) { Integer rId = e . getKey ( ) ; Record r = e . getValue ( ) ; if ( ! c . contains ( r ) ) { remove ( rId ) ; modified = true ; } } if ( modified ) { recalculateMeta ( ) ; } return modified ; }
Retains only the elements in this collection that are contained in the specified collection and updates the meta data .
37,023
public Integer addRecord ( Record r ) { Integer rId = _unsafe_add ( r ) ; updateMeta ( r ) ; return rId ; }
Adds a Record in the Dataframe and returns its id .
37,024
public Integer set ( Integer rId , Record r ) { _unsafe_set ( rId , r ) ; updateMeta ( r ) ; return rId ; }
Sets the record of a particular id in the dataset . If the record does not exist it will be added with the specific id and the next added record will have as id the next integer .
37,025
public FlatDataList getXColumn ( Object column ) { FlatDataList flatDataList = new FlatDataList ( ) ; for ( Record r : values ( ) ) { flatDataList . add ( r . getX ( ) . get ( column ) ) ; } return flatDataList ; }
It extracts the values of a particular column from all records and stores them into an FlatDataList .
37,026
public FlatDataList getYColumn ( ) { FlatDataList flatDataList = new FlatDataList ( ) ; for ( Record r : values ( ) ) { flatDataList . add ( r . getY ( ) ) ; } return flatDataList ; }
It extracts the values of the response variables from all observations and stores them into an FlatDataList .
37,027
public void dropXColumns ( Set < Object > columnSet ) { columnSet . retainAll ( data . xDataTypes . keySet ( ) ) ; if ( columnSet . isEmpty ( ) ) { return ; } data . xDataTypes . keySet ( ) . removeAll ( columnSet ) ; streamExecutor . forEach ( StreamMethods . stream ( entries ( ) , true ) , e -> { Integer rId = e . getKey ( ) ; Record r = e . getValue ( ) ; AssociativeArray xData = r . getX ( ) . copy ( ) ; boolean modified = xData . keySet ( ) . removeAll ( columnSet ) ; if ( modified ) { Record newR = new Record ( xData , r . getY ( ) , r . getYPredicted ( ) , r . getYPredictedProbabilities ( ) ) ; _unsafe_set ( rId , newR ) ; } } ) ; }
Removes completely a list of columns from the dataset . The meta - data of the Dataframe are updated . The method internally uses threads .
37,028
public Dataframe getSubset ( FlatDataList idsCollection ) { Dataframe d = new Dataframe ( configuration ) ; for ( Object id : idsCollection ) { d . add ( get ( ( Integer ) id ) ) ; } return d ; }
It generates and returns a new Dataframe which contains a subset of this Dataframe . All the Records of the returned Dataframe are copies of the original Records . The method is used for k - fold cross validation and sampling . Note that the Records in the new Dataframe have DIFFERENT ids from the original ones .
37,029
public void recalculateMeta ( ) { data . yDataType = null ; data . xDataTypes . clear ( ) ; for ( Record r : values ( ) ) { updateMeta ( r ) ; } }
It forces the recalculation of Meta data using the Records of the dataset .
37,030
public Iterable < Map . Entry < Integer , Record > > entries ( ) { return ( ) -> new Iterator < Map . Entry < Integer , Record > > ( ) { private final Iterator < Map . Entry < Integer , Record > > it = data . records . entrySet ( ) . iterator ( ) ; public boolean hasNext ( ) { return it . hasNext ( ) ; } public Map . Entry < Integer , Record > next ( ) { return it . next ( ) ; } public void remove ( ) { throw new UnsupportedOperationException ( "This is a read-only iterator, remove operation is not supported." ) ; } } ; }
Returns a read - only Iterable on the keys and Records of the Dataframe .
37,031
public Iterable < Integer > index ( ) { return ( ) -> new Iterator < Integer > ( ) { private final Iterator < Integer > it = data . records . keySet ( ) . iterator ( ) ; public boolean hasNext ( ) { return it . hasNext ( ) ; } public Integer next ( ) { return it . next ( ) ; } public void remove ( ) { throw new UnsupportedOperationException ( "This is a read-only iterator, remove operation is not supported." ) ; } } ; }
Returns a read - only Iterable on the keys of the Dataframe .
37,032
public Iterable < Record > values ( ) { return ( ) -> new Iterator < Record > ( ) { private final Iterator < Record > it = data . records . values ( ) . iterator ( ) ; public boolean hasNext ( ) { return it . hasNext ( ) ; } public Record next ( ) { return it . next ( ) ; } public void remove ( ) { throw new UnsupportedOperationException ( "This is a read-only iterator, remove operation is not supported." ) ; } } ; }
Returns a read - only Iterable on the values of the Dataframe .
37,033
private Integer _unsafe_add ( Record r ) { Integer newId = data . atomicNextAvailableRecordId . getAndIncrement ( ) ; data . records . put ( newId , r ) ; return newId ; }
Adds the record in the dataset without updating the Meta . The add method returns the id of the new record .
37,034
private void updateMeta ( Record r ) { for ( Map . Entry < Object , Object > entry : r . getX ( ) . entrySet ( ) ) { Object column = entry . getKey ( ) ; Object value = entry . getValue ( ) ; if ( value != null ) { data . xDataTypes . putIfAbsent ( column , TypeInference . getDataType ( value ) ) ; } } if ( data . yDataType == null ) { Object value = r . getY ( ) ; if ( value != null ) { data . yDataType = TypeInference . getDataType ( r . getY ( ) ) ; } } }
Updates the meta data of the Dataframe using the provided Record . The Meta - data include the supported columns and their DataTypes .
37,035
public static AssociativeArray normalDistributionGetParams ( FlatDataCollection flatDataCollection ) { AssociativeArray params = new AssociativeArray ( ) ; params . put ( "mean" , Descriptives . mean ( flatDataCollection ) ) ; params . put ( "variance" , Descriptives . variance ( flatDataCollection , true ) ) ; return params ; }
Estimate Parameters of Normal based on Sample . This method is called via reflection .
37,036
public static < C extends Configurable > C getConfiguration ( Class < C > klass ) { String defaultPropertyFile = "datumbox." + klass . getSimpleName ( ) . toLowerCase ( Locale . ENGLISH ) + DEFAULT_POSTFIX + ".properties" ; Properties properties = new Properties ( ) ; ClassLoader cl = klass . getClassLoader ( ) ; try ( InputStream in = cl . getResourceAsStream ( defaultPropertyFile ) ) { properties . load ( in ) ; } catch ( IOException ex ) { throw new UncheckedIOException ( ex ) ; } String propertyFile = defaultPropertyFile . replaceFirst ( DEFAULT_POSTFIX , "" ) ; if ( cl . getResource ( propertyFile ) != null ) { try ( InputStream in = cl . getResourceAsStream ( propertyFile ) ) { properties . load ( in ) ; } catch ( IOException ex ) { throw new UncheckedIOException ( ex ) ; } logger . trace ( "Loading properties file {}: {}" , propertyFile , properties ) ; } else { logger . warn ( "Using default properties file {}: {}" , defaultPropertyFile , properties ) ; } return getConfiguration ( klass , properties ) ; }
Initializes the Configuration Object based on the configuration file .
37,037
public static < C extends Configurable > C getConfiguration ( Class < C > klass , Properties properties ) { C configuration ; try { Constructor < C > constructor = klass . getDeclaredConstructor ( ) ; constructor . setAccessible ( true ) ; configuration = constructor . newInstance ( ) ; } catch ( InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException ex ) { throw new RuntimeException ( ex ) ; } configuration . load ( properties ) ; return configuration ; }
Initializes the Configuration Object using a properties object .
37,038
public static double getPvalue ( TransposeDataList transposeDataList ) { Object [ ] keys = transposeDataList . keySet ( ) . toArray ( ) ; if ( keys . length != 2 ) { throw new IllegalArgumentException ( "The collection must contain observations from 2 groups." ) ; } Object keyX = keys [ 0 ] ; Object keyY = keys [ 1 ] ; FlatDataList flatDataListX = transposeDataList . get ( keyX ) ; FlatDataList flatDataListY = transposeDataList . get ( keyY ) ; int n = flatDataListX . size ( ) ; if ( n <= 0 || n != flatDataListY . size ( ) ) { throw new IllegalArgumentException ( "The number of observations in each group must be equal and larger than 0." ) ; } int Tplus = 0 ; for ( int j = 0 ; j < n ; ++ j ) { double delta = flatDataListX . getDouble ( j ) - flatDataListY . getDouble ( j ) ; if ( delta == 0 ) { continue ; } if ( delta > 0 ) { ++ Tplus ; } } double pvalue = scoreToPvalue ( Tplus , n ) ; return pvalue ; }
Estimates the p - value of the sign test for the provided data .
37,039
public static double calculateCorrelation ( TransposeDataList transposeDataList ) { Object [ ] keys = transposeDataList . keySet ( ) . toArray ( ) ; if ( keys . length != 2 ) { throw new IllegalArgumentException ( "The collection must contain observations from 2 groups." ) ; } Object keyX = keys [ 0 ] ; Object keyY = keys [ 1 ] ; FlatDataList flatDataListX = transposeDataList . get ( keyX ) . copy ( ) ; FlatDataList flatDataListY = transposeDataList . get ( keyY ) . copy ( ) ; int n = flatDataListX . size ( ) ; if ( n <= 0 || n != flatDataListY . size ( ) ) { throw new IllegalArgumentException ( "The number of observations in each group must be equal and larger than 0." ) ; } AssociativeArray tiesCounter = Ranks . getRanksFromValues ( flatDataListX ) ; double Sum_Rx_square = ( n * n - 1.0 ) * n ; for ( Object value : tiesCounter . values ( ) ) { double Ti = TypeInference . toDouble ( value ) ; Sum_Rx_square -= ( ( Ti * Ti - 1.0 ) * Ti ) ; } Sum_Rx_square /= 12.0 ; tiesCounter = Ranks . getRanksFromValues ( flatDataListY ) ; double Sum_Ry_square = ( n * n - 1.0 ) * n ; for ( Object value : tiesCounter . values ( ) ) { double Ti = TypeInference . toDouble ( value ) ; Sum_Ry_square -= ( ( Ti * Ti - 1.0 ) * Ti ) ; } Sum_Ry_square /= 12.0 ; double Sum_Di_square = 0 ; for ( int j = 0 ; j < n ; ++ j ) { double di = flatDataListX . getDouble ( j ) - flatDataListY . getDouble ( j ) ; Sum_Di_square += di * di ; } double Rs = ( Sum_Rx_square + Sum_Ry_square - Sum_Di_square ) / ( 2.0 * Math . sqrt ( Sum_Rx_square * Sum_Ry_square ) ) ; return Rs ; }
Estimates Spearman s Correlation for the provided data .
37,040
private static double scoreToPvalue ( double score , int n ) { double Zs = score * Math . sqrt ( n - 1.0 ) ; double Ts = score * Math . sqrt ( ( n - Zs ) / ( 1.0 - score * score ) ) ; return ContinuousDistributions . studentsCdf ( Ts , n - 2 ) ; }
Returns the Pvalue for a particular score .
37,041
public static P create ( String ... texts ) { P p = objectFactory . createP ( ) ; for ( String text : texts ) { R r = RunUtil . create ( text , p ) ; p . getContent ( ) . add ( r ) ; } return p ; }
Creates a new paragraph .
37,042
public Object resolveExpression ( String expressionString , Object contextRoot ) { if ( ( expressionString . startsWith ( "${" ) || expressionString . startsWith ( "#{" ) ) && expressionString . endsWith ( "}" ) ) { expressionString = expressionUtil . stripExpression ( expressionString ) ; } ExpressionParser parser = new SpelExpressionParser ( ) ; StandardEvaluationContext evaluationContext = new StandardEvaluationContext ( contextRoot ) ; evaluationContextConfigurer . configureEvaluationContext ( evaluationContext ) ; Expression expression = parser . parseExpression ( expressionString ) ; return expression . getValue ( evaluationContext ) ; }
Runs the given expression against the given context object and returns the result of the evaluated expression .
37,043
public < T > void runProcessors ( final WordprocessingMLPackage document , final ProxyBuilder < T > proxyBuilder ) { final Map < BigInteger , CommentWrapper > comments = CommentUtil . getComments ( document ) ; CoordinatesWalker walker = new BaseCoordinatesWalker ( document ) { protected void onParagraph ( ParagraphCoordinates paragraphCoordinates ) { runProcessorsOnParagraphComment ( document , comments , proxyBuilder , paragraphCoordinates ) ; runProcessorsOnInlineContent ( proxyBuilder , paragraphCoordinates ) ; } protected CommentWrapper onRun ( RunCoordinates runCoordinates , ParagraphCoordinates paragraphCoordinates ) { return runProcessorsOnRunComment ( document , comments , proxyBuilder , runCoordinates , paragraphCoordinates ) ; } } ; walker . walk ( ) ; for ( ICommentProcessor processor : commentProcessors ) { processor . commitChanges ( document ) ; } }
Lets each registered ICommentProcessor have a run on the specified docx document . At the end of the document the commit method is called for each ICommentProcessor . The ICommentProcessors are run in the order they were registered .
37,044
public ProxyBuilder < T > withInterface ( Class < ? > interfaceClass , Object interfaceImpl ) { this . interfacesToImplementations . put ( interfaceClass , interfaceImpl ) ; return this ; }
Specifies an interfaces and an implementation of an interface by which the root object shall be extended .
37,045
public T build ( ) throws ProxyException { if ( this . root == null ) { throw new IllegalArgumentException ( "root must not be null!" ) ; } if ( this . interfacesToImplementations . isEmpty ( ) ) { return this . root ; } try { ProxyMethodHandler methodHandler = new ProxyMethodHandler ( root , interfacesToImplementations ) ; ProxyFactory proxyFactory = new ProxyFactory ( ) ; proxyFactory . setSuperclass ( root . getClass ( ) ) ; proxyFactory . setInterfaces ( interfacesToImplementations . keySet ( ) . toArray ( new Class [ ] { } ) ) ; return ( T ) proxyFactory . create ( new Class [ 0 ] , new Object [ 0 ] , methodHandler ) ; } catch ( Exception e ) { throw new ProxyException ( e ) ; } }
Creates a proxy object out of the specified root object and the specified interfaces and implementations .
37,046
public static Comments . Comment getCommentAround ( R run , WordprocessingMLPackage document ) { try { if ( run instanceof Child ) { Child child = ( Child ) run ; ContentAccessor parent = ( ContentAccessor ) child . getParent ( ) ; if ( parent == null ) return null ; CommentRangeStart possibleComment = null ; boolean foundChild = false ; for ( Object contentElement : parent . getContent ( ) ) { if ( XmlUtils . unwrap ( contentElement ) instanceof CommentRangeStart ) { possibleComment = ( CommentRangeStart ) contentElement ; } else if ( possibleComment != null && child . equals ( contentElement ) ) { foundChild = true ; } else if ( possibleComment != null && foundChild && XmlUtils . unwrap ( contentElement ) instanceof CommentRangeEnd ) { try { BigInteger id = possibleComment . getId ( ) ; CommentsPart commentsPart = ( CommentsPart ) document . getParts ( ) . get ( new PartName ( "/word/comments.xml" ) ) ; Comments comments = commentsPart . getContents ( ) ; for ( Comments . Comment comment : comments . getComment ( ) ) { if ( comment . getId ( ) . equals ( id ) ) { return comment ; } } } catch ( InvalidFormatException e ) { logger . warn ( String . format ( "Error while searching comment. Skipping run %s." , run ) , e ) ; } } else { possibleComment = null ; foundChild = false ; } } } return null ; } catch ( Docx4JException e ) { throw new DocxStamperException ( "error accessing the comments of the document!" , e ) ; } }
Returns the comment the given DOCX4J run is commented with .
37,047
public static Comments . Comment getCommentFor ( ContentAccessor object , WordprocessingMLPackage document ) { try { for ( Object contentObject : object . getContent ( ) ) { if ( contentObject instanceof CommentRangeStart ) { try { BigInteger id = ( ( CommentRangeStart ) contentObject ) . getId ( ) ; CommentsPart commentsPart = ( CommentsPart ) document . getParts ( ) . get ( new PartName ( "/word/comments.xml" ) ) ; Comments comments = commentsPart . getContents ( ) ; for ( Comments . Comment comment : comments . getComment ( ) ) { if ( comment . getId ( ) . equals ( id ) ) { return comment ; } } } catch ( InvalidFormatException e ) { logger . warn ( String . format ( "Error while searching comment. Skipping object %s." , object ) , e ) ; } } } return null ; } catch ( Docx4JException e ) { throw new DocxStamperException ( "error accessing the comments of the document!" , e ) ; } }
Returns the first comment found for the given docx object . Note that an object is only considered commented if the comment STARTS within the object . Comments spanning several objects are not supported by this method .
37,048
public static String getCommentString ( Comments . Comment comment ) { StringBuilder builder = new StringBuilder ( ) ; for ( Object commentChildObject : comment . getContent ( ) ) { if ( commentChildObject instanceof P ) { builder . append ( new ParagraphWrapper ( ( P ) commentChildObject ) . getText ( ) ) ; } } return builder . toString ( ) ; }
Returns the string value of the specified comment object .
37,049
public static String getText ( R run ) { String result = "" ; for ( Object content : run . getContent ( ) ) { if ( content instanceof JAXBElement ) { JAXBElement element = ( JAXBElement ) content ; if ( element . getValue ( ) instanceof Text ) { Text textObj = ( Text ) element . getValue ( ) ; String text = textObj . getValue ( ) ; if ( ! "preserve" . equals ( textObj . getSpace ( ) ) ) { text = text . trim ( ) ; } result += text ; } else if ( element . getValue ( ) instanceof R . Tab ) { result += "\t" ; } } else if ( content instanceof Text ) { result += ( ( Text ) content ) . getValue ( ) ; } } return result ; }
Returns the text string of a run .
37,050
public static void setText ( R run , String text ) { run . getContent ( ) . clear ( ) ; Text textObj = factory . createText ( ) ; textObj . setSpace ( "preserve" ) ; textObj . setValue ( text ) ; textObj . setSpace ( "preserve" ) ; run . getContent ( ) . add ( textObj ) ; }
Sets the text of the given run to the given value .
37,051
public static R create ( String text ) { R run = factory . createR ( ) ; setText ( run , text ) ; return run ; }
Creates a new run with the specified text .
37,052
public static R create ( Object content ) { R run = factory . createR ( ) ; run . getContent ( ) . add ( content ) ; return run ; }
Creates a new run with the given object as content .
37,053
public static R create ( String text , P parentParagraph ) { R run = create ( text ) ; applyParagraphStyle ( parentParagraph , run ) ; return run ; }
Creates a new run with the specified text and inherits the style of the parent paragraph .
37,054
public DocxStamperConfiguration addCommentProcessor ( Class < ? > interfaceClass , ICommentProcessor commentProcessor ) { this . commentProcessors . put ( interfaceClass , commentProcessor ) ; return this ; }
Registers the specified ICommentProcessor as an implementation of the specified interface .
37,055
public DocxStamperConfiguration exposeInterfaceToExpressionLanguage ( Class < ? > interfaceClass , Object implementation ) { this . expressionFunctions . put ( interfaceClass , implementation ) ; return this ; }
Exposes all methods of a given interface to the expression language .
37,056
public < T > ITypeResolver getResolverForType ( Class < T > type ) { ITypeResolver resolver = typeResolversByType . get ( type ) ; if ( resolver == null ) { return defaultResolver ; } else { return resolver ; } }
Gets the ITypeResolver that was registered for the specified type .
37,057
private void addRun ( R run , int index ) { int startIndex = currentPosition ; int endIndex = currentPosition + RunUtil . getText ( run ) . length ( ) - 1 ; runs . add ( new IndexedRun ( startIndex , endIndex , index , run ) ) ; currentPosition = endIndex + 1 ; }
Adds a run to the aggregation .
37,058
public List < R > getRuns ( ) { List < R > resultList = new ArrayList < > ( ) ; for ( IndexedRun run : runs ) { resultList . add ( run . getRun ( ) ) ; } return resultList ; }
Returns the list of runs that are aggregated . Depending on what modifications were done to the aggregated text this list may not return the same runs that were initially added to the aggregator .
37,059
public boolean isTouchedByRange ( int globalStartIndex , int globalEndIndex ) { return ( ( startIndex >= globalStartIndex ) && ( startIndex <= globalEndIndex ) ) || ( ( endIndex >= globalStartIndex ) && ( endIndex <= globalEndIndex ) ) || ( ( startIndex <= globalStartIndex ) && ( endIndex >= globalEndIndex ) ) ; }
Determines whether the specified range of start and end index touches this run .
37,060
public void replace ( int globalStartIndex , int globalEndIndex , String replacement ) { int localStartIndex = globalIndexToLocalIndex ( globalStartIndex ) ; int localEndIndex = globalIndexToLocalIndex ( globalEndIndex ) ; String text = RunUtil . getText ( run ) ; text = text . substring ( 0 , localStartIndex ) ; text += replacement ; String runText = RunUtil . getText ( run ) ; if ( runText . length ( ) > 0 ) { text += RunUtil . getText ( run ) . substring ( localEndIndex + 1 ) ; } RunUtil . setText ( run , text ) ; }
Replaces the substring starting at the given index with the given replacement string .
37,061
public void resolveExpressions ( final WordprocessingMLPackage document , ProxyBuilder < T > proxyBuilder ) { try { final T expressionContext = proxyBuilder . build ( ) ; CoordinatesWalker walker = new BaseCoordinatesWalker ( document ) { protected void onParagraph ( ParagraphCoordinates paragraphCoordinates ) { resolveExpressionsForParagraph ( paragraphCoordinates . getParagraph ( ) , expressionContext , document ) ; } } ; walker . walk ( ) ; } catch ( ProxyException e ) { throw new DocxStamperException ( "could not create proxy around context root!" , e ) ; } }
Finds expressions in a document and resolves them against the specified context object . The expressions in the document are then replaced by the resolved values .
37,062
protected void onScrollChanged ( int l , int t , int oldl , int oldt ) { super . onScrollChanged ( l , t , oldl , oldt ) ; if ( mTrackedChild == null ) { if ( getChildCount ( ) > 0 ) { mTrackedChild = getChildInTheMiddle ( ) ; mTrackedChildPrevTop = mTrackedChild . getTop ( ) ; mTrackedChildPrevPosition = getPositionForView ( mTrackedChild ) ; } } else { boolean childIsSafeToTrack = mTrackedChild . getParent ( ) == this && getPositionForView ( mTrackedChild ) == mTrackedChildPrevPosition ; if ( childIsSafeToTrack ) { int top = mTrackedChild . getTop ( ) ; float deltaY = top - mTrackedChildPrevTop ; if ( deltaY == 0 ) { deltaY = OldDeltaY ; } else { OldDeltaY = deltaY ; } updateChildrenControlPoints ( deltaY ) ; mTrackedChildPrevTop = top ; } else { mTrackedChild = null ; } } }
Calculate the scroll distance comparing the distance with the top of the list of the current child and the last one tracked
37,063
public static String of ( String [ ] headers , String [ ] [ ] data ) { if ( headers == null ) throw new NullPointerException ( "headers == null" ) ; if ( headers . length == 0 ) throw new IllegalArgumentException ( "Headers must not be empty." ) ; if ( data == null ) throw new NullPointerException ( "data == null" ) ; return new FlipTable ( headers , data ) . toString ( ) ; }
Create a new table with the specified headers and row data .
37,064
public static < T > String fromIterable ( Iterable < T > rows , Class < T > rowType ) { if ( rows == null ) throw new NullPointerException ( "rows == null" ) ; if ( rowType == null ) throw new NullPointerException ( "rowType == null" ) ; Method [ ] declaredMethods = rowType . getDeclaredMethods ( ) ; Arrays . sort ( declaredMethods , METHOD_COMPARATOR ) ; List < Method > methods = new ArrayList < > ( ) ; List < String > headers = new ArrayList < > ( ) ; for ( Method declaratedMethod : declaredMethods ) { if ( declaratedMethod . getParameterTypes ( ) . length > 0 ) continue ; if ( declaratedMethod . getReturnType ( ) == void . class ) continue ; Matcher matcher = METHOD . matcher ( declaratedMethod . getName ( ) ) ; if ( ! matcher . matches ( ) ) continue ; declaratedMethod . setAccessible ( true ) ; methods . add ( declaratedMethod ) ; headers . add ( matcher . group ( 1 ) ) ; } int columnCount = methods . size ( ) ; List < String [ ] > data = new ArrayList < > ( ) ; for ( T row : rows ) { String [ ] rowData = new String [ columnCount ] ; for ( int column = 0 ; column < columnCount ; column ++ ) { try { rowData [ column ] = String . valueOf ( methods . get ( column ) . invoke ( row ) ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } data . add ( rowData ) ; } String [ ] headerArray = headers . toArray ( new String [ headers . size ( ) ] ) ; String [ ] [ ] dataArray = data . toArray ( new String [ data . size ( ) ] [ ] ) ; return FlipTable . of ( headerArray , dataArray ) ; }
Create a table from a group of objects . Public accessor methods on the class type with no arguments will be used as the columns .
37,065
public String getBaseClassName ( ) { CodeGeneratorLoggerFactory . getLogger ( ) . debug ( String . format ( "Reading base class name from data file [%s]" , fileName ) ) ; String baseClass = reader . getBaseClassName ( ) ; if ( baseClass == null ) { String path = new File ( fileName ) . getAbsolutePath ( ) ; throw new IllegalArgumentException ( "Missing base class details in Data file :" + path ) ; } return baseClass ; }
Return the base page class name from the PageYaml input
37,066
public TestPlatform platform ( ) { CodeGeneratorLoggerFactory . getLogger ( ) . debug ( String . format ( "Specified platform in data file [%s] : [%s] " , fileName , reader . getPlatform ( ) ) ) ; TestPlatform currentPlatform = reader . getPlatform ( ) ; if ( currentPlatform == null ) { String dataFile = new File ( fileName ) . getAbsolutePath ( ) ; throw new IllegalArgumentException ( "Missing or incorrect platform in Data file:" + dataFile ) ; } return currentPlatform ; }
Return the platform specified in the PageYaml input
37,067
public static void registerListener ( ListenerInfo information ) { if ( isServiceLoaderDisabled ( ) ) { return ; } logger . entering ( information ) ; listenerMap . put ( information . getListenerClassName ( ) , information ) ; }
Register your Listener using this method .
37,068
public static Map < String , String > getParameters ( HttpServletRequest request ) { Map < String , String > parameters = new HashMap < > ( ) ; Enumeration < ? > names = request . getParameterNames ( ) ; while ( names . hasMoreElements ( ) ) { String key = ( String ) names . nextElement ( ) ; String value = request . getParameter ( key ) ; if ( StringUtils . isNotEmpty ( value ) ) { parameters . put ( key , value ) ; } } return parameters ; }
Helps retrieve the parameters and its values as a Map
37,069
static String saveGetLocation ( WebDriver driver ) { logger . entering ( driver ) ; String location = "n/a" ; try { if ( driver != null ) { location = driver . getCurrentUrl ( ) ; } } catch ( Exception exception ) { logger . log ( Level . FINER , "Current location couldn't be retrieved by getCurrentUrl(). This can be SAFELY " + "IGNORED if testing a non-web mobile application. Reason: " , exception ) ; } logger . exiting ( location ) ; return location ; }
getCurrentURL will throw Exception
37,070
public String returnArg ( String key ) { SeLionElement element = HtmlSeLionElementSet . getInstance ( ) . findMatch ( key ) ; if ( element == null ) { return key ; } if ( ! element . isUIElement ( ) ) { return key ; } return key . substring ( 0 , key . indexOf ( element . getElementClass ( ) ) ) ; }
DO NOT tamper with this method
37,071
public static List < GUIObjectDetails > transformKeys ( List < String > keys , TestPlatform platform ) { List < GUIObjectDetails > htmlObjectDetailsList = null ; switch ( platform ) { case WEB : htmlObjectDetailsList = HtmlSeLionElementSet . getInstance ( ) . getGUIObjectList ( keys ) ; break ; case IOS : htmlObjectDetailsList = IOSSeLionElementSet . getInstance ( ) . getGUIObjectList ( keys ) ; break ; case ANDROID : htmlObjectDetailsList = AndroidSeLionElementSet . getInstance ( ) . getGUIObjectList ( keys ) ; break ; case MOBILE : htmlObjectDetailsList = MobileSeLionElementSet . getInstance ( ) . getGUIObjectList ( keys ) ; break ; } return htmlObjectDetailsList ; }
This method convert each key in the data sheet into corresponding HtmlObjectDetails object and returns list of HtmlObjectDetails
37,072
public void type ( String value ) { getDispatcher ( ) . beforeType ( this , value ) ; RemoteWebElement element = getElement ( ) ; element . clear ( ) ; element . sendKeys ( value ) ; if ( Config . getBoolConfigProperty ( ConfigProperty . ENABLE_GUI_LOGGING ) ) { logUIActions ( UIActions . ENTERED , value ) ; } getDispatcher ( ) . afterType ( this , value ) ; }
The TextField type function
37,073
public void type ( String value , boolean isKeepExistingText ) { if ( isKeepExistingText ) { getDispatcher ( ) . beforeType ( this , value ) ; getElement ( ) . sendKeys ( value ) ; if ( Config . getBoolConfigProperty ( ConfigProperty . ENABLE_GUI_LOGGING ) ) { logUIActions ( UIActions . ENTERED , value ) ; } getDispatcher ( ) . afterType ( this , value ) ; } else { type ( value ) ; } }
The TextField type function which allow users to keep the TextField and append the input text to it .
37,074
public void clear ( ) { getElement ( ) . clear ( ) ; if ( Config . getBoolConfigProperty ( ConfigProperty . ENABLE_GUI_LOGGING ) ) { logUIAction ( UIActions . CLEARED ) ; } }
Text TextField clear function
37,075
public String getText ( ) { String text = getElement ( ) . getText ( ) ; if ( text . isEmpty ( ) ) { text = getValue ( ) ; } return text ; }
Get the text value from a TextField object .
37,076
public void uploadFile ( String filePath ) { SeLionLogger . getLogger ( ) . entering ( filePath ) ; Preconditions . checkArgument ( StringUtils . isNotBlank ( filePath ) , "Please provide a valid file path to work with." ) ; String filePathToUse = new File ( filePath ) . getAbsolutePath ( ) ; LocalFileDetector detector = new LocalFileDetector ( ) ; RemoteWebElement element = getElement ( ) ; element . setFileDetector ( detector ) ; element . sendKeys ( filePathToUse ) ; SeLionLogger . getLogger ( ) . exiting ( ) ; }
A Utility method that helps with uploading a File to a Web Application .
37,077
public void check ( ) { getDispatcher ( ) . beforeCheck ( this ) ; RemoteWebElement e = ( RemoteWebElement ) getElement ( ) ; while ( ! e . isSelected ( ) ) { e . click ( ) ; } if ( Config . getBoolConfigProperty ( ConfigProperty . ENABLE_GUI_LOGGING ) ) { logUIAction ( UIActions . CHECKED ) ; } getDispatcher ( ) . afterCheck ( this ) ; }
The CheckBox check function It invokes selenium session to handle the check action against the element .
37,078
public void check ( String locator ) { getDispatcher ( ) . beforeCheck ( this , locator ) ; this . check ( ) ; validatePresenceOfAlert ( ) ; WebDriverWaitUtils . waitUntilElementIsPresent ( locator ) ; getDispatcher ( ) . afterUncheck ( this , locator ) ; }
The CheckBox check function It invokes selenium session to handle the check action against the element . Waits until element is found with given locator .
37,079
public void uncheck ( ) { getDispatcher ( ) . beforeUncheck ( this ) ; RemoteWebElement e = ( RemoteWebElement ) getElement ( ) ; while ( e . isSelected ( ) ) { e . click ( ) ; } if ( Config . getBoolConfigProperty ( ConfigProperty . ENABLE_GUI_LOGGING ) ) { logUIAction ( UIActions . UNCHECKED ) ; } getDispatcher ( ) . afterUncheck ( this ) ; }
The CheckBox uncheck function It invokes SeLion session to handle the uncheck action against the element .
37,080
public void uncheck ( String locator ) { getDispatcher ( ) . beforeUncheck ( this , locator ) ; this . uncheck ( ) ; validatePresenceOfAlert ( ) ; WebDriverWaitUtils . waitUntilElementIsPresent ( locator ) ; getDispatcher ( ) . afterUncheck ( this , locator ) ; }
The CheckBox uncheck function It invokes SeLion session to handle the uncheck action against the element . Waits until element is found with given locator .
37,081
public void click ( ) { getDispatcher ( ) . beforeClick ( this ) ; getElement ( ) . click ( ) ; if ( Config . getBoolConfigProperty ( ConfigProperty . ENABLE_GUI_LOGGING ) ) { logUIAction ( UIActions . CLICKED ) ; } getDispatcher ( ) . afterClick ( this ) ; }
The CheckBox click function and wait for page to load
37,082
public void click ( String locator ) { getDispatcher ( ) . beforeClick ( this , locator ) ; click ( ) ; validatePresenceOfAlert ( ) ; WebDriverWaitUtils . waitUntilElementIsPresent ( locator ) ; getDispatcher ( ) . afterClick ( this , locator ) ; }
The CheckBox click function and wait for object to load
37,083
public ManagedArtifact getArtifact ( String pathInfo ) { LOGGER . entering ( ) ; ManagedArtifact managedArtifact = serverRepository . getArtifact ( pathInfo ) ; LOGGER . exiting ( managedArtifact ) ; return managedArtifact ; }
Returns the managed artifact requested in the HTTP call .
37,084
static void cleanup ( ) { LOGGER . entering ( ) ; for ( String temp : files ) { new File ( temp ) . delete ( ) ; } files . clear ( ) ; LOGGER . exiting ( ) ; }
Cleanup all the files already downloaded within the same JVM process . Automatically called internally .
37,085
static void checkForDownloads ( List < String > artifactNames , boolean checkTimeStamp , boolean cleanup ) { LOGGER . entering ( ) ; if ( checkTimeStamp && ( lastModifiedTime == DOWNLOAD_FILE . lastModified ( ) ) ) { return ; } lastModifiedTime = DOWNLOAD_FILE . lastModified ( ) ; if ( cleanup ) { cleanup ( ) ; } List < URLChecksumEntity > artifactDetails = new ArrayList < ArtifactDetails . URLChecksumEntity > ( ) ; try { artifactDetails = ArtifactDetails . getArtifactDetailsForCurrentPlatformByNames ( DOWNLOAD_FILE , artifactNames ) ; } catch ( IOException e ) { LOGGER . log ( Level . SEVERE , "Unable to open download.json file" , e ) ; throw new RuntimeException ( e ) ; } downloadAndExtractArtifacts ( artifactDetails ) ; LOGGER . exiting ( ) ; }
Check download . json and download files based on artifact names
37,086
static String downloadFile ( String artifactUrl , String checksum ) { LOGGER . entering ( new Object [ ] { artifactUrl , checksum } ) ; Preconditions . checkArgument ( StringUtils . isNotBlank ( artifactUrl ) , "Invalid URL: Cannot be null or empty" ) ; Preconditions . checkArgument ( StringUtils . isNotBlank ( checksum ) , "Invalid CheckSum: Cannot be null or empty" ) ; isValidFileType ( artifactUrl ) ; String algorithm = null ; if ( isValidSHA1 ( checksum ) ) { algorithm = "SHA1" ; } else if ( isValidMD5 ( checksum ) ) { algorithm = "MD5" ; } String result = downloadFile ( artifactUrl , checksum , algorithm ) ; LOGGER . exiting ( result ) ; return result ; }
Download a file from the specified url
37,087
public void insertCode ( ) throws IOException , ParseException { CompilationUnit cuResult = JavaParser . parse ( baseFile ) ; if ( cuResult . getImports ( ) != null ) { List < ImportDeclaration > importsFromBaseFile = cuResult . getImports ( ) ; for ( ImportDeclaration eachImport : importsFromExtendedFile ) { if ( ! importAlreadyPresent ( importsFromBaseFile , eachImport ) ) { importsFromBaseFile . add ( eachImport ) ; } } cuResult . setImports ( importsFromBaseFile ) ; } String code = cuResult . toString ( ) ; BufferedWriter b = new BufferedWriter ( new FileWriter ( baseFile ) ) ; b . write ( code ) ; b . close ( ) ; }
This method will add methods fields and import statement to existing java file
37,088
public boolean add ( SeLionElement element ) { if ( initialized ) { CodeGeneratorLogger logger = CodeGeneratorLoggerFactory . getLogger ( ) ; if ( isExactMatch ( element . getElementClass ( ) ) ) { logger . info ( "Registering the element " + element + " which is now overwriting a pre-existing element." ) ; } else { logger . info ( "Registering the element " + element + " as a valid element." ) ; } SeLionElementSet elementSet = ( SeLionElementSet ) clone ( ) ; clear ( ) ; super . add ( element ) ; elementSet . stream ( ) . forEachOrdered ( a -> super . add ( a ) ) ; return true ; } return super . add ( element ) ; }
Add an element to the list
37,089
public void generateReport ( List < XmlSuite > xmlSuites , List < ISuite > suites , String sOpDirectory ) { logger . entering ( new Object [ ] { xmlSuites , suites , sOpDirectory } ) ; if ( ListenerManager . isCurrentMethodSkipped ( this ) ) { logger . exiting ( ListenerManager . THREAD_EXCLUSION_MSG ) ; return ; } if ( logger . isLoggable ( Level . INFO ) ) { logger . log ( Level . INFO , "Generating ExcelReport" ) ; } TestCaseResult . setOutputDirectory ( sOpDirectory ) ; this . generateSummaryData ( suites ) ; this . generateTCBasedData ( allTestsResults ) ; this . createExcelReport ( ) ; Path p = Paths . get ( sOpDirectory , reportFileName ) ; try { Path opDirectory = Paths . get ( sOpDirectory ) ; if ( ! Files . exists ( opDirectory ) ) { Files . createDirectories ( Paths . get ( sOpDirectory ) ) ; } FileOutputStream fOut = new FileOutputStream ( p . toFile ( ) ) ; wb . write ( fOut ) ; fOut . flush ( ) ; } catch ( IOException e ) { logger . log ( Level . SEVERE , e . getMessage ( ) , e ) ; } if ( logger . isLoggable ( Level . INFO ) ) { logger . log ( Level . INFO , "Excel File Created @ " + p . toAbsolutePath ( ) . toString ( ) ) ; } }
The first method that gets called when generating the report . Generates data in way the Excel should appear . Creates the Excel Report and writes it to a file .
37,090
public void setExcelFileName ( String fileName ) { Preconditions . checkArgument ( StringUtils . endsWith ( fileName , ".xls" ) , "Excel file name must end with '.xls'." ) ; reportFileName = fileName ; }
Sets the output file name for the Excel Report . The file should have xls extension .
37,091
@ SuppressWarnings ( "rawtypes" ) private void createExcelReport ( ) { logger . entering ( ) ; wb = new HSSFWorkbook ( ) ; Styles . initStyles ( wb ) ; this . createReportInfo ( ) ; this . createReportMap ( ) ; for ( ReportMap rm : fullReportMap ) { List < BaseReport < ? > > allReports = rm . getGeneratedReport ( ) ; allReports . iterator ( ) . next ( ) . generateRep ( this . wb , rm . getName ( ) , rm . getGeneratedReport ( ) ) ; } logger . exiting ( ) ; }
Initialized styles used in the workbook . Generates the report related info . Creates the structure of the Excel Reports
37,092
private void createReportInfo ( ) { logger . entering ( ) ; HSSFSheet summarySheet = wb . createSheet ( ReportSheetNames . TESTSUMMARYREPORT . getName ( ) ) ; Map < String , String > reportInfo = new LinkedHashMap < String , String > ( ) ; for ( Entry < String , String > temp : ConfigSummaryData . getConfigSummary ( ) . entrySet ( ) ) { reportInfo . put ( temp . getKey ( ) , temp . getValue ( ) ) ; } int rowNum = 0 ; HSSFCell col ; HSSFRow row ; for ( Entry < String , String > eachReportInfo : reportInfo . entrySet ( ) ) { int colNum = 2 ; row = summarySheet . createRow ( rowNum ++ ) ; col = row . createCell ( colNum ) ; col . setCellStyle ( Styles . getSubHeading2Style ( ) ) ; col . setCellValue ( eachReportInfo . getKey ( ) ) ; col = row . createCell ( ++ colNum ) ; col . setCellStyle ( Styles . getThinBorderStyle ( ) ) ; col . setCellValue ( eachReportInfo . getValue ( ) ) ; } logger . exiting ( ) ; }
Create Run details like owner of run time and stage used .
37,093
private void generateSummaryData ( List < ISuite > suites ) { logger . entering ( suites ) ; SummarizedData tempSuite ; SummarizedData tempTest ; SummarizedData tempGroups ; this . generateTestCaseResultData ( suites ) ; for ( ISuite suite : suites ) { tempSuite = new SummarizedData ( ) ; tempSuite . setsName ( suite . getName ( ) ) ; Map < String , ISuiteResult > allResults = suite . getResults ( ) ; for ( Entry < String , Collection < ITestNGMethod > > sGroupName : suite . getMethodsByGroups ( ) . entrySet ( ) ) { tempGroups = new SummarizedData ( ) ; tempGroups . setsName ( sGroupName . getKey ( ) ) ; tempGroups . incrementiTotal ( sGroupName . getValue ( ) . size ( ) ) ; for ( TestCaseResult tr : allTestsResults ) { if ( tr . getGroup ( ) . contains ( sGroupName . getKey ( ) ) ) { tempGroups . incrementCount ( tr . getStatus ( ) ) ; tempGroups . incrementDuration ( tr . getDurationTaken ( ) ) ; } } tempGroups . setiTotal ( tempGroups . getiPassedCount ( ) + tempGroups . getiFailedCount ( ) + tempGroups . getiSkippedCount ( ) ) ; lGroups . add ( tempGroups ) ; } for ( ISuiteResult testResult : allResults . values ( ) ) { ITestContext testContext = testResult . getTestContext ( ) ; tempTest = new SummarizedData ( ) ; tempTest . setsName ( testContext . getName ( ) ) ; tempTest . setiFailedCount ( testContext . getFailedTests ( ) . size ( ) ) ; tempTest . setiPassedCount ( testContext . getPassedTests ( ) . size ( ) ) ; tempTest . setiSkippedCount ( testContext . getSkippedTests ( ) . size ( ) ) ; tempTest . setiTotal ( tempTest . getiPassedCount ( ) + tempTest . getiFailedCount ( ) + tempTest . getiSkippedCount ( ) ) ; tempTest . setlRuntime ( testContext . getEndDate ( ) . getTime ( ) - testContext . getStartDate ( ) . getTime ( ) ) ; lTests . add ( tempTest ) ; } for ( SummarizedData test : lTests ) { tempSuite . setiPassedCount ( test . getiPassedCount ( ) + tempSuite . getiPassedCount ( ) ) ; tempSuite . setiFailedCount ( test . getiFailedCount ( ) + tempSuite . getiFailedCount ( ) ) ; tempSuite . setiSkippedCount ( tempSuite . getiSkippedCount ( ) + test . getiSkippedCount ( ) ) ; tempSuite . setiTotal ( tempSuite . getiPassedCount ( ) + tempSuite . getiFailedCount ( ) + tempSuite . getiSkippedCount ( ) ) ; tempSuite . setlRuntime ( test . getlRuntime ( ) + tempSuite . getlRuntime ( ) ) ; } lSuites . add ( tempSuite ) ; } Collections . sort ( lGroups ) ; Collections . sort ( lTests ) ; logger . exiting ( ) ; }
Generates all summarized counts for various reports
37,094
private List < TestCaseResult > createResultFromMap ( IResultMap resultMap ) { logger . entering ( resultMap ) ; List < TestCaseResult > statusWiseResults = new ArrayList < TestCaseResult > ( ) ; for ( ITestResult singleMethodResult : resultMap . getAllResults ( ) ) { TestCaseResult tcresult1 = new TestCaseResult ( ) ; tcresult1 . setITestResultobj ( singleMethodResult ) ; statusWiseResults . add ( tcresult1 ) ; } Collections . sort ( statusWiseResults ) ; logger . exiting ( statusWiseResults ) ; return statusWiseResults ; }
Generates individual TestCase Results based on map of passed failed and skipped methods Returns the list of TestCaseResult objects generated .
37,095
private void showAssertInfo ( IAssert < ? > assertCommand , AssertionError ex , boolean failedTest ) { ITestResult testResult = Reporter . getCurrentTestResult ( ) ; String methodName = "main" ; if ( testResult != null ) { methodName = testResult . getMethod ( ) . getMethodName ( ) ; } StringBuilder sb = new StringBuilder ( ) ; sb . append ( "Soft Assert " ) ; if ( assertCommand . getMessage ( ) != null && ! assertCommand . getMessage ( ) . trim ( ) . isEmpty ( ) ) { sb . append ( "[" ) . append ( assertCommand . getMessage ( ) ) . append ( "] " ) ; } if ( failedTest ) { sb . append ( "failed in " ) ; } else { sb . append ( "passed in " ) ; } sb . append ( methodName ) . append ( "()\n" ) ; if ( failedTest ) { sb . append ( ExceptionUtils . getStackTrace ( ex ) ) ; } Reporter . log ( sb . toString ( ) , true ) ; }
Shows a message in Reporter based on the assert result and also includes the stacktrace for failed assert .
37,096
public RemoteWebDriver createDriver ( WebDriverPlatform platform , CommandExecutor commandExecutor , URL url , Capabilities caps ) { if ( platform . equals ( WebDriverPlatform . ANDROID ) ) { if ( commandExecutor == null ) { return new SeLionAppiumAndroidDriver ( url , caps ) ; } else { return new SeLionAppiumAndroidDriver ( commandExecutor , caps , url ) ; } } else if ( platform . equals ( WebDriverPlatform . IOS ) ) { if ( commandExecutor == null ) { return new SeLionAppiumIOSDriver ( url , caps ) ; } else { return new SeLionAppiumIOSDriver ( commandExecutor , caps , url ) ; } } logger . log ( Level . SEVERE , "Error creating instance of Appium RemoteWebDriver for " + platform ) ; return null ; }
create an instance of SeLionAppiumIOSDriver or SeLionAppiumAndroidDriver
37,097
static void copyFileFromResources ( String sourcePath , String destPath ) throws IOException { LOGGER . entering ( new Object [ ] { sourcePath , destPath } ) ; File downloadFile = new File ( destPath ) ; if ( ! downloadFile . exists ( ) ) { InputStream stream = JarSpawner . class . getResourceAsStream ( sourcePath ) ; FileUtils . copyInputStreamToFile ( stream , downloadFile ) ; LOGGER . fine ( "File copied to " + destPath ) ; } LOGGER . exiting ( ) ; }
Copy file from source path to destination location
37,098
public String getDateText ( ) { String value = null ; value = HtmlElementUtils . locateElement ( dateTextLocator ) . getText ( ) ; return value ; }
Gets the current setting month and year from the calendar header .
37,099
public void setDate ( Calendar to ) { navigateMonth ( calendar , to ) ; clickDay ( to . get ( Calendar . DATE ) ) ; Calendar cal = calendar ; cal . set ( Calendar . YEAR , to . get ( Calendar . YEAR ) ) ; cal . set ( Calendar . MONTH , to . get ( Calendar . MONTH ) ) ; cal . set ( Calendar . DATE , to . get ( Calendar . DATE ) ) ; }
This is the main function of the DatePicker object to select the date specified by the input parameter . It will calculate how many time needed to click on the next month or previous month button to arrive at the correct month and year in the input parameters . It then click on the day - of - month tablet to select the correct day - of - month as specified in the input param .