idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
19,600 | public ProxyConfiguration < T > setProxyName ( final Package pkg , final String simpleName ) { this . proxyName = pkg . getName ( ) + ' ' + simpleName ; return this ; } | Sets the proxy name | 44 | 5 |
19,601 | public static Class < ? > loadJavaType ( String typeName , ClassLoader classLoader ) throws ClassNotFoundException { if ( classLoader == null ) classLoader = getContextClassLoader ( ) ; Class < ? > javaType = primitiveNames . get ( typeName ) ; if ( javaType == null ) javaType = getArray ( typeName , classLoader ) ; if ( javaType == null ) javaType = classLoader . loadClass ( typeName ) ; return javaType ; } | Load a Java type from a given class loader . | 103 | 10 |
19,602 | public static boolean isPrimitive ( Class < ? > javaType ) { return javaType . isPrimitive ( ) || ( javaType . isArray ( ) && isPrimitive ( javaType . getComponentType ( ) ) ) ; } | True if the given class is a primitive or array of which . | 50 | 13 |
19,603 | public static String getJustClassName ( Class < ? > cls ) { if ( cls == null ) return null ; if ( cls . isArray ( ) ) { Class < ? > c = cls . getComponentType ( ) ; return getJustClassName ( c . getName ( ) ) ; } return getJustClassName ( cls . getName ( ) ) ; } | Given a class strip out the package name | 83 | 8 |
19,604 | public static String getJustClassName ( String classname ) { int index = classname . lastIndexOf ( ' ' ) ; if ( index < 0 ) index = 0 ; else index = index + 1 ; return classname . substring ( index ) ; } | Given a FQN of a class strip out the package name | 55 | 13 |
19,605 | public static Class < ? > getPrimitiveType ( Class < ? > javaType ) { if ( javaType == Integer . class ) return int . class ; if ( javaType == Short . class ) return short . class ; if ( javaType == Boolean . class ) return boolean . class ; if ( javaType == Byte . class ) return byte . class ; if ( javaType == Long . class ) return long . class ; if ( javaType == Double . class ) return double . class ; if ( javaType == Float . class ) return float . class ; if ( javaType == Character . class ) return char . class ; if ( javaType == Integer [ ] . class ) return int [ ] . class ; if ( javaType == Short [ ] . class ) return short [ ] . class ; if ( javaType == Boolean [ ] . class ) return boolean [ ] . class ; if ( javaType == Byte [ ] . class ) return byte [ ] . class ; if ( javaType == Long [ ] . class ) return long [ ] . class ; if ( javaType == Double [ ] . class ) return double [ ] . class ; if ( javaType == Float [ ] . class ) return float [ ] . class ; if ( javaType == Character [ ] . class ) return char [ ] . class ; if ( javaType . isArray ( ) && javaType . getComponentType ( ) . isArray ( ) ) { Class < ? > compType = getPrimitiveType ( javaType . getComponentType ( ) ) ; return Array . newInstance ( compType , 0 ) . getClass ( ) ; } return javaType ; } | Get the corresponding primitive for a give wrapper type . Also handles arrays of which . | 345 | 16 |
19,606 | public static Object getPrimitiveValueArray ( Object value ) { if ( value == null ) return null ; Class < ? > javaType = value . getClass ( ) ; if ( javaType . isArray ( ) ) { int length = Array . getLength ( value ) ; Object destArr = Array . newInstance ( getPrimitiveType ( javaType . getComponentType ( ) ) , length ) ; for ( int i = 0 ; i < length ; i ++ ) { Object srcObj = Array . get ( value , i ) ; Array . set ( destArr , i , getPrimitiveValueArray ( srcObj ) ) ; } return destArr ; } return value ; } | Converts an n - dimensional array of wrapper types to primitive types | 146 | 13 |
19,607 | public static boolean isAssignableFrom ( Class < ? > dest , Class < ? > src ) { if ( dest == null || src == null ) throw MESSAGES . cannotCheckClassIsAssignableFrom ( dest , src ) ; boolean isAssignable = dest . isAssignableFrom ( src ) ; if ( isAssignable == false && dest . getName ( ) . equals ( src . getName ( ) ) ) { ClassLoader destLoader = dest . getClassLoader ( ) ; ClassLoader srcLoader = src . getClassLoader ( ) ; if ( ROOT_LOGGER . isTraceEnabled ( ) ) ROOT_LOGGER . notAssignableDueToConflictingClassLoaders ( dest , src , destLoader , srcLoader ) ; } if ( isAssignable == false && isPrimitive ( dest ) ) { dest = getWrapperType ( dest ) ; isAssignable = dest . isAssignableFrom ( src ) ; } if ( isAssignable == false && isPrimitive ( src ) ) { src = getWrapperType ( src ) ; isAssignable = dest . isAssignableFrom ( src ) ; } return isAssignable ; } | Return true if the dest class is assignable from the src . Also handles arrays and primitives . | 263 | 20 |
19,608 | public static Class < ? > erasure ( Type type ) { if ( type instanceof ParameterizedType ) { return erasure ( ( ( ParameterizedType ) type ) . getRawType ( ) ) ; } if ( type instanceof TypeVariable < ? > ) { return erasure ( ( ( TypeVariable < ? > ) type ) . getBounds ( ) [ 0 ] ) ; } if ( type instanceof WildcardType ) { return erasure ( ( ( WildcardType ) type ) . getUpperBounds ( ) [ 0 ] ) ; } if ( type instanceof GenericArrayType ) { return Array . newInstance ( erasure ( ( ( GenericArrayType ) type ) . getGenericComponentType ( ) ) , 0 ) . getClass ( ) ; } // Only type left is class return ( Class < ? > ) type ; } | Erases a type according to the JLS type erasure rules | 181 | 13 |
19,609 | public static boolean isJBossRepositoryClassLoader ( ClassLoader loader ) { Class < ? > clazz = loader . getClass ( ) ; while ( ! clazz . getName ( ) . startsWith ( "java" ) ) { if ( "org.jboss.mx.loading.RepositoryClassLoader" . equals ( clazz . getName ( ) ) ) return true ; clazz = clazz . getSuperclass ( ) ; } return false ; } | Tests if this class loader is a JBoss RepositoryClassLoader | 99 | 14 |
19,610 | public static void clearBlacklists ( ClassLoader loader ) { if ( isJBossRepositoryClassLoader ( loader ) ) { for ( Method m : loader . getClass ( ) . getMethods ( ) ) { if ( "clearBlackLists" . equalsIgnoreCase ( m . getName ( ) ) ) { try { m . invoke ( loader ) ; } catch ( Exception e ) { if ( ROOT_LOGGER . isTraceEnabled ( ) ) ROOT_LOGGER . couldNotClearBlacklist ( loader , e ) ; } } } } } | Clears black lists on a JBoss RepositoryClassLoader . This is somewhat of a hack and could be replaced with an integration module . This is needed when the following order of events occur . | 120 | 39 |
19,611 | private static String getName ( final String resourceName , final String fallBackName ) { return resourceName . length ( ) > 0 ? resourceName : fallBackName ; } | Returns JNDI resource name . | 36 | 7 |
19,612 | private static String convertToBeanName ( final String methodName ) { return Character . toLowerCase ( methodName . charAt ( 3 ) ) + methodName . substring ( 4 ) ; } | Translates setBeanName to beanName string . | 42 | 12 |
19,613 | protected final Method getImplMethod ( final Class < ? > implClass , final Method seiMethod ) throws NoSuchMethodException { final String methodName = seiMethod . getName ( ) ; final Class < ? > [ ] paramTypes = seiMethod . getParameterTypes ( ) ; return implClass . getMethod ( methodName , paramTypes ) ; } | Returns implementation method that will be used for invocation . | 76 | 10 |
19,614 | @ SuppressWarnings ( "rawtypes" ) public void setupConfigHandlers ( Binding binding , CommonConfig config ) { if ( config != null ) { //start with the use handlers only to remove the previously set configuration List < Handler > userHandlers = getNonConfigHandlers ( binding . getHandlerChain ( ) ) ; List < Handler > handlers = convertToHandlers ( config . getPreHandlerChains ( ) , binding . getBindingID ( ) , true ) ; //PRE handlers . addAll ( userHandlers ) ; //ENDPOINT handlers . addAll ( convertToHandlers ( config . getPostHandlerChains ( ) , binding . getBindingID ( ) , false ) ) ; //POST binding . setHandlerChain ( handlers ) ; } } | Setups a given Binding instance using a specified CommonConfig | 166 | 11 |
19,615 | public T newInstance ( InvocationHandler handler ) throws InstantiationException , IllegalAccessException { T ret = newInstance ( ) ; setInvocationHandler ( ret , handler ) ; return ret ; } | Create a new proxy initialising it with the given invocation handler . | 41 | 13 |
19,616 | public void setInvocationHandler ( Object proxy , InvocationHandler handler ) { Field field = getInvocationHandlerField ( ) ; try { field . set ( proxy , handler ) ; } catch ( IllegalArgumentException e ) { throw new RuntimeException ( e ) ; } catch ( IllegalAccessException e ) { throw new RuntimeException ( e ) ; } } | Sets the invocation handler for a proxy created from this factory . | 75 | 13 |
19,617 | public InvocationHandler getInvocationHandler ( Object proxy ) { Field field = getInvocationHandlerField ( ) ; try { return ( InvocationHandler ) field . get ( proxy ) ; } catch ( IllegalArgumentException e ) { throw new RuntimeException ( "Object is not a proxy of correct type" , e ) ; } catch ( IllegalAccessException e ) { throw new RuntimeException ( e ) ; } } | Returns the invocation handler for a proxy created from this factory . | 87 | 12 |
19,618 | public boolean isProxyClassDefined ( ClassLoader classLoader ) { try { // first check that the proxy has not already been created classLoader . loadClass ( this . className ) ; return true ; } catch ( ClassNotFoundException e ) { return false ; } } | Checks if the proxy class has been defined in the given class loader | 57 | 14 |
19,619 | protected String getImplicitContextRoot ( ArchiveDeployment dep ) { String simpleName = dep . getSimpleName ( ) ; String contextRoot = simpleName . substring ( 0 , simpleName . length ( ) - 4 ) ; return contextRoot ; } | Use the implicit context root derived from the deployment name | 53 | 10 |
19,620 | public static void copyReader ( OutputStream outs , Reader reader ) throws IOException { try { OutputStreamWriter writer = new OutputStreamWriter ( outs , StandardCharsets . UTF_8 ) ; char [ ] bytes = new char [ 1024 ] ; int r = reader . read ( bytes ) ; while ( r > 0 ) { writer . write ( bytes , 0 , r ) ; r = reader . read ( bytes ) ; } } catch ( IOException e ) { throw e ; } finally { reader . close ( ) ; } } | Copy the reader to the output stream | 112 | 7 |
19,621 | public Object invoke ( final Object proxy , final Method method , final Object [ ] args ) throws Throwable { InterceptorContext context = new InterceptorContext ( ) ; context . setParameters ( args ) ; context . setMethod ( method ) ; return interceptor . processInvocation ( context ) ; } | Handle a proxy method invocation . | 62 | 6 |
19,622 | public static byte [ ] generateRandomUUIDBytes ( ) { if ( rand == null ) rand = new SecureRandom ( ) ; byte [ ] buffer = new byte [ 16 ] ; rand . nextBytes ( buffer ) ; // Set version to 3 (Random) buffer [ 6 ] = ( byte ) ( ( buffer [ 6 ] & 0x0f ) | 0x40 ) ; // Set variant to 2 (IETF) buffer [ 8 ] = ( byte ) ( ( buffer [ 8 ] & 0x3f ) | 0x80 ) ; return buffer ; } | Generates a pseudo random UUID and returns it in byte array form . | 119 | 15 |
19,623 | public static String convertToString ( byte [ ] uuid ) { if ( uuid . length != 16 ) throw Messages . MESSAGES . uuidMustBeOf16Bytes ( ) ; String string = bytesToHex ( uuid , 0 , 4 ) + "-" + bytesToHex ( uuid , 4 , 2 ) + "-" + bytesToHex ( uuid , 6 , 2 ) + "-" + bytesToHex ( uuid , 8 , 2 ) + "-" + bytesToHex ( uuid , 10 , 6 ) ; return string ; } | Converts a UUID in byte array form to the IETF string format . | 125 | 16 |
19,624 | @ Override public void afterClassLoad ( Class < ? > clazz ) { super . afterClassLoad ( clazz ) ; //force <clinit> to be run, while the correct ThreadLocal is set //if we do not run this then <clinit> may be run later, perhaps even in //another thread try { Class . forName ( clazz . getName ( ) , true , clazz . getClassLoader ( ) ) ; } catch ( ClassNotFoundException e ) { throw new RuntimeException ( e ) ; } } | Sets the accessible flag on the cached methods | 114 | 9 |
19,625 | static boolean isEscaped ( final String characters , final int position ) { int p = position ; int nbBackslash = 0 ; while ( p > 0 && characters . charAt ( -- p ) == ' ' ) { nbBackslash ++ ; } return ( nbBackslash % 2 == 1 ) ; } | Indicates if the character at the given position is escaped or not . | 70 | 14 |
19,626 | private Object wrappedAction ( final Context cx , final Scriptable scope , final Scriptable thisObj , final Object [ ] args , final int actionType ) { // take care to set the context's RegExp proxy to the original one as // this is checked // (cf net.sourceforge.htmlunit.corejs.javascript.regexp.RegExpImp:334) try { ScriptRuntime . setRegExpProxy ( cx , wrapped_ ) ; return wrapped_ . action ( cx , scope , thisObj , args , actionType ) ; } finally { ScriptRuntime . setRegExpProxy ( cx , this ) ; } } | Calls action on the wrapped RegExp proxy . | 131 | 10 |
19,627 | static String jsRegExpToJavaRegExp ( String re ) { re = re . replaceAll ( "\\[\\^\\\\\\d\\]" , "." ) ; re = re . replaceAll ( "\\[([^\\]]*)\\\\b([^\\]]*)\\]" , "[$1\\\\cH$2]" ) ; // [...\b...] // -> // [...\cH...] re = re . replaceAll ( "(?<!\\\\)\\[([^((?<!\\\\)\\[)\\]]*)\\[" , "[$1\\\\[" ) ; // [...[...] // -> // [...\[...] // back reference in character classes are simply ignored by browsers re = re . replaceAll ( "(?<!\\\\)\\[([^\\]]*)(?<!\\\\)\\\\\\d" , "[$1" ) ; // [...ab\5cd...] // -> // [...abcd...] // characters escaped without need should be "un-escaped" re = re . replaceAll ( "(?<!\\\\)\\\\([ACE-RT-VX-Zaeg-mpqyz])" , "$1" ) ; re = escapeJSCurly ( re ) ; return re ; } | Transform a JavaScript regular expression to a Java regular expression | 268 | 10 |
19,628 | private void consumeInputFully ( HttpServletRequest req ) { try { ServletInputStream is = req . getInputStream ( ) ; while ( ! is . isFinished ( ) && is . read ( ) != - 1 ) { } } catch ( IOException e ) { log . info ( "Could not consume full client request" , e ) ; } } | connection - see SOLR - 8453 and SOLR - 8683 | 79 | 14 |
19,629 | public void toSAX ( ContentHandler contentHandler ) throws SAXException { for ( SaxBit saxbit : this . saxbits ) { saxbit . send ( contentHandler ) ; } } | Stream this buffer into the provided content handler . If contentHandler object implements LexicalHandler it will get lexical events as well . | 40 | 26 |
19,630 | public void dump ( Writer writer ) throws IOException { Iterator < SaxBit > i = this . saxbits . iterator ( ) ; while ( i . hasNext ( ) ) { final SaxBit saxbit = i . next ( ) ; saxbit . dump ( writer ) ; } writer . flush ( ) ; } | Dump buffer contents into the provided writer . | 66 | 9 |
19,631 | @ Override public void addChild ( Tree t ) { //System.out.println("add child "+t.toStringTree()+" "+this.toStringTree()); //System.out.println("existing children: "+children); if ( t == null ) { return ; // do nothing upon addChild(null) } BaseTree childTree = ( BaseTree ) t ; if ( childTree . isNil ( ) ) { // t is an empty node possibly with children if ( this . children != null && this . children == childTree . children ) { throw new RuntimeException ( "attempt to add child list to itself" ) ; } // just add all of childTree's children to this if ( childTree . children != null ) { if ( this . children != null ) { // must copy, this has children already int n = childTree . children . size ( ) ; for ( int i = 0 ; i < n ; i ++ ) { Tree c = ( Tree ) childTree . children . get ( i ) ; this . children . add ( c ) ; // handle double-link stuff for each child of nil root c . setParent ( this ) ; c . setChildIndex ( children . size ( ) - 1 ) ; } } else { // no children for this but t has children; just set pointer // call general freshener routine this . children = childTree . children ; this . freshenParentAndChildIndexes ( ) ; } } } else { // child is not nil (don't care about children) if ( children == null ) { children = createChildrenList ( ) ; // create children list on demand } children . add ( t ) ; childTree . setParent ( this ) ; childTree . setChildIndex ( children . size ( ) - 1 ) ; } // System.out.println("now children are: "+children); } | Add t as child of this node . | 394 | 8 |
19,632 | public void addChildren ( List < ? extends Tree > kids ) { for ( int i = 0 ; i < kids . size ( ) ; i ++ ) { Tree t = kids . get ( i ) ; addChild ( t ) ; } } | Add all elements of kids list as children of this node | 51 | 11 |
19,633 | @ Override public Tree getAncestor ( int ttype ) { Tree t = this ; t = t . getParent ( ) ; while ( t != null ) { if ( t . getType ( ) == ttype ) return t ; t = t . getParent ( ) ; } return null ; } | Walk upwards and get first ancestor with this token type . | 65 | 11 |
19,634 | @ Override public List < ? extends Tree > getAncestors ( ) { if ( getParent ( ) == null ) return null ; List < Tree > ancestors = new ArrayList < Tree > ( ) ; Tree t = this ; t = t . getParent ( ) ; while ( t != null ) { ancestors . add ( 0 , t ) ; // insert at start t = t . getParent ( ) ; } return ancestors ; } | Return a list of all ancestors of this node . The first node of list is the root and the last is the parent of this node . | 92 | 28 |
19,635 | @ Override public String toStringTree ( ) { if ( children == null || children . isEmpty ( ) ) { return this . toString ( ) ; } StringBuilder buf = new StringBuilder ( ) ; if ( ! isNil ( ) ) { buf . append ( "(" ) ; buf . append ( this . toString ( ) ) ; buf . append ( ' ' ) ; } for ( int i = 0 ; children != null && i < children . size ( ) ; i ++ ) { Tree t = ( Tree ) children . get ( i ) ; if ( i > 0 ) { buf . append ( ' ' ) ; } buf . append ( t . toStringTree ( ) ) ; } if ( ! isNil ( ) ) { buf . append ( ")" ) ; } return buf . toString ( ) ; } | Print out a whole tree not just a node | 177 | 9 |
19,636 | public Obj work ( Obj cmd ) throws Exception { stopping = false ; return status ( ) . with ( P_STATUS , STATUS_STARTED ) ; } | null not run false err true ok | 35 | 7 |
19,637 | public String render ( SoyMapData model , String view ) throws IOException { return getSoyTofu ( null ) . newRenderer ( view ) . setData ( model ) . render ( ) ; } | simple helper method to quickly render a template | 46 | 8 |
19,638 | public Obj buildObject ( Object ... members ) { Obj o = newObject ( ) ; for ( int i = 0 ; i < members . length ; i += 2 ) { o . put ( ( String ) members [ i ] , members [ i + 1 ] ) ; } return o ; } | members in the form key val key val etc . | 61 | 10 |
19,639 | @ SuppressWarnings ( "unchecked" ) public < T > void sort ( Arr arr , Comparator < T > c ) { int l = arr . getLength ( ) ; Object [ ] objs = new Object [ l ] ; for ( int i = 0 ; i < l ; i ++ ) { objs [ i ] = arr . get ( i ) ; } Arrays . sort ( ( T [ ] ) objs , c ) ; for ( int i = 0 ; i < l ; i ++ ) { arr . put ( i , objs [ i ] ) ; } } | can lead to classcastexception if comparator is not of the right type | 128 | 16 |
19,640 | public JsonTransformer build ( ) { try { return new WrappingTransformer ( buildPipe ( ) ) ; } catch ( Exception e ) { throw new RuntimeException ( "Failed to build pipeline: " + e . getMessage ( ) , e ) ; } } | Build a raw pipeline without a terminating transformer . It is the caller s responsibility to set the final transformer ( | 58 | 21 |
19,641 | public List < String > getSearchDimensions ( ) { List < String > dimensions = new ArrayList < String > ( ) ; for ( int i = 0 ; i < m_Space . dimensions ( ) ; ++ i ) { dimensions . add ( m_Space . getDimension ( i ) . getLabel ( ) ) ; } return dimensions ; } | Returns the search dimensions | 74 | 4 |
19,642 | protected String logPerformances ( Space space , Vector < Performance > performances , Tag type ) { return m_Owner . logPerformances ( space , performances , type ) ; } | generates a table string for all the performances in the space and returns that . | 38 | 16 |
19,643 | protected void logPerformances ( Space space , Vector < Performance > performances ) { m_Owner . logPerformances ( space , performances ) ; } | aligns all performances in the space and prints those tables to the log file . | 32 | 16 |
19,644 | public void addPerformance ( Performance performance , int folds ) { m_Performances . add ( performance ) ; m_Cache . add ( folds , performance ) ; m_Trace . add ( new AbstractMap . SimpleEntry < Integer , Performance > ( folds , performance ) ) ; } | Adds the performance to the cache and the current list of performances . | 60 | 13 |
19,645 | public List < Entry < String , Object > > getTraceParameterSettings ( int index ) { List < Entry < String , Object > > result = new ArrayList < Map . Entry < String , Object > > ( ) ; List < String > dimensions = getSearchDimensions ( ) ; for ( int i = 0 ; i < dimensions . size ( ) ; ++ i ) { String parameter = dimensions . get ( i ) ; Object value = m_Trace . get ( index ) . getValue ( ) . getValues ( ) . getValue ( i ) ; Map . Entry < String , Object > current = new AbstractMap . SimpleEntry < String , Object > ( parameter , value ) ; result . add ( i , current ) ; } return result ; } | Returns the parameter settings in structured way | 159 | 7 |
19,646 | public SearchResult search ( Instances data ) throws Exception { SearchResult result ; SearchResult best ; try { log ( "\n" + getClass ( ) . getName ( ) + "\n" + getClass ( ) . getName ( ) . replaceAll ( "." , "=" ) + "\n" + "Options: " + Utils . joinOptions ( getOptions ( ) ) + "\n" ) ; log ( "\n---> check" ) ; check ( data ) ; log ( "\n---> preSearch" ) ; preSearch ( data ) ; log ( "\n---> doSearch" ) ; best = doSearch ( data ) ; log ( "\n---> postSearch" ) ; result = postSearch ( data , best ) ; } catch ( Exception e ) { throw e ; } finally { cleanUpSearch ( ) ; } return result ; } | Performs the search and returns the best setup . | 184 | 10 |
19,647 | public void cleanUp ( ) { m_Owner = null ; m_Train = null ; m_Test = null ; m_Generator = null ; m_Values = null ; } | Cleans up after the task finishes . | 39 | 8 |
19,648 | public int compareTo ( Point < E > obj ) { if ( obj == null ) return - 1 ; if ( dimensions ( ) != obj . dimensions ( ) ) return - 1 ; for ( int i = 0 ; i < dimensions ( ) ; i ++ ) { if ( getValue ( i ) . getClass ( ) != obj . getValue ( i ) . getClass ( ) ) return - 1 ; if ( getValue ( i ) instanceof Double ) { if ( Utils . sm ( ( Double ) getValue ( i ) , ( Double ) obj . getValue ( i ) ) ) { return - 1 ; } else if ( Utils . gr ( ( Double ) getValue ( i ) , ( Double ) obj . getValue ( i ) ) ) { return 1 ; } } else { int r = getValue ( i ) . toString ( ) . compareTo ( obj . getValue ( i ) . toString ( ) ) ; if ( r != 0 ) { return r ; } } } return 0 ; } | Compares the given point with this point . | 216 | 9 |
19,649 | public Space subspace ( Point < Integer > center ) { Space result ; SpaceDimension [ ] dimensions ; int i ; dimensions = new SpaceDimension [ dimensions ( ) ] ; for ( i = 0 ; i < dimensions . length ; i ++ ) dimensions [ i ] = getDimension ( i ) . subdimension ( center . getValue ( i ) - 1 , center . getValue ( i ) + 1 ) ; result = new Space ( dimensions ) ; return result ; } | Returns a subspace around the given point with just one more neighbor left and right on each dimension . | 100 | 20 |
19,650 | protected boolean inc ( Integer [ ] locations , int [ ] max ) { boolean result ; int i ; result = true ; i = 0 ; while ( i < locations . length ) { if ( locations [ i ] < max [ i ] - 1 ) { locations [ i ] ++ ; break ; } else { locations [ i ] = 0 ; i ++ ; // adding was not possible! if ( i == locations . length ) result = false ; } } return result ; } | Increments the location array by 1 . | 98 | 8 |
19,651 | protected Vector < Point < Integer > > listPoints ( ) { Vector < Point < Integer >> result ; int i ; int [ ] max ; Integer [ ] locations ; boolean ok ; result = new Vector < Point < Integer > > ( ) ; // determine maximum locations per dimension max = new int [ dimensions ( ) ] ; for ( i = 0 ; i < max . length ; i ++ ) max [ i ] = getDimension ( i ) . width ( ) ; // create first point locations = new Integer [ dimensions ( ) ] ; for ( i = 0 ; i < locations . length ; i ++ ) locations [ i ] = 0 ; result . add ( new Point < Integer > ( locations ) ) ; ok = true ; while ( ok ) { ok = inc ( locations , max ) ; if ( ok ) result . add ( new Point < Integer > ( locations ) ) ; } return result ; } | returns a Vector with all points in the space . | 188 | 11 |
19,652 | protected String getID ( int cv , Point < Object > values ) { String result ; int i ; result = "" + cv ; for ( i = 0 ; i < values . dimensions ( ) ; i ++ ) result += " \ t " + values . getValue ( i ) ; return result ; } | returns the ID string for a cache item . | 65 | 10 |
19,653 | public Performance get ( int cv , Point < Object > values ) { return m_Cache . get ( getID ( cv , values ) ) ; } | returns a cached performance object null if not yet in the cache . | 33 | 14 |
19,654 | public void add ( int cv , Performance p ) { m_Cache . put ( getID ( cv , p . getValues ( ) ) , p ) ; } | adds the performance to the cache . | 36 | 8 |
19,655 | @ Override public DefaultEvaluationTask newTask ( MultiSearchCapable owner , Instances train , Instances test , SetupGenerator generator , Point < Object > values , int folds , int eval , int classLabel ) { return new DefaultEvaluationTask ( owner , train , test , generator , values , folds , eval , classLabel ) ; } | Returns a new task . | 75 | 5 |
19,656 | public boolean check ( int id ) { for ( Tag tag : getTags ( ) ) { if ( tag . getID ( ) == id ) return true ; } return false ; } | Returns whether the ID is valid . | 38 | 7 |
19,657 | public double getMetric ( int id , int classLabel ) { try { switch ( id ) { case DefaultEvaluationMetrics . EVALUATION_CC : return m_Evaluation . correlationCoefficient ( ) ; case DefaultEvaluationMetrics . EVALUATION_MATTHEWS_CC : return m_Evaluation . matthewsCorrelationCoefficient ( 0 ) ; case DefaultEvaluationMetrics . EVALUATION_RMSE : return m_Evaluation . rootMeanSquaredError ( ) ; case DefaultEvaluationMetrics . EVALUATION_RRSE : return m_Evaluation . rootRelativeSquaredError ( ) ; case DefaultEvaluationMetrics . EVALUATION_MAE : return m_Evaluation . meanAbsoluteError ( ) ; case DefaultEvaluationMetrics . EVALUATION_RAE : return m_Evaluation . relativeAbsoluteError ( ) ; case DefaultEvaluationMetrics . EVALUATION_COMBINED : return ( 1 - StrictMath . abs ( m_Evaluation . correlationCoefficient ( ) ) + m_Evaluation . rootRelativeSquaredError ( ) + m_Evaluation . relativeAbsoluteError ( ) ) ; case DefaultEvaluationMetrics . EVALUATION_ACC : return m_Evaluation . pctCorrect ( ) ; case DefaultEvaluationMetrics . EVALUATION_KAPPA : return m_Evaluation . kappa ( ) ; case DefaultEvaluationMetrics . EVALUATION_PRECISION : return m_Evaluation . precision ( classLabel ) ; case DefaultEvaluationMetrics . EVALUATION_WEIGHTED_PRECISION : return m_Evaluation . weightedPrecision ( ) ; case DefaultEvaluationMetrics . EVALUATION_RECALL : return m_Evaluation . recall ( classLabel ) ; case DefaultEvaluationMetrics . EVALUATION_WEIGHTED_RECALL : return m_Evaluation . weightedRecall ( ) ; case DefaultEvaluationMetrics . EVALUATION_AUC : return m_Evaluation . areaUnderROC ( classLabel ) ; case DefaultEvaluationMetrics . EVALUATION_WEIGHTED_AUC : return m_Evaluation . weightedAreaUnderROC ( ) ; case DefaultEvaluationMetrics . EVALUATION_PRC : return m_Evaluation . areaUnderPRC ( classLabel ) ; case DefaultEvaluationMetrics . EVALUATION_WEIGHTED_PRC : return m_Evaluation . weightedAreaUnderPRC ( ) ; case DefaultEvaluationMetrics . EVALUATION_FMEASURE : return m_Evaluation . fMeasure ( classLabel ) ; case DefaultEvaluationMetrics . EVALUATION_WEIGHTED_FMEASURE : return m_Evaluation . weightedFMeasure ( ) ; case DefaultEvaluationMetrics . EVALUATION_TRUE_POSITIVE_RATE : return m_Evaluation . truePositiveRate ( classLabel ) ; case DefaultEvaluationMetrics . EVALUATION_TRUE_NEGATIVE_RATE : return m_Evaluation . trueNegativeRate ( classLabel ) ; case DefaultEvaluationMetrics . EVALUATION_FALSE_POSITIVE_RATE : return m_Evaluation . falsePositiveRate ( classLabel ) ; case DefaultEvaluationMetrics . EVALUATION_FALSE_NEGATIVE_RATE : return m_Evaluation . falseNegativeRate ( classLabel ) ; default : return Double . NaN ; } } catch ( Exception e ) { return Double . NaN ; } } | Returns the metric for the given ID . | 847 | 8 |
19,658 | public boolean invert ( int id ) { switch ( id ) { case EVALUATION_CC : case EVALUATION_ACC : case EVALUATION_KAPPA : case EVALUATION_MATTHEWS_CC : case EVALUATION_PRECISION : case EVALUATION_WEIGHTED_PRECISION : case EVALUATION_RECALL : case EVALUATION_WEIGHTED_RECALL : case EVALUATION_AUC : case EVALUATION_WEIGHTED_AUC : case EVALUATION_PRC : case EVALUATION_WEIGHTED_PRC : case EVALUATION_FMEASURE : case EVALUATION_WEIGHTED_FMEASURE : case EVALUATION_TRUE_POSITIVE_RATE : case EVALUATION_TRUE_NEGATIVE_RATE : return true ; default : return false ; } } | Returns whether to negate the metric for sorting purposes . | 211 | 10 |
19,659 | public String [ ] getItems ( ) throws Exception { String [ ] result ; if ( getCustomDelimiter ( ) . isEmpty ( ) ) result = Utils . splitOptions ( getList ( ) ) ; else result = getList ( ) . split ( getCustomDelimiter ( ) ) ; return result ; } | Splits the list string using the appropriate delimiter . | 68 | 11 |
19,660 | public SpaceDimension spaceDimension ( ) throws Exception { String [ ] items ; items = getItems ( ) ; return new ListSpaceDimension ( 0 , items . length - 1 , items , getProperty ( ) ) ; } | Returns the parameter as space dimensions . | 48 | 7 |
19,661 | public boolean getBooleanSetting ( final ChaiSetting setting ) { final String settingValue = getSetting ( setting ) ; return StringHelper . convertStrToBoolean ( settingValue ) ; } | Get an individual setting value and test it as a boolean . | 40 | 12 |
19,662 | public List < String > bindURLsAsList ( ) { final List < String > splitUrls = Arrays . asList ( getSetting ( ChaiSetting . BIND_URLS ) . split ( LDAP_URL_SEPARATOR_REGEX_PATTERN ) ) ; return Collections . unmodifiableList ( splitUrls ) ; } | Returns an immutable list of the ldap URLs . | 76 | 11 |
19,663 | private static void pause ( final long time ) { final long startTime = System . currentTimeMillis ( ) ; do { try { final long sleepTime = time - ( System . currentTimeMillis ( ) - startTime ) ; Thread . sleep ( sleepTime > 0 ? sleepTime : 10 ) ; } catch ( InterruptedException e ) { //don't care } } while ( ( System . currentTimeMillis ( ) - startTime ) < time ) ; } | Causes the executing thread to pause for a period of time . | 99 | 13 |
19,664 | public static ChaiResponseSet newChaiResponseSet ( final Map < Challenge , String > challengeResponseMap , final Locale locale , final int minimumRandomRequired , final ChaiConfiguration chaiConfiguration , final String csIdentifier ) throws ChaiValidationException { return newChaiResponseSet ( challengeResponseMap , Collections . emptyMap ( ) , locale , minimumRandomRequired , chaiConfiguration , csIdentifier ) ; } | Create a new ResponseSet . The generated ResponseSet will be suitable for writing to the directory . | 89 | 19 |
19,665 | private void checkTimer ( ) { try { serviceThreadLock . lock ( ) ; if ( watchdogTimer == null ) { // if there is NOT an active timer if ( ! issuedWatchdogWrappers . allValues ( ) . isEmpty ( ) ) { // if there are active providers. LOGGER . debug ( "starting up " + THREAD_NAME + ", " + watchdogFrequency + "ms check frequency" ) ; // create a new timer startWatchdogThread ( ) ; } } } finally { serviceThreadLock . unlock ( ) ; } } | Regulate the timer . This is important because the timer task creates its own thread and if the task isn t cleaned up there could be a thread leak . | 116 | 31 |
19,666 | public static ConfigObjectRecord createNew ( final ChaiEntry entry , final String attr , final String recordType , final String guid1 , final String guid2 ) { //Ensure the entry is not null if ( entry == null ) { throw new NullPointerException ( "entry can not be null" ) ; } //Ensure the record type is not null if ( recordType == null ) { throw new NullPointerException ( "recordType can not be null" ) ; } //Make sure the attr is not null if ( attr == null ) { throw new NullPointerException ( "attr can not be null" ) ; } // truncate record type to 4 chars. final String effectiveRecordType = recordType . length ( ) > 4 ? recordType . substring ( 0 , 4 ) : recordType ; final ConfigObjectRecord cor = new ConfigObjectRecord ( ) ; cor . objectEntry = entry ; cor . attr = attr ; cor . recordType = effectiveRecordType ; cor . guid1 = ( guid1 == null || guid1 . length ( ) < 1 ) ? EMPTY_RECORD_VALUE : guid1 ; cor . guid2 = ( guid2 == null || guid2 . length ( ) < 1 ) ? EMPTY_RECORD_VALUE : guid2 ; return cor ; } | Create a new config object record . This will only create a java object representing the config object record . It is up to the caller to call the updatePayload method which will actually commit the record to the directory . | 279 | 43 |
19,667 | public static List < ConfigObjectRecord > readRecordFromLDAP ( final ChaiEntry ldapEntry , final String attr , final String recordType , final Set guid1 , final Set guid2 ) throws ChaiOperationException , ChaiUnavailableException { if ( ldapEntry == null ) { throw new NullPointerException ( "ldapEntry can not be null" ) ; } if ( attr == null ) { throw new NullPointerException ( "attr can not be null" ) ; } if ( recordType == null ) { throw new NullPointerException ( "recordType can not be null" ) ; } //Read the attribute final Set < String > values = ldapEntry . readMultiStringAttribute ( attr ) ; final List < ConfigObjectRecord > cors = new ArrayList < ConfigObjectRecord > ( ) ; for ( final String value : values ) { final ConfigObjectRecord loopRec = parseString ( value ) ; loopRec . objectEntry = ldapEntry ; loopRec . attr = attr ; cors . add ( loopRec ) ; //If it doesnt match any of the tests, then remove the record. if ( ! loopRec . getRecordType ( ) . equalsIgnoreCase ( recordType ) ) { cors . remove ( loopRec ) ; } else if ( guid1 != null && ! guid1 . contains ( loopRec . getGuid1 ( ) ) ) { cors . remove ( loopRec ) ; } else if ( guid2 != null && ! guid2 . contains ( loopRec . getGuid2 ( ) ) ) { cors . remove ( loopRec ) ; } } return cors ; } | Retreive matching config object records from the directory . | 357 | 11 |
19,668 | public static ChaiGroup createGroup ( final String parentDN , final String name , final ChaiProvider provider ) throws ChaiOperationException , ChaiUnavailableException { //Get a good CN for it final String objectCN = findUniqueName ( name , parentDN , provider ) ; //Concantonate the entryDN final StringBuilder entryDN = new StringBuilder ( ) ; entryDN . append ( "cn=" ) ; entryDN . append ( objectCN ) ; entryDN . append ( ' ' ) ; entryDN . append ( parentDN ) ; //First create the base group. provider . createEntry ( entryDN . toString ( ) , ChaiConstant . OBJECTCLASS_BASE_LDAP_GROUP , Collections . emptyMap ( ) ) ; //Now build an ldapentry object to add attributes to it final ChaiEntry theObject = provider . getEntryFactory ( ) . newChaiEntry ( entryDN . toString ( ) ) ; //Add the description theObject . writeStringAttribute ( ChaiConstant . ATTR_LDAP_DESCRIPTION , name ) ; //Return the newly created group. return provider . getEntryFactory ( ) . newChaiGroup ( entryDN . toString ( ) ) ; } | Creates a new group entry in the ldap directory . A new groupOfNames object is created . The cn and description ldap attributes are set to the supplied name . | 266 | 38 |
19,669 | public static String findUniqueName ( final String baseName , final String containerDN , final ChaiProvider provider ) throws ChaiOperationException , ChaiUnavailableException { char ch ; final StringBuilder cnStripped = new StringBuilder ( ) ; final String effectiveBasename = ( baseName == null ) ? "" : baseName ; // First boil down the root name. Preserve only the alpha-numerics. for ( int i = 0 ; i < effectiveBasename . length ( ) ; i ++ ) { ch = effectiveBasename . charAt ( i ) ; if ( Character . isLetterOrDigit ( ch ) ) { cnStripped . append ( ch ) ; } } if ( cnStripped . length ( ) == 0 ) { // Generate a random seed to runServer with, how about the current date cnStripped . append ( System . currentTimeMillis ( ) ) ; } // Now we have a base name, let's runServer testing it... String uniqueCN ; StringBuilder filter ; final Random randomNumber = new Random ( ) ; String stringCounter = null ; // Start with a random 3 digit number int counter = randomNumber . nextInt ( ) % 1000 ; while ( true ) { // Initialize the String Buffer and Unique DN. filter = new StringBuilder ( 64 ) ; if ( stringCounter != null ) { uniqueCN = cnStripped . append ( stringCounter ) . toString ( ) ; } else { uniqueCN = cnStripped . toString ( ) ; } filter . append ( "(" ) . append ( ChaiConstant . ATTR_LDAP_COMMON_NAME ) . append ( "=" ) . append ( uniqueCN ) . append ( ")" ) ; final Map < String , Map < String , String > > results = provider . search ( containerDN , filter . toString ( ) , null , SearchScope . ONE ) ; if ( results . size ( ) == 0 ) { // No object found! break ; } else { // Increment it every time stringCounter = Integer . toString ( counter ++ ) ; } } return uniqueCN ; } | Derives a unique entry name for an ldap container . Assumes CN as the naming attribute . | 456 | 21 |
19,670 | public static String entryToLDIF ( final ChaiEntry theEntry ) throws ChaiUnavailableException , ChaiOperationException { final StringBuilder sb = new StringBuilder ( ) ; sb . append ( "dn: " ) . append ( theEntry . getEntryDN ( ) ) . append ( "\n" ) ; final Map < String , Map < String , List < String > > > results = theEntry . getChaiProvider ( ) . searchMultiValues ( theEntry . getEntryDN ( ) , "(objectClass=*)" , null , SearchScope . BASE ) ; final Map < String , List < String > > props = results . get ( theEntry . getEntryDN ( ) ) ; for ( final Map . Entry < String , List < String > > entry : props . entrySet ( ) ) { final String attrName = entry . getKey ( ) ; final List < String > values = entry . getValue ( ) ; for ( final String value : values ) { sb . append ( attrName ) . append ( ": " ) . append ( value ) . append ( ' ' ) ; } } return sb . toString ( ) ; } | Convert to an LDIF format . Useful for debugging or other purposes | 250 | 14 |
19,671 | public static DirectoryVendor determineDirectoryVendor ( final ChaiEntry rootDSE ) throws ChaiUnavailableException , ChaiOperationException { final Set < String > interestedAttributes = new HashSet <> ( ) ; for ( final DirectoryVendor directoryVendor : DirectoryVendor . values ( ) ) { interestedAttributes . addAll ( directoryVendor . getVendorFactory ( ) . interestedDseAttributes ( ) ) ; } final SearchHelper searchHelper = new SearchHelper ( ) ; searchHelper . setAttributes ( interestedAttributes . toArray ( new String [ interestedAttributes . size ( ) ] ) ) ; searchHelper . setFilter ( "(objectClass=*)" ) ; searchHelper . setMaxResults ( 1 ) ; searchHelper . setSearchScope ( SearchScope . BASE ) ; final Map < String , Map < String , List < String > > > results = rootDSE . getChaiProvider ( ) . searchMultiValues ( "" , searchHelper ) ; if ( results != null && ! results . isEmpty ( ) ) { final Map < String , List < String > > rootDseSearchResults = results . values ( ) . iterator ( ) . next ( ) ; for ( final DirectoryVendor directoryVendor : DirectoryVendor . values ( ) ) { if ( directoryVendor . getVendorFactory ( ) . detectVendorFromRootDSEData ( rootDseSearchResults ) ) { return directoryVendor ; } } } return DirectoryVendor . GENERIC ; } | Determines the vendor of a the ldap directory by reading RootDSE attributes . | 315 | 19 |
19,672 | static boolean isAuthenticationRelated ( final String message ) { for ( final DirectoryVendor vendor : DirectoryVendor . values ( ) ) { final ErrorMap errorMap = vendor . getVendorFactory ( ) . getErrorMap ( ) ; if ( errorMap . isAuthenticationRelated ( message ) ) { return true ; } } return false ; } | Indicates if the error is related to authentication . | 73 | 10 |
19,673 | public void setFilterNot ( final String attributeName , final String value ) { this . setFilter ( attributeName , value ) ; filter = "(!" + filter + ")" ; } | Set up a not exists filter for an attribute name and value pair . | 38 | 14 |
19,674 | public void setFilter ( final String attributeName , final String value ) { filter = new FilterSequence ( attributeName , value ) . toString ( ) ; } | Set up a standard filter attribute name and value pair . | 34 | 11 |
19,675 | public void setFilterOr ( final Map < String , String > nameValuePairs ) { if ( nameValuePairs == null ) { throw new NullPointerException ( ) ; } if ( nameValuePairs . size ( ) < 1 ) { throw new IllegalArgumentException ( "requires at least one key" ) ; } final List < FilterSequence > filters = new ArrayList <> ( ) ; for ( final Map . Entry < String , String > entry : nameValuePairs . entrySet ( ) ) { filters . add ( new FilterSequence ( entry . getKey ( ) , entry . getValue ( ) , FilterSequence . MatchingRuleEnum . EQUALS ) ) ; } setFilterBind ( filters , "|" ) ; } | Set up an OR filter for each map key and value . Consider the following example . | 162 | 17 |
19,676 | public static boolean convertStrToBoolean ( final String string ) { return ! ( string == null || string . length ( ) < 1 ) && ( "true" . equalsIgnoreCase ( string ) || "1" . equalsIgnoreCase ( string ) || "yes" . equalsIgnoreCase ( string ) || "y" . equalsIgnoreCase ( string ) ) ; } | Convert a string value to a boolean . If the value is a common positive string value such as 1 true y or yes then TRUE is returned . For any other value or null FALSE is returned . | 81 | 40 |
19,677 | public byte [ ] getEncodedValue ( ) { final String characterEncoding = this . chaiConfiguration . getSetting ( ChaiSetting . LDAP_CHARACTER_ENCODING ) ; final byte [ ] password = modifyPassword . getBytes ( Charset . forName ( characterEncoding ) ) ; final byte [ ] dn = modifyDn . getBytes ( Charset . forName ( characterEncoding ) ) ; // Sequence tag (1) + sequence length (1) + dn tag (1) + // dn length (1) + dn (variable) + password tag (1) + // password length (1) + password (variable) final int encodedLength = 6 + dn . length + password . length ; final byte [ ] encoded = new byte [ encodedLength ] ; int valueI = 0 ; // sequence start encoded [ valueI ++ ] = ( byte ) 0x30 ; // length of body encoded [ valueI ++ ] = ( byte ) ( 4 + dn . length + password . length ) ; encoded [ valueI ++ ] = LDAP_TAG_EXOP_X_MODIFY_PASSWD_ID ; encoded [ valueI ++ ] = ( byte ) dn . length ; System . arraycopy ( dn , 0 , encoded , valueI , dn . length ) ; valueI += dn . length ; encoded [ valueI ++ ] = LDAP_TAG_EXOP_X_MODIFY_PASSWD_NEW ; encoded [ valueI ++ ] = ( byte ) password . length ; System . arraycopy ( password , 0 , encoded , valueI , password . length ) ; valueI += password . length ; return encoded ; } | Get the BER encoded value for this operation . | 364 | 10 |
19,678 | public static void registerTypeConversion ( Conversion < ? > conversion ) { Object [ ] keys = conversion . getTypeKeys ( ) ; if ( keys == null ) { return ; } for ( int i = 0 ; i < keys . length ; i ++ ) { registerTypeConversion ( keys [ i ] , conversion ) ; } } | Register a type conversion object under the specified keys . This method can be used by developers to register custom type conversion objects . | 70 | 24 |
19,679 | private static List < Object > getTypeKeys ( Conversion < ? > conversion ) { List < Object > result = new ArrayList < Object > ( ) ; synchronized ( typeConversions ) { // Clone the conversions Map < Object , Conversion < ? > > map = new HashMap < Object , Conversion < ? > > ( typeConversions ) ; // Find all keys that map to this conversion instance for ( Map . Entry < Object , Conversion < ? > > entry : map . entrySet ( ) ) { if ( entry . getValue ( ) == conversion ) { result . add ( entry . getKey ( ) ) ; } } } return result ; } | Discover all the type key mappings for this conversion | 135 | 10 |
19,680 | private static Conversion < ? > getTypeConversion ( Object typeKey , Object value ) { // Check if the provided value is already of the target type if ( typeKey instanceof Class && ( ( Class ) typeKey ) != Object . class && ( ( Class ) typeKey ) . isInstance ( value ) ) { return IDENTITY_CONVERSION ; } // Find the type conversion object return ( value instanceof Convertible ) ? ( ( Convertible ) value ) . getTypeConversion ( typeKey ) : typeConversions . get ( typeKey ) ; } | Obtain a conversion for the specified type key and value | 118 | 11 |
19,681 | @ Override public boolean getScrollableTracksViewportWidth ( ) { Component parent = getParent ( ) ; ComponentUI myui = getUI ( ) ; return parent == null || ( myui . getPreferredSize ( this ) . width <= parent . getSize ( ) . width ) ; } | to preserve the full width of the text | 64 | 8 |
19,682 | public int yToLine ( int y ) { FontMetrics fm = this . getFontMetrics ( this . getFont ( ) ) ; int height = fm . getHeight ( ) ; Document doc = this . getDocument ( ) ; int length = doc . getLength ( ) ; Element map = doc . getDefaultRootElement ( ) ; int startLine = map . getElementIndex ( 0 ) ; int endline = map . getElementIndex ( length ) ; return Math . max ( 0 , Math . min ( endline - 1 , y / height + startLine ) ) - 1 ; } | Converts a y co - ordinate to a line index . | 128 | 13 |
19,683 | public Campaign readFile ( String fileName ) throws Exception { Campaign result = new Campaign ( ) ; DocumentBuilderFactory dbf = DocumentBuilderFactory . newInstance ( ) ; DocumentBuilder db = dbf . newDocumentBuilder ( ) ; Document doc = db . parse ( fileName ) ; doc . getDocumentElement ( ) . normalize ( ) ; Element el = doc . getDocumentElement ( ) ; if ( ! el . getNodeName ( ) . equals ( "campaign" ) ) { throw new Exception ( fileName + " is not a valid xml campain file" ) ; } result . name = el . getAttributeNode ( "name" ) . getValue ( ) ; NodeList nodeLst = doc . getElementsByTagName ( "run" ) ; for ( int s = 0 ; s < nodeLst . getLength ( ) ; s ++ ) { Node node = nodeLst . item ( s ) ; if ( node . getNodeType ( ) == Node . ELEMENT_NODE ) { Element element = ( Element ) node ; CampaignRun run = new CampaignRun ( ) ; run . testbed = element . getAttribute ( "testbed" ) ; result . runs . add ( run ) ; NodeList nodeList = element . getElementsByTagName ( "testsuite" ) ; for ( int t = 0 ; t < nodeList . getLength ( ) ; t ++ ) { TestSuiteParams params = new TestSuiteParams ( ) ; run . testsuites . add ( params ) ; params . setDirectory ( nodeList . item ( t ) . getAttributes ( ) . getNamedItem ( "directory" ) . getNodeValue ( ) ) ; NodeList childList = nodeList . item ( t ) . getChildNodes ( ) ; for ( int c = 0 ; c < childList . getLength ( ) ; c ++ ) { Node childNode = childList . item ( c ) ; if ( childNode . getNodeName ( ) . equals ( "testdata" ) ) { String selectorStr = childNode . getAttributes ( ) . getNamedItem ( "selector" ) . getNodeValue ( ) ; String [ ] selectedRowsStr = selectorStr . split ( "," ) ; TreeSet < Integer > selectedRows = new TreeSet <> ( ) ; for ( String selectedRowStr : selectedRowsStr ) { selectedRows . add ( Integer . parseInt ( selectedRowStr ) ) ; } params . setDataRows ( selectedRows ) ; } if ( childList . item ( c ) . getNodeName ( ) . equals ( "loopInHours" ) ) { params . setLoopInHours ( true ) ; } if ( childList . item ( c ) . getNodeName ( ) . equals ( "count" ) ) { try { params . setCount ( Integer . parseInt ( childList . item ( c ) . getTextContent ( ) ) ) ; } catch ( NumberFormatException e ) { logger . error ( "count field in " + fileName + " file should be numeric" ) ; } } } } } } return result ; } | Read the xml campaign file | 671 | 5 |
19,684 | public boolean execute ( Campaign campaign ) { boolean campaignResult = true ; currentCampaign = campaign ; campaignStartTimeStamp = new Date ( ) ; try { createReport ( ) ; for ( CampaignRun run : currentCampaign . getRuns ( ) ) { if ( TestEngine . isAbortedByUser ( ) ) { break ; } currentTestBed = run . getTestbed ( ) ; String testSuiteName = currentCampaign . getName ( ) + " - " + currentTestBed . substring ( 0 , currentTestBed . lastIndexOf ( ' ' ) ) ; TestBedConfiguration . setConfigFile ( StaticConfiguration . TESTBED_CONFIG_DIRECTORY + "/" + currentTestBed ) ; currentTestSuite = MetaTestSuite . createMetaTestSuite ( testSuiteName , run . getTestsuites ( ) ) ; if ( currentTestSuite == null ) { continue ; } currentTestSuite . addTestReportListener ( this ) ; campaignResult &= TestEngine . execute ( currentTestSuite ) ; // NOSONAR - Potentially dangerous use of non-short-circuit logic currentTestSuite . removeTestReportListener ( this ) ; currentTestSuite = null ; } CampaignReportManager . getInstance ( ) . stopReport ( ) ; } finally { TestEngine . tearDown ( ) ; campaignStartTimeStamp = null ; currentCampaign = null ; } return campaignResult ; } | Executes a campaign | 307 | 4 |
19,685 | private void createReport ( ) { CampaignReportManager . getInstance ( ) . startReport ( campaignStartTimeStamp , currentCampaign . getName ( ) ) ; for ( CampaignRun run : currentCampaign . getRuns ( ) ) { CampaignResult result = new CampaignResult ( run . getTestbed ( ) ) ; result . setStatus ( Status . NOT_EXECUTED ) ; CampaignReportManager . getInstance ( ) . putEntry ( result ) ; } CampaignReportManager . getInstance ( ) . refresh ( ) ; } | Create a empty report . All campaign run will be Not Executed | 112 | 13 |
19,686 | public void open ( ) throws SQLException , ClassNotFoundException { logger . info ( "Using database driver: " + jdbcDriver ) ; Class . forName ( jdbcDriver ) ; logger . info ( "Using database.url: " + jdbcURL ) ; // connect login/pass con = DriverManager . getConnection ( jdbcURL , user , password ) ; // Exception will be thrown if something went wrong connected = true ; } | Open a JDBC connection to the database | 99 | 8 |
19,687 | public ResultSet executeQuery ( String query ) throws SQLException , ClassNotFoundException { if ( ! connected ) { open ( ) ; } Statement stmt = con . createStatement ( ) ; return stmt . executeQuery ( query ) ; } | Execute the specified query If the SQL connection if not open it will be opened automatically | 53 | 17 |
19,688 | public boolean executeCommand ( String query ) throws SQLException , ClassNotFoundException { if ( ! connected ) { open ( ) ; } Statement stmt = con . createStatement ( ) ; return stmt . execute ( query ) ; } | Execute the specified SQL command If the SQL connection if not open it will be opened automatically | 51 | 18 |
19,689 | public void doubleClick ( String fileName ) throws QTasteException { try { new Region ( this . rect ) . doubleClick ( fileName ) ; } catch ( Exception ex ) { throw new QTasteException ( ex . getMessage ( ) , ex ) ; } } | Simulates a double click on the specified image of the area . | 58 | 13 |
19,690 | public static Type getType ( ) { String osName = System . getProperty ( "os.name" ) . toLowerCase ( ) ; if ( osName . contains ( "windows" ) ) { return Type . WINDOWS ; } else if ( osName . contains ( "linux" ) ) { return Type . LINUX ; } else if ( osName . contains ( "mac" ) ) { return Type . MAC ; } return Type . UNKNOWN ; } | Get OS type . | 99 | 4 |
19,691 | public static void copyFiles ( File src , File dest ) throws IOException { if ( src . isDirectory ( ) ) { dest . mkdirs ( ) ; String list [ ] = src . list ( ) ; for ( String fileName : list ) { String dest1 = dest . getPath ( ) + "/" + fileName ; String src1 = src . getPath ( ) + "/" + fileName ; // i.e: avoid .svn directory File src1_ = new File ( src1 ) ; File dest1_ = new File ( dest1 ) ; if ( ! src1_ . isHidden ( ) ) { copyFiles ( src1_ , dest1_ ) ; } } } else { FileInputStream fin = new FileInputStream ( src ) ; FileOutputStream fout = new FileOutputStream ( dest ) ; int c ; while ( ( c = fin . read ( ) ) >= 0 ) { fout . write ( c ) ; } fin . close ( ) ; fout . close ( ) ; } } | The method copyFiles being defined | 221 | 6 |
19,692 | public static int collapseJTreeNode ( javax . swing . JTree tree , javax . swing . tree . TreeModel model , Object node , int row , int depth ) { if ( node != null && ! model . isLeaf ( node ) ) { tree . collapseRow ( row ) ; if ( depth != 0 ) { for ( int index = 0 ; row + 1 < tree . getRowCount ( ) && index < model . getChildCount ( node ) ; index ++ ) { row ++ ; Object child = model . getChild ( node , index ) ; if ( child == null ) { break ; } javax . swing . tree . TreePath path ; while ( ( path = tree . getPathForRow ( row ) ) != null && path . getLastPathComponent ( ) != child ) { row ++ ; } if ( path == null ) { break ; } row = collapseJTreeNode ( tree , model , child , row , depth - 1 ) ; } } } return row ; } | Expands a given node in a JTree . | 215 | 10 |
19,693 | public static String getDocumentAsXmlString ( Document doc ) throws TransformerConfigurationException , TransformerException { DOMSource domSource = new DOMSource ( doc ) ; TransformerFactory tf = TransformerFactory . newInstance ( ) ; try { tf . setAttribute ( "indent-number" , 4 ) ; } catch ( IllegalArgumentException e ) { // ignore } Transformer transformer = tf . newTransformer ( ) ; //transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,"yes"); transformer . setOutputProperty ( OutputKeys . METHOD , "xml" ) ; transformer . setOutputProperty ( OutputKeys . ENCODING , "UTF-8" ) ; transformer . setOutputProperty ( "{http://xml.apache.org/xslt}indent-amount" , "4" ) ; transformer . setOutputProperty ( OutputKeys . INDENT , "yes" ) ; // java . io . StringWriter sw = new java . io . StringWriter ( ) ; StreamResult sr = new StreamResult ( sw ) ; transformer . transform ( domSource , sr ) ; return sw . toString ( ) ; } | Return the XMLDocument formatted as a String | 248 | 8 |
19,694 | public boolean connect ( ) { if ( client . isConnected ( ) ) { logger . warn ( "Already connected" ) ; return true ; } try { logger . info ( "Connecting to remote host " + remoteHost ) ; client . connect ( remoteHost ) ; client . rlogin ( localUser , remoteUser , terminalType ) ; writer = new OutputStreamWriter ( client . getOutputStream ( ) ) ; outputReaderThread = new Thread ( new OutputReader ( ) ) ; outputReaderThread . start ( ) ; if ( interactive ) { standardInputReaderThread = new Thread ( new StandardInputReader ( ) ) ; standardInputReaderThread . start ( ) ; } try { Thread . sleep ( 200 ) ; } catch ( InterruptedException ex ) { } if ( client . isConnected ( ) ) { return true ; } else { logger . fatal ( "Client has been immediately disconnected from remote host:" + remoteHost ) ; return false ; } //outputReaderThread. } catch ( IOException e ) { logger . fatal ( "Could not connect to remote host:" + remoteHost , e ) ; return false ; } } | Create a rlogin connection to the specified remote host . | 237 | 11 |
19,695 | public boolean reboot ( ) { if ( ! sendCommand ( "reboot" ) ) { return false ; } // wait 1 second try { Thread . sleep ( 1000 ) ; } catch ( InterruptedException ex ) { } disconnect ( ) ; // check that remote host is not accessible anymore // open a socket without any parameters. It hasn't been binded or connected try ( Socket socket = new Socket ( ) ) { // bind to a local ephemeral port socket . bind ( null ) ; socket . connect ( new InetSocketAddress ( remoteHost , RLoginClient . DEFAULT_PORT ) , 1 ) ; } catch ( SocketTimeoutException e ) { logger . info ( "Rebooted host " + remoteHost + " successfully" ) ; return true ; } catch ( IOException e ) { logger . error ( "Something went wrong while rebooting host:" + remoteHost ) ; return false ; } // Expected to get an exception as the remote host should not be reachable anymore logger . error ( "Host " + remoteHost + " did not reboot as expected! Please check that no other rlogin client is connected!" ) ; return false ; } | Reboot the remote host by sending the reboot command and check that the remote host is not accessible anymore . | 241 | 21 |
19,696 | public boolean sendCommand ( String command ) { if ( writer != null ) { try { logger . info ( "Sending command " + command + " to remote host " + remoteHost ) ; writer . write ( command ) ; writer . write ( ' ' ) ; writer . flush ( ) ; } catch ( IOException e ) { logger . fatal ( "Error while sending command " + command + " to remote host " + remoteHost , e ) ; return false ; } return true ; } else { return false ; } } | Send the specified command to the remote host | 109 | 8 |
19,697 | public void disconnect ( ) { try { if ( client . isConnected ( ) ) { client . disconnect ( ) ; } if ( standardInputReaderThread != null ) { standardInputReaderThread = null ; } if ( outputReaderThread != null ) { outputReaderThread . join ( ) ; outputReaderThread = null ; } writer = null ; } catch ( InterruptedException ex ) { } catch ( IOException e ) { logger . fatal ( "Error while disconnecting from rlogin session. Host: " + remoteHost , e ) ; } } | Disconnect the rlogin client from the remote host . | 115 | 11 |
19,698 | protected void paintDisabledText ( JLabel pLabel , Graphics pG , String pStr , int pTextX , int pTextY ) { Graphics2D g2 = ( Graphics2D ) pG ; pG . setColor ( Color . GRAY ) ; g2 . setRenderingHint ( RenderingHints . KEY_ANTIALIASING , RenderingHints . VALUE_ANTIALIAS_ON ) ; pG . drawString ( pStr , pTextX , pTextY ) ; g2 . setRenderingHint ( RenderingHints . KEY_ANTIALIASING , RenderingHints . VALUE_ANTIALIAS_OFF ) ; /*FontMetrics fm = pG.getFontMetrics(); Rectangle strrect = fm.getStringBounds(pStr, pG).getBounds(); if(pLabel.getText().length() > 0) { pG.setColor(ResourceManager.getInstance().getNormalColor()); pG.fillRect(pTextX + strrect.width + SPACE_INC, pTextY + strrect.y, 2, strrect.height); }*/ } | private static final int SPACE_INC = 12 ; | 255 | 10 |
19,699 | public void close ( ) { if ( mWithBody ) { mOut . println ( "</BODY>" ) ; } mOut . println ( "</HTML>" ) ; mOut . close ( ) ; mOut = null ; } | Writes HTML body ending tag if needed and HTML footer and closes file . | 50 | 16 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.