idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
10,600 | private static boolean isOverridable ( Method method , Class < ? > targetClass ) { if ( Modifier . isPrivate ( method . getModifiers ( ) ) ) { return false ; } if ( Modifier . isPublic ( method . getModifiers ( ) ) || Modifier . isProtected ( method . getModifiers ( ) ) ) { return true ; } return ( targetClass == null || getPackageName ( method . getDeclaringClass ( ) ) . equals ( getPackageName ( targetClass ) ) ) ; } | Determine whether the given method is overridable in the given target class . | 113 | 17 |
10,601 | < I > void register ( Method disposeMethod , I injectee ) { disposables . add ( new Disposable ( disposeMethod , injectee ) ) ; } | Register an injectee and its related method to release resources . | 34 | 12 |
10,602 | @ Override public void dispatch ( ParameterResolveFactory parameterResolveFactory , ActionParam param , Route route , Object [ ] args ) { if ( ! route . isRegex ( ) ) return ; Matcher matcher = route . getMatcher ( ) ; String [ ] pathParameters = new String [ matcher . groupCount ( ) ] ; for ( int i = 1 , len = matcher . groupCount ( ) ; i <= len ; i ++ ) { pathParameters [ i - 1 ] = matcher . group ( i ) ; } Map < String , String > path = new HashMap <> ( ) ; route . getRegexRoute ( ) . getNames ( ) . forEach ( name -> CollectionKit . MapAdd ( path , name , matcher . group ( name ) ) ) ; param . getRequest ( ) . setPathNamedParameters ( path ) ; param . getRequest ( ) . setPathParameters ( pathParameters ) ; } | prepare to resolve path parameters | 203 | 6 |
10,603 | public File createDir ( File dir ) throws DataUtilException { if ( dir == null ) { throw new DataUtilException ( "Dir parameter can not be a null value" ) ; } if ( dir . exists ( ) ) { throw new DataUtilException ( "Directory already exists: " + dir . getAbsolutePath ( ) ) ; } if ( ! dir . mkdir ( ) ) { throw new DataUtilException ( "The result of File.mkDir() was false. Failed to create directory. : " + dir . getAbsolutePath ( ) ) ; } trackedFiles . add ( dir ) ; return dir ; } | Create and add a new directory | 136 | 6 |
10,604 | public void deleteAll ( ) { if ( trackedFiles . size ( ) == 0 ) { return ; } ArrayList < File > files = new ArrayList < File > ( trackedFiles ) ; Collections . sort ( files , filePathComparator ) ; for ( File file : files ) { if ( file . exists ( ) ) { if ( ! file . delete ( ) ) { throw new DataUtilException ( "Couldn't delete a tracked " + ( file . isFile ( ) ? "file" : "directory" + ": " ) + file . getAbsolutePath ( ) ) ; } } } trackedFiles . clear ( ) ; } | Delete all tracked files | 137 | 4 |
10,605 | public void removeTombstone ( final String path ) throws FedoraException { final HttpDelete delete = httpHelper . createDeleteMethod ( path + "/fcr:tombstone" ) ; try { final HttpResponse response = httpHelper . execute ( delete ) ; final StatusLine status = response . getStatusLine ( ) ; final String uri = delete . getURI ( ) . toString ( ) ; if ( status . getStatusCode ( ) == SC_NO_CONTENT ) { LOGGER . debug ( "triples updated successfully for resource {}" , uri ) ; } else if ( status . getStatusCode ( ) == SC_NOT_FOUND ) { LOGGER . error ( "resource {} does not exist, cannot update" , uri ) ; throw new NotFoundException ( "resource " + uri + " does not exist, cannot update" ) ; } else { LOGGER . error ( "error updating resource {}: {} {}" , uri , status . getStatusCode ( ) , status . getReasonPhrase ( ) ) ; throw new FedoraException ( "error updating resource " + uri + ": " + status . getStatusCode ( ) + " " + status . getReasonPhrase ( ) ) ; } } catch ( final FedoraException e ) { throw e ; } catch ( final Exception e ) { LOGGER . error ( "Error executing request" , e ) ; throw new FedoraException ( e ) ; } finally { delete . releaseConnection ( ) ; } } | Remove tombstone located at given path | 319 | 7 |
10,606 | protected Collection < String > getPropertyValues ( final Property property ) { final ExtendedIterator < Triple > iterator = graph . find ( Node . ANY , property . asNode ( ) , Node . ANY ) ; final Set < String > set = new HashSet <> ( ) ; while ( iterator . hasNext ( ) ) { final Node object = iterator . next ( ) . getObject ( ) ; if ( object . isLiteral ( ) ) { set . add ( object . getLiteralValue ( ) . toString ( ) ) ; } else if ( object . isURI ( ) ) { set . add ( object . getURI ( ) . toString ( ) ) ; } else { set . add ( object . toString ( ) ) ; } } return set ; } | Return all the values of a property | 164 | 7 |
10,607 | public static String generateRequestId ( ) { /* compute a random 256-bit string and hex-encode it */ final SecureRandom sr = new SecureRandom ( ) ; final byte [ ] bytes = new byte [ 32 ] ; sr . nextBytes ( bytes ) ; return hexEncode ( bytes ) ; } | Generate a request ID suitable for passing to SAMLClient . createAuthnRequest . | 64 | 18 |
10,608 | public final boolean isAssignableTo ( MimeType mimeType ) { if ( mimeType . getPrimaryType ( ) . equals ( "*" ) ) { // matches all return true ; } if ( ! mimeType . getPrimaryType ( ) . equalsIgnoreCase ( getPrimaryType ( ) ) ) { return false ; } String mtSec = mimeType . getSecondaryType ( ) ; return mtSec . equals ( "*" ) || mtSec . equalsIgnoreCase ( getSecondaryType ( ) ) ; } | Checks if this MIME type is a subtype of the provided MIME type . | 117 | 18 |
10,609 | @ SuppressWarnings ( "rawtypes" ) public List < ServletDefinition > initJawrSpringServlets ( ServletContext servletContext ) throws ServletException { List < ServletDefinition > jawrServletDefinitions = new ArrayList < ServletDefinition > ( ) ; ContextLoader contextLoader = new ContextLoader ( ) ; WebApplicationContext applicationCtx = contextLoader . initWebApplicationContext ( servletContext ) ; Map < ? , ? > jawrControllersMap = applicationCtx . getBeansOfType ( JawrSpringController . class ) ; Iterator < ? > entrySetIterator = jawrControllersMap . entrySet ( ) . iterator ( ) ; while ( entrySetIterator . hasNext ( ) ) { JawrSpringController jawrController = ( JawrSpringController ) ( ( Map . Entry ) entrySetIterator . next ( ) ) . getValue ( ) ; Map < String , Object > initParams = new HashMap < String , Object > ( ) ; initParams . putAll ( jawrController . getInitParams ( ) ) ; ServletConfig servletConfig = new MockServletConfig ( SPRING_DISPATCHER_SERVLET , servletContext , initParams ) ; MockJawrSpringServlet servlet = new MockJawrSpringServlet ( jawrController , servletConfig ) ; ServletDefinition servletDefinition = new ServletDefinition ( servlet , servletConfig ) ; jawrServletDefinitions . add ( servletDefinition ) ; } contextLoader . closeWebApplicationContext ( servletContext ) ; return jawrServletDefinitions ; } | Initialize the servlets which will handle the request to the JawrSpringController | 353 | 16 |
10,610 | public static Graph filterTriples ( final Iterator < Triple > triples , final Node ... properties ) { final Graph filteredGraph = new RandomOrderGraph ( RandomOrderGraph . createDefaultGraph ( ) ) ; final Sink < Triple > graphOutput = new SinkTriplesToGraph ( true , filteredGraph ) ; final RDFSinkFilter rdfFilter = new RDFSinkFilter ( graphOutput , properties ) ; rdfFilter . start ( ) ; while ( triples . hasNext ( ) ) { final Triple triple = triples . next ( ) ; rdfFilter . triple ( triple ) ; } rdfFilter . finish ( ) ; return filteredGraph ; } | Filter the triples | 142 | 4 |
10,611 | @ Override public List < ? extends TypeMirror > directSupertypes ( TypeMirror t ) { switch ( t . getKind ( ) ) { case DECLARED : DeclaredType dt = ( DeclaredType ) t ; TypeElement te = ( TypeElement ) dt . asElement ( ) ; List < TypeMirror > list = new ArrayList <> ( ) ; TypeElement superclass = ( TypeElement ) asElement ( te . getSuperclass ( ) ) ; if ( superclass != null ) { list . add ( 0 , superclass . asType ( ) ) ; } list . addAll ( te . getInterfaces ( ) ) ; return list ; case EXECUTABLE : case PACKAGE : throw new IllegalArgumentException ( t . getKind ( ) . name ( ) ) ; default : throw new UnsupportedOperationException ( t . getKind ( ) . name ( ) + " not supported yet" ) ; } } | The direct superclass is the class from whose implementation the implementation of the current class is derived . | 204 | 19 |
10,612 | protected Provider < ObjectMapper > getJacksonProvider ( ) { return new Provider < ObjectMapper > ( ) { @ Override public ObjectMapper get ( ) { final ObjectMapper mapper = new ObjectMapper ( ) ; mapper . registerModule ( new JodaModule ( ) ) ; mapper . disable ( SerializationFeature . WRITE_DATES_AS_TIMESTAMPS ) ; return mapper ; } } ; } | Override this method to provide your own Jackson provider . | 94 | 10 |
10,613 | public Injector injector ( final ServletContextEvent event ) { return ( Injector ) event . getServletContext ( ) . getAttribute ( Injector . class . getName ( ) ) ; } | This method can be called by classes extending SetupServer to retrieve the actual injector . This requires some inside knowledge on where it is stored but the actual key is not visible outside the guice packages . | 46 | 40 |
10,614 | private void writeParent ( Account account , XmlStreamWriter writer ) throws Exception { // Sequence block writer . writeStartElement ( "RDF:Seq" ) ; writer . writeAttribute ( "RDF:about" , account . getId ( ) ) ; for ( Account child : account . getChildren ( ) ) { logger . fine ( " Write-RDF:li: " + child . getId ( ) ) ; writer . writeStartElement ( "RDF:li" ) ; writer . writeAttribute ( "RDF:resource" , child . getId ( ) ) ; writer . writeEndElement ( ) ; } writer . writeEndElement ( ) ; // Descriptions of all elements including the parent writeDescription ( account , writer ) ; for ( Account child : account . getChildren ( ) ) { logger . fine ( "Write-RDF:Desc: " + child . getName ( ) ) ; writeDescription ( child , writer ) ; } // Recurse into the children for ( Account child : account . getChildren ( ) ) { if ( child . getChildren ( ) . size ( ) > 0 ) { writeParent ( child , writer ) ; } } } | Writes a parent node to the stream recursing into any children . | 248 | 15 |
10,615 | private void writeFFGlobalSettings ( Database db , XmlStreamWriter writer ) throws Exception { writer . writeStartElement ( "RDF:Description" ) ; writer . writeAttribute ( "RDF:about" , RDFDatabaseReader . FF_GLOBAL_SETTINGS_URI ) ; for ( String key : db . getGlobalSettings ( ) . keySet ( ) ) { writer . writeAttribute ( key , db . getGlobalSettings ( ) . get ( key ) ) ; } writer . writeEndElement ( ) ; } | Writes the firefox settings back . | 113 | 8 |
10,616 | public static boolean intersectsLineSegment ( Coordinate a , Coordinate b , Coordinate c , Coordinate d ) { // check single-point segment: these never intersect if ( ( a . getX ( ) == b . getX ( ) && a . getY ( ) == b . getY ( ) ) || ( c . getX ( ) == d . getX ( ) && c . getY ( ) == d . getY ( ) ) ) { return false ; } double c1 = cross ( a , c , a , b ) ; double c2 = cross ( a , b , c , d ) ; if ( c1 == 0 && c2 == 0 ) { // colinear, only intersecting if overlapping (touch is ok) double xmin = Math . min ( a . getX ( ) , b . getX ( ) ) ; double ymin = Math . min ( a . getY ( ) , b . getY ( ) ) ; double xmax = Math . max ( a . getX ( ) , b . getX ( ) ) ; double ymax = Math . max ( a . getY ( ) , b . getY ( ) ) ; // check first point of last segment in bounding box of first segment if ( c . getX ( ) > xmin && c . getX ( ) < xmax && c . getY ( ) > ymin && c . getY ( ) < ymax ) { return true ; // check last point of last segment in bounding box of first segment } else if ( d . getX ( ) > xmin && d . getX ( ) < xmax && d . getY ( ) > ymin && d . getY ( ) < ymax ) { return true ; // check same segment } else { return c . getX ( ) >= xmin && c . getX ( ) <= xmax && c . getY ( ) >= ymin && c . getY ( ) <= ymax & d . getX ( ) >= xmin && d . getX ( ) <= xmax && d . getY ( ) >= ymin && d . getY ( ) <= ymax ; } } if ( c2 == 0 ) { // segments are parallel but not colinear return false ; } // not parallel, classical test double u = c1 / c2 ; double t = cross ( a , c , c , d ) / c2 ; return ( t > 0 ) && ( t < 1 ) && ( u > 0 ) && ( u < 1 ) ; } | Calculates whether or not 2 line - segments intersect . The definition we use is that line segments intersect if they either cross or overlap . If they touch in 1 end point they do not intersect . This definition is most useful for checking polygon validity as touching rings in 1 point are allowed but crossing or overlapping not . | 544 | 64 |
10,617 | private static double cross ( Coordinate a1 , Coordinate a2 , Coordinate b1 , Coordinate b2 ) { return ( a2 . getX ( ) - a1 . getX ( ) ) * ( b2 . getY ( ) - b1 . getY ( ) ) - ( a2 . getY ( ) - a1 . getY ( ) ) * ( b2 . getX ( ) - b1 . getX ( ) ) ; } | cross - product of 2 vectors | 100 | 6 |
10,618 | public static double distance ( Coordinate c1 , Coordinate c2 ) { double a = c1 . getX ( ) - c2 . getX ( ) ; double b = c1 . getY ( ) - c2 . getY ( ) ; return Math . sqrt ( a * a + b * b ) ; } | Distance between 2 points . | 70 | 5 |
10,619 | public static double distance ( Coordinate c1 , Coordinate c2 , Coordinate c ) { return distance ( nearest ( c1 , c2 , c ) , c ) ; } | Distance between a point and a line segment . This method looks at the line segment c1 - c2 it does not regard it as a line . This means that the distance to c is calculated to a point between c1 and c2 . | 38 | 49 |
10,620 | public static Coordinate nearest ( Coordinate c1 , Coordinate c2 , Coordinate c ) { double len = distance ( c1 , c2 ) ; double u = ( c . getX ( ) - c1 . getX ( ) ) * ( c2 . getX ( ) - c1 . getX ( ) ) + ( c . getY ( ) - c1 . getY ( ) ) * ( c2 . getY ( ) - c1 . getY ( ) ) ; u = u / ( len * len ) ; if ( u < 0.00001 || u > 1 ) { // Shortest point not within LineSegment, so take closest end-point. double len1 = distance ( c , c1 ) ; double len2 = distance ( c , c2 ) ; if ( len1 < len2 ) { return c1 ; } return c2 ; } else { // Intersecting point is on the line, use the formula: P = P1 + u (P2 - P1) double x1 = c1 . getX ( ) + u * ( c2 . getX ( ) - c1 . getX ( ) ) ; double y1 = c1 . getY ( ) + u * ( c2 . getY ( ) - c1 . getY ( ) ) ; return new Coordinate ( x1 , y1 ) ; } } | Calculate which point on a line segment is nearest to the given coordinate . Will be perpendicular or one of the end - points . | 297 | 27 |
10,621 | public static boolean isXForwardedAllowed ( String remoteAddr ) { return isXForwardedAllowed ( ) && ( S . eq ( "all" , xForwardedAllowed ) || xForwardedAllowed . contains ( remoteAddr ) ) ; } | Does the remote address is allowed for x - forwarded header | 57 | 11 |
10,622 | public static String createId ( Account acc ) throws Exception { return Account . createId ( acc . getName ( ) + acc . getDesc ( ) + ( new Random ( ) ) . nextLong ( ) + Runtime . getRuntime ( ) . freeMemory ( ) ) ; } | Creates and _returns_ an ID from data in an account . | 58 | 15 |
10,623 | public Account getChild ( int index ) throws IndexOutOfBoundsException { if ( index < 0 || index >= children . size ( ) ) throw new IndexOutOfBoundsException ( "Illegal child index, " + index ) ; return children . get ( index ) ; } | Gets a specifically indexed child . | 59 | 7 |
10,624 | public boolean hasChild ( Account account ) { for ( Account child : children ) { if ( child . equals ( account ) ) return true ; } return false ; } | Tests if an account is a direct child of this account . | 34 | 13 |
10,625 | public int compareTo ( Account o ) { if ( this . isFolder ( ) && ! o . isFolder ( ) ) return - 1 ; else if ( ! this . isFolder ( ) && o . isFolder ( ) ) return 1 ; // First ignore case, if they equate, use case. int result = name . compareToIgnoreCase ( o . name ) ; if ( result == 0 ) return name . compareTo ( o . name ) ; else return result ; } | Implements the Comparable< ; Account> ; interface this is based first on if the account is a folder or not . This is so that during sorting all folders are first in the list . Finally it is based on the name . | 101 | 50 |
10,626 | @ SuppressWarnings ( "UnusedDeclaration" ) public void setPatterns ( Iterable < AccountPatternData > patterns ) { this . patterns . clear ( ) ; for ( AccountPatternData data : patterns ) { this . patterns . add ( new AccountPatternData ( data ) ) ; } } | This will make a deep clone of the passed in Iterable . This will also replace any patterns already set . | 65 | 22 |
10,627 | public void close ( ) throws DiffException { try { if ( writer != null ) { writer . flush ( ) ; writer . close ( ) ; } } catch ( IOException e ) { throw new DiffException ( "Failed to close report file" , e ) ; } } | Close the file report instance and it s underlying writer | 58 | 10 |
10,628 | public void swapAccounts ( Database other ) { Account otherRoot = other . rootAccount ; other . rootAccount = rootAccount ; rootAccount = otherRoot ; boolean otherDirty = other . dirty ; other . dirty = dirty ; dirty = otherDirty ; HashMap < String , String > otherGlobalSettings = other . globalSettings ; other . globalSettings = globalSettings ; globalSettings = otherGlobalSettings ; } | Is is so that the after an database is loaded we can reuse this object This does not swap listeners . | 86 | 21 |
10,629 | public void addAccount ( Account parent , Account child ) throws Exception { // Check to see if the account physically already exists - there is something funny with // some Firefox RDF exports where an RDF:li node gets duplicated multiple times. for ( Account dup : parent . getChildren ( ) ) { if ( dup == child ) { logger . warning ( "Duplicate RDF:li=" + child . getId ( ) + " detected. Dropping duplicate" ) ; return ; } } int iterationCount = 0 ; final int maxIteration = 0x100000 ; // if we can't find a hash in 1 million iterations, something is wrong while ( findAccountById ( child . getId ( ) ) != null && ( iterationCount ++ < maxIteration ) ) { logger . warning ( "ID collision detected on '" + child . getId ( ) + "', attempting to regenerate ID. iteration=" + iterationCount ) ; child . setId ( Account . createId ( child ) ) ; } if ( iterationCount >= maxIteration ) { throw new Exception ( "Could not genererate a unique ID in " + iterationCount + " iterations, this is really rare. I know it's lame, but change the description and try again." ) ; } // add to new parent parent . getChildren ( ) . add ( child ) ; sendAccountAdded ( parent , child ) ; setDirty ( true ) ; } | Adds an account to a parent . This will first check to see if the account already has a parent and if so remove it from that parent before adding it to the new parent . | 299 | 36 |
10,630 | public void removeAccount ( Account accountToDelete ) { // Thou shalt not delete root if ( accountToDelete . getId ( ) . equals ( rootAccount . getId ( ) ) ) return ; Account parent = findParent ( accountToDelete ) ; if ( parent != null ) { removeAccount ( parent , accountToDelete ) ; setDirty ( true ) ; } } | Removes an account from a parent account . | 78 | 9 |
10,631 | private void removeAccount ( Account parent , Account child ) { parent . getChildren ( ) . remove ( child ) ; sendAccountRemoved ( parent , child ) ; } | Internal routine to remove a child from a parent . Notifies the listeners of the removal | 34 | 17 |
10,632 | public void setGlobalSetting ( String name , String value ) { String oldValue ; // Avoid redundant setting if ( globalSettings . containsKey ( name ) ) { oldValue = globalSettings . get ( name ) ; if ( value . compareTo ( oldValue ) == 0 ) return ; } globalSettings . put ( name , value ) ; setDirty ( true ) ; } | Sets a firefox global setting . This allows any name and should be avoided . It is used by the RDF reader . | 78 | 26 |
10,633 | public String getGlobalSetting ( GlobalSettingKey key ) { if ( globalSettings . containsKey ( key . toString ( ) ) ) return globalSettings . get ( key . toString ( ) ) ; return key . getDefault ( ) ; } | The preferred way of getting a global setting value . | 51 | 10 |
10,634 | private static int checkResult ( int result ) { if ( exceptionsEnabled && result != curandStatus . CURAND_STATUS_SUCCESS ) { throw new CudaException ( curandStatus . stringFor ( result ) ) ; } return result ; } | If the given result is not curandStatus . CURAND_STATUS_SUCCESS and exceptions have been enabled this method will throw a CudaException with an error message that corresponds to the given result code . Otherwise the given result is simply returned . | 55 | 53 |
10,635 | public final void nameArgument ( String name , int index ) { VariableElement lv = getLocalVariable ( index ) ; if ( lv instanceof UpdateableElement ) { UpdateableElement ue = ( UpdateableElement ) lv ; ue . setSimpleName ( El . getName ( name ) ) ; } else { throw new IllegalArgumentException ( "local variable at index " + index + " cannot be named" ) ; } } | Names an argument | 95 | 3 |
10,636 | public VariableElement getLocalVariable ( int index ) { int idx = 0 ; for ( VariableElement lv : localVariables ) { if ( idx == index ) { return lv ; } if ( Typ . isCategory2 ( lv . asType ( ) ) ) { idx += 2 ; } else { idx ++ ; } } throw new IllegalArgumentException ( "local variable at index " + index + " not found" ) ; } | Returns local variable at index . Note! long and double take two positions . | 97 | 15 |
10,637 | public String getLocalName ( int index ) { VariableElement lv = getLocalVariable ( index ) ; return lv . getSimpleName ( ) . toString ( ) ; } | Returns the name of local variable at index | 38 | 8 |
10,638 | public TypeMirror getLocalType ( String name ) { VariableElement lv = getLocalVariable ( name ) ; return lv . asType ( ) ; } | returns the type of local variable named name . | 34 | 10 |
10,639 | public String getLocalDescription ( int index ) { StringWriter sw = new StringWriter ( ) ; El . printElements ( sw , getLocalVariable ( index ) ) ; return sw . toString ( ) ; } | return a descriptive text about local variable named name . | 45 | 10 |
10,640 | public void loadDefault ( TypeMirror type ) throws IOException { if ( type . getKind ( ) != TypeKind . VOID ) { if ( Typ . isPrimitive ( type ) ) { tconst ( type , 0 ) ; } else { aconst_null ( ) ; } } } | Load default value to stack depending on type | 64 | 8 |
10,641 | public void startSubroutine ( String target ) throws IOException { if ( subroutine != null ) { throw new IllegalStateException ( "subroutine " + subroutine + " not ended when " + target + "started" ) ; } subroutine = target ; if ( ! hasLocalVariable ( SUBROUTINERETURNADDRESSNAME ) ) { addVariable ( SUBROUTINERETURNADDRESSNAME , Typ . ReturnAddress ) ; } fixAddress ( target ) ; tstore ( SUBROUTINERETURNADDRESSNAME ) ; } | Compiles the subroutine start . Use endSubroutine to end that subroutine . | 125 | 20 |
10,642 | public TypeMirror typeForCount ( int count ) { if ( count <= Byte . MAX_VALUE ) { return Typ . Byte ; } if ( count <= Short . MAX_VALUE ) { return Typ . Short ; } if ( count <= Integer . MAX_VALUE ) { return Typ . Int ; } return Typ . Long ; } | Return a integral class able to support count values | 69 | 9 |
10,643 | @ Override public void fixAddress ( String name ) throws IOException { super . fixAddress ( name ) ; if ( debugMethod != null ) { int position = position ( ) ; tload ( "this" ) ; ldc ( position ) ; ldc ( name ) ; invokevirtual ( debugMethod ) ; } } | Labels a current position | 67 | 5 |
10,644 | public Route matchRoute ( String url ) { if ( hashRoute . containsKey ( url ) ) { return new Route ( hashRoute . get ( url ) . get ( 0 ) , null ) ; } for ( RegexRoute route : regexRoute ) { Matcher matcher = route . getPattern ( ) . matcher ( url ) ; if ( matcher . matches ( ) ) { return new Route ( route , matcher ) ; } } return null ; } | simple match route | 97 | 3 |
10,645 | public void addAttributes ( List < Attribute > attributes ) { for ( Attribute attribute : attributes ) { addAttribute ( attribute . getName ( ) , attribute . getValue ( ) ) ; } } | Add element attributes | 42 | 3 |
10,646 | public void addAttribute ( String attributeName , String attributeValue ) throws XmlModelException { String name = attributeName . trim ( ) ; String value = attributeValue . trim ( ) ; if ( attributesMap . containsKey ( name ) ) { throw new XmlModelException ( "Duplicate attribute: " + name ) ; } attributeNames . add ( name ) ; attributesMap . put ( name , new Attribute ( name , value ) ) ; } | Add a new element attribute | 96 | 5 |
10,647 | private static void tc ( Map < M , Set < M > > index ) { final Map < String , Object [ ] > warnings = new HashMap <> ( ) ; for ( Entry < M , Set < M > > entry : index . entrySet ( ) ) { final M src = entry . getKey ( ) ; final Set < M > dependents = entry . getValue ( ) ; final Queue < M > queue = new LinkedList < M > ( dependents ) ; while ( ! queue . isEmpty ( ) ) { final M key = queue . poll ( ) ; if ( ! index . containsKey ( key ) ) { continue ; } for ( M addition : index . get ( key ) ) { if ( ! dependents . contains ( addition ) ) { dependents . add ( addition ) ; queue . add ( addition ) ; warnings . put ( src + "|" + addition + "|" + key , new Object [ ] { src , addition , key } ) ; } } } } for ( final Object [ ] args : warnings . values ( ) ) { StructuredLog . ImpliedTransitiveDependency . warn ( log , args ) ; } } | Compute the transitive closure of the dependencies | 250 | 9 |
10,648 | private < I > void hear ( Class < ? super I > type , TypeEncounter < I > encounter ) { if ( type == null || type . getPackage ( ) . getName ( ) . startsWith ( JAVA_PACKAGE ) ) { return ; } for ( Method method : type . getDeclaredMethods ( ) ) { if ( method . isAnnotationPresent ( annotationType ) ) { if ( method . getParameterTypes ( ) . length != 0 ) { encounter . addError ( "Annotated methods with @%s must not accept any argument, found %s" , annotationType . getName ( ) , method ) ; } hear ( method , encounter ) ; } } hear ( type . getSuperclass ( ) , encounter ) ; } | Allows traverse the input type hierarchy . | 162 | 7 |
10,649 | public ResultSetStreamer require ( String column , Assertion assertion ) { if ( _requires == Collections . EMPTY_MAP ) _requires = new HashMap < String , Assertion > ( ) ; _requires . put ( column , assertion ) ; return this ; } | Requires a data column to satisfy an assertion . | 57 | 9 |
10,650 | public ResultSetStreamer exclude ( String column , Assertion assertion ) { if ( _excludes == Collections . EMPTY_MAP ) _excludes = new HashMap < String , Assertion > ( ) ; _excludes . put ( column , assertion ) ; return this ; } | Excludes rows whose data columns satisfy an assertion . | 60 | 10 |
10,651 | public static < T extends Executable > Predicate < T > executableIsSynthetic ( ) { return candidate -> candidate != null && candidate . isSynthetic ( ) ; } | Checks if a candidate executable is synthetic . | 38 | 9 |
10,652 | public static < T extends Executable > Predicate < T > executableBelongsToClass ( Class < ? > reference ) { return candidate -> candidate != null && reference . equals ( candidate . getDeclaringClass ( ) ) ; } | Checks if a candidate executable does belong to the specified class . | 48 | 13 |
10,653 | public static < T extends Executable > Predicate < T > executableBelongsToClassAssignableTo ( Class < ? > reference ) { return candidate -> candidate != null && reference . isAssignableFrom ( candidate . getDeclaringClass ( ) ) ; } | Checks if a candidate executable does belong to a class assignable as the specified class . | 56 | 18 |
10,654 | public static < T extends Executable > Predicate < T > executableIsEquivalentTo ( T reference ) { Predicate < T > predicate = candidate -> candidate != null && candidate . getName ( ) . equals ( reference . getName ( ) ) && executableHasSameParameterTypesAs ( reference ) . test ( candidate ) ; if ( reference instanceof Method ) { predicate . and ( candidate -> candidate instanceof Method && ( ( Method ) candidate ) . getReturnType ( ) . equals ( ( ( Method ) reference ) . getReturnType ( ) ) ) ; } return predicate ; } | Checks if a candidate executable is equivalent to the specified reference executable . | 122 | 14 |
10,655 | public static < T extends Executable > Predicate < T > executableHasSameParameterTypesAs ( T reference ) { return candidate -> { if ( candidate == null ) { return false ; } Class < ? > [ ] candidateParameterTypes = candidate . getParameterTypes ( ) ; Class < ? > [ ] referenceParameterTypes = reference . getParameterTypes ( ) ; if ( candidateParameterTypes . length != referenceParameterTypes . length ) { return false ; } for ( int i = 0 ; i < candidateParameterTypes . length ; i ++ ) { if ( ! candidateParameterTypes [ i ] . equals ( referenceParameterTypes [ i ] ) ) { return false ; } } return true ; } ; } | Checks if a candidate executable has the same parameter type as the specified reference executable . | 145 | 17 |
10,656 | @ Override public void run ( ) { try { try { turnsControl . waitTurns ( 1 , "Robot starting" ) ; // block at the beginning so that all // robots start at the // same time } catch ( BankInterruptedException exc ) { log . trace ( "[run] Interrupted before starting" ) ; } assert getData ( ) . isEnabled ( ) : "Robot is disabled" ; mainLoop ( ) ; log . debug ( "[run] Robot terminated gracefully" ) ; } catch ( Exception | Error all ) { log . error ( "[run] Problem running robot " + this , all ) ; die ( "Execution Error -- " + all ) ; } } | The main loop of the robot | 146 | 6 |
10,657 | @ Override public void die ( String reason ) { log . info ( "[die] Robot {} died with reason: {}" , serialNumber , reason ) ; if ( alive ) { // if not alive it means it was killed at creation alive = false ; interrupted = true ; // to speed up death world . remove ( Robot . this ) ; } } | Kills the robot and removes it from the board | 73 | 10 |
10,658 | protected List < FileStatus > listStatus ( JobContext job ) throws IOException { List < FileStatus > result = new ArrayList < FileStatus > ( ) ; Path [ ] dirs = getInputPaths ( job ) ; if ( dirs . length == 0 ) { throw new IOException ( "No input paths specified in job" ) ; } // Get tokens for all the required FileSystems.. TokenCache . obtainTokensForNamenodes ( job . getCredentials ( ) , dirs , job . getConfiguration ( ) ) ; List < IOException > errors = new ArrayList < IOException > ( ) ; for ( Path p : dirs ) { FileSystem fs = p . getFileSystem ( job . getConfiguration ( ) ) ; final SmilePathFilter filter = new SmilePathFilter ( ) ; FileStatus [ ] matches = fs . globStatus ( p , filter ) ; if ( matches == null ) { errors . add ( new IOException ( "Input path does not exist: " + p ) ) ; } else if ( matches . length == 0 ) { errors . add ( new IOException ( "Input Pattern " + p + " matches 0 files" ) ) ; } else { for ( FileStatus globStat : matches ) { if ( globStat . isDir ( ) ) { Collections . addAll ( result , fs . listStatus ( globStat . getPath ( ) , filter ) ) ; } else { result . add ( globStat ) ; } } } } if ( ! errors . isEmpty ( ) ) { throw new InvalidInputException ( errors ) ; } return result ; } | List input directories . | 338 | 4 |
10,659 | protected void checkInputClass ( final Object domainObject ) { final Class < ? > actualInputType = domainObject . getClass ( ) ; if ( ! ( expectedInputType . isAssignableFrom ( actualInputType ) ) ) { throw new IllegalArgumentException ( "The input document is required to be of type: " + expectedInputType . getName ( ) ) ; } } | Optional hook ; default implementation checks that the input type is of the correct type . | 82 | 16 |
10,660 | public void setTimeout ( long timeout , TimeUnit unit ) { this . timeout = TimeUnit . MILLISECONDS . convert ( timeout , unit ) ; } | Change the idle timeout . | 34 | 5 |
10,661 | public final void sendObjectToSocket ( Object o ) { Session sess = this . getSession ( ) ; if ( sess != null ) { String json ; try { json = this . mapper . writeValueAsString ( o ) ; } catch ( JsonProcessingException e ) { ClientSocketAdapter . LOGGER . error ( "Failed to serialize object" , e ) ; return ; } sess . getRemote ( ) . sendString ( json , new WriteCallback ( ) { @ Override public void writeSuccess ( ) { ClientSocketAdapter . LOGGER . info ( "Send data to socket" ) ; } @ Override public void writeFailed ( Throwable x ) { ClientSocketAdapter . LOGGER . error ( "Error sending message to socket" , x ) ; } } ) ; } } | send the given object to the server using JSON serialization | 173 | 11 |
10,662 | protected final < T > T readMessage ( String message , Class < T > clazz ) { if ( ( message == null ) || message . isEmpty ( ) ) { ClientSocketAdapter . LOGGER . info ( "Got empty session data" ) ; return null ; } try { return this . mapper . readValue ( message , clazz ) ; } catch ( IOException e1 ) { ClientSocketAdapter . LOGGER . info ( "Got invalid session data" , e1 ) ; return null ; } } | reads the received string into the given class by parsing JSON | 108 | 11 |
10,663 | public ByteBuffer makeByteBuffer ( InputStream in ) throws IOException { int limit = in . available ( ) ; if ( limit < 1024 ) limit = 1024 ; ByteBuffer result = byteBufferCache . get ( limit ) ; int position = 0 ; while ( in . available ( ) != 0 ) { if ( position >= limit ) // expand buffer result = ByteBuffer . allocate ( limit <<= 1 ) . put ( ( ByteBuffer ) result . flip ( ) ) ; int count = in . read ( result . array ( ) , position , limit - position ) ; if ( count < 0 ) break ; result . position ( position += count ) ; } return ( ByteBuffer ) result . flip ( ) ; } | Make a byte buffer from an input stream . | 148 | 9 |
10,664 | public void add ( Collection < BrowserApplication > browserApplications ) { for ( BrowserApplication browserApplication : browserApplications ) this . browserApplications . put ( browserApplication . getId ( ) , browserApplication ) ; } | Adds the browser application list to the browser applications for the account . | 43 | 13 |
10,665 | public static Object getProperty ( Object object , String name ) throws NoSuchFieldException { try { Matcher matcher = ARRAY_INDEX . matcher ( name ) ; if ( matcher . matches ( ) ) { object = getProperty ( object , matcher . group ( 1 ) ) ; if ( object . getClass ( ) . isArray ( ) ) { return Array . get ( object , Integer . parseInt ( matcher . group ( 2 ) ) ) ; } else { return ( ( List ) object ) . get ( Integer . parseInt ( matcher . group ( 2 ) ) ) ; } } else { int dot = name . lastIndexOf ( ' ' ) ; if ( dot > 0 ) { object = getProperty ( object , name . substring ( 0 , dot ) ) ; name = name . substring ( dot + 1 ) ; } return Beans . getKnownField ( object . getClass ( ) , name ) . get ( object ) ; } } catch ( NoSuchFieldException x ) { throw x ; } catch ( Exception x ) { throw new IllegalArgumentException ( x . getMessage ( ) + ": " + name , x ) ; } } | Reports a property . | 251 | 4 |
10,666 | @ SuppressWarnings ( "unchecked" ) public static void setProperty ( Object object , String name , String text ) throws NoSuchFieldException { try { // need to get to the field for any typeinfo annotation, so here we go ... int length = name . lastIndexOf ( ' ' ) ; if ( length > 0 ) { object = getProperty ( object , name . substring ( 0 , length ) ) ; name = name . substring ( length + 1 ) ; } length = name . length ( ) ; Matcher matcher = ARRAY_INDEX . matcher ( name ) ; for ( Matcher m = matcher ; m . matches ( ) ; m = ARRAY_INDEX . matcher ( name ) ) { name = m . group ( 1 ) ; } Field field = Beans . getKnownField ( object . getClass ( ) , name ) ; if ( name . length ( ) != length ) { int index = Integer . parseInt ( matcher . group ( 2 ) ) ; object = getProperty ( object , matcher . group ( 1 ) ) ; if ( object . getClass ( ) . isArray ( ) ) { Array . set ( object , index , new ValueOf ( object . getClass ( ) . getComponentType ( ) , field . getAnnotation ( typeinfo . class ) ) . invoke ( text ) ) ; } else { ( ( List ) object ) . set ( index , new ValueOf ( field . getAnnotation ( typeinfo . class ) . value ( ) [ 0 ] ) . invoke ( text ) ) ; } } else { field . set ( object , new ValueOf ( field . getType ( ) , field . getAnnotation ( typeinfo . class ) ) . invoke ( text ) ) ; } } catch ( NoSuchFieldException x ) { throw x ; } catch ( Exception x ) { throw new IllegalArgumentException ( x . getMessage ( ) + ": " + name , x ) ; } } | Updates a property . | 421 | 5 |
10,667 | @ SafeVarargs public static < T > T [ ] concat ( T [ ] first , T [ ] ... rest ) { int length = first . length ; for ( T [ ] array : rest ) { length += array . length ; } T [ ] result = Arrays . copyOf ( first , length ) ; int offset = first . length ; for ( T [ ] array : rest ) { System . arraycopy ( array , 0 , result , offset , array . length ) ; offset += array . length ; } return result ; } | Concatenates several reference arrays . | 113 | 8 |
10,668 | public Iterable < Di18n > queryByBaseBundle ( java . lang . String baseBundle ) { return queryByField ( null , Di18nMapper . Field . BASEBUNDLE . getFieldName ( ) , baseBundle ) ; } | query - by method for field baseBundle | 57 | 9 |
10,669 | public Iterable < Di18n > queryByKey ( java . lang . String key ) { return queryByField ( null , Di18nMapper . Field . KEY . getFieldName ( ) , key ) ; } | query - by method for field key | 47 | 7 |
10,670 | public Iterable < Di18n > queryByLocale ( java . lang . String locale ) { return queryByField ( null , Di18nMapper . Field . LOCALE . getFieldName ( ) , locale ) ; } | query - by method for field locale | 49 | 7 |
10,671 | public Iterable < Di18n > queryByLocalizedMessage ( java . lang . String localizedMessage ) { return queryByField ( null , Di18nMapper . Field . LOCALIZEDMESSAGE . getFieldName ( ) , localizedMessage ) ; } | query - by method for field localizedMessage | 58 | 8 |
10,672 | public static String maskExcept ( final String s , final int unmaskedLength , final char maskChar ) { if ( s == null ) { return null ; } final boolean maskLeading = unmaskedLength > 0 ; final int length = s . length ( ) ; final int maskedLength = Math . max ( 0 , length - Math . abs ( unmaskedLength ) ) ; if ( maskedLength > 0 ) { final String mask = StringUtils . repeat ( maskChar , maskedLength ) ; if ( maskLeading ) { return StringUtils . overlay ( s , mask , 0 , maskedLength ) ; } return StringUtils . overlay ( s , mask , length - maskedLength , length ) ; } return s ; } | Returns a masked string leaving only the given number of characters unmasked . | 155 | 15 |
10,673 | public static String replaceNonPrintableControlCharacters ( final String value ) { if ( value == null || value . length ( ) == 0 ) { return value ; } boolean changing = false ; for ( int i = 0 , length = value . length ( ) ; i < length ; i ++ ) { final char ch = value . charAt ( i ) ; if ( ch < 32 && ch != ' ' && ch != ' ' && ch != ' ' ) { changing = true ; break ; } } if ( ! changing ) { return value ; } final StringBuilder buf = new StringBuilder ( value ) ; for ( int i = 0 , length = buf . length ( ) ; i < length ; i ++ ) { final char ch = buf . charAt ( i ) ; if ( ch < 32 && ch != ' ' && ch != ' ' && ch != ' ' ) { buf . setCharAt ( i , ' ' ) ; } } // return cleaned string return buf . toString ( ) ; } | Returns a string where non - printable control characters are replaced by whitespace . | 210 | 16 |
10,674 | public static String shortUuid ( ) { // source: java.util.UUID.randomUUID() final byte [ ] randomBytes = new byte [ 16 ] ; UUID_GENERATOR . nextBytes ( randomBytes ) ; randomBytes [ 6 ] = ( byte ) ( randomBytes [ 6 ] & 0x0f ) ; // clear version randomBytes [ 6 ] = ( byte ) ( randomBytes [ 6 ] | 0x40 ) ; // set to version 4 randomBytes [ 8 ] = ( byte ) ( randomBytes [ 8 ] & 0x3f ) ; // clear variant randomBytes [ 8 ] = ( byte ) ( randomBytes [ 8 ] | 0x80 ) ; // set to IETF variant // all base 64 encoding schemes use A-Z, a-z, and 0-9 for the first 62 characters. for the // last 2 characters, we use hyphen and underscore, which are URL safe return BaseEncoding . base64Url ( ) . omitPadding ( ) . encode ( randomBytes ) ; } | Returns a short UUID which is encoding use base 64 characters instead of hexadecimal . This saves 10 bytes per UUID . | 220 | 27 |
10,675 | public static List < String > splitToList ( final String value ) { if ( ! StringUtils . isEmpty ( value ) ) { return COMMA_SPLITTER . splitToList ( value ) ; } return Collections . < String > emptyList ( ) ; } | Parses a comma - separated string and returns a list of String values . | 58 | 16 |
10,676 | public static String trimWhitespace ( final String s ) { if ( s == null || s . length ( ) == 0 ) { return s ; } final int length = s . length ( ) ; int end = length ; int start = 0 ; while ( start < end && Character . isWhitespace ( s . charAt ( start ) ) ) { start ++ ; } while ( start < end && Character . isWhitespace ( s . charAt ( end - 1 ) ) ) { end -- ; } return start > 0 || end < length ? s . substring ( start , end ) : s ; } | Strip leading and trailing whitespace from a String . | 130 | 11 |
10,677 | public static String trimWhitespaceToNull ( final String s ) { final String result = trimWhitespace ( s ) ; return StringUtils . isEmpty ( result ) ? null : s ; } | Strip leading and trailing whitespace from a String . If the resulting string is empty this method returns null . | 43 | 22 |
10,678 | public List < ServiceReference > getReferences ( String resourceType ) { List < ServiceReference > references = new ArrayList < ServiceReference > ( ) ; if ( containsKey ( resourceType ) ) { references . addAll ( get ( resourceType ) ) ; Collections . sort ( references , new Comparator < ServiceReference > ( ) { @ Override public int compare ( ServiceReference r0 , ServiceReference r1 ) { Integer p0 = OsgiUtil . toInteger ( r0 . getProperty ( ComponentBindingsProvider . PRIORITY ) , 0 ) ; Integer p1 = OsgiUtil . toInteger ( r1 . getProperty ( ComponentBindingsProvider . PRIORITY ) , 0 ) ; return - 1 * p0 . compareTo ( p1 ) ; } } ) ; } return references ; } | Gets the ComponentBindingProvider references for the specified resource type . | 172 | 14 |
10,679 | public void registerComponentBindingsProvider ( ServiceReference reference ) { log . info ( "registerComponentBindingsProvider" ) ; log . info ( "Registering Component Bindings Provider {} - {}" , new Object [ ] { reference . getProperty ( Constants . SERVICE_ID ) , reference . getProperty ( Constants . SERVICE_PID ) } ) ; String [ ] resourceTypes = OsgiUtil . toStringArray ( reference . getProperty ( ComponentBindingsProvider . RESOURCE_TYPE_PROP ) , new String [ 0 ] ) ; for ( String resourceType : resourceTypes ) { if ( ! this . containsKey ( resourceType ) ) { put ( resourceType , new HashSet < ServiceReference > ( ) ) ; } log . debug ( "Adding to resource type {}" , resourceType ) ; get ( resourceType ) . add ( reference ) ; } } | Registers the ComponentBindingsProvider specified by the ServiceReference . | 186 | 13 |
10,680 | public void unregisterComponentBindingsProvider ( ServiceReference reference ) { log . info ( "unregisterComponentBindingsProvider" ) ; String [ ] resourceTypes = OsgiUtil . toStringArray ( reference . getProperty ( ComponentBindingsProvider . RESOURCE_TYPE_PROP ) , new String [ 0 ] ) ; for ( String resourceType : resourceTypes ) { if ( ! this . containsKey ( resourceType ) ) { continue ; } get ( resourceType ) . remove ( reference ) ; } } | UnRegisters the ComponentBindingsProvider specified by the ServiceReference . | 108 | 14 |
10,681 | public ComponentFactory < T , E > toCreate ( BiFunction < Constructor , Object [ ] , Object > createFunction ) { return new ComponentFactory <> ( this . annotationType , this . classElement , this . contextConsumer , createFunction ) ; } | Sets the function used to create the objects . | 54 | 10 |
10,682 | public ComponentFactory < T , E > toConfigure ( BiConsumer < Context , Annotation > consumer ) { return new ComponentFactory <> ( this . annotationType , this . classElement , consumer , this . createFunction ) ; } | Adds more rules to the context by passing a consumer that will be invoked before creating the component . | 49 | 19 |
10,683 | public List < E > createAll ( AnnotatedElement element ) { List < E > result = new ArrayList <> ( ) ; for ( Annotation annotation : element . getAnnotations ( ) ) { create ( annotation ) . ifPresent ( result :: add ) ; } return result ; } | Creates a list of components based on the annotations of the given element . | 62 | 15 |
10,684 | public static String getVersion ( ) { String version = null ; // try to load from maven properties first try { Properties p = new Properties ( ) ; InputStream is = VersionHelper . class . getResourceAsStream ( "/META-INF/maven/io.redlink/redlink-sdk-java/pom.properties" ) ; if ( is != null ) { p . load ( is ) ; version = p . getProperty ( "version" , "" ) ; } } catch ( Exception e ) { // ignore } // fallback to using Java API if ( version == null ) { Package aPackage = VersionHelper . class . getPackage ( ) ; if ( aPackage != null ) { version = aPackage . getImplementationVersion ( ) ; if ( version == null ) { version = aPackage . getSpecificationVersion ( ) ; } } } // fallback to read pom.xml on testing if ( version == null ) { final MavenXpp3Reader reader = new MavenXpp3Reader ( ) ; try { Model model = reader . read ( new FileReader ( new File ( "pom.xml" ) ) ) ; version = model . getVersion ( ) ; } catch ( IOException | XmlPullParserException e ) { // ignore } } return version ; } | Get artifact current version | 279 | 4 |
10,685 | protected static String formatApiVersion ( String version ) { if ( StringUtils . isBlank ( version ) ) { return VERSION ; } else { final Matcher matcher = VERSION_PATTERN . matcher ( version ) ; if ( matcher . matches ( ) ) { return String . format ( "%s.%s" , matcher . group ( 1 ) , matcher . group ( 2 ) ) ; } else { return VERSION ; } } } | Build a proper api version | 101 | 5 |
10,686 | @ Override public int numSheets ( ) { int ret = - 1 ; if ( workbook != null ) ret = workbook . getNumberOfSheets ( ) ; else if ( writableWorkbook != null ) ret = writableWorkbook . getNumberOfSheets ( ) ; return ret ; } | Returns the number of worksheets in the given workbook . | 66 | 13 |
10,687 | @ Override public String [ ] getSheetNames ( ) { String [ ] ret = null ; if ( workbook != null ) ret = workbook . getSheetNames ( ) ; else if ( writableWorkbook != null ) ret = writableWorkbook . getSheetNames ( ) ; return ret ; } | Returns the list of worksheet names from the given Excel XLS file . | 68 | 15 |
10,688 | @ Override public XlsWorksheet getSheet ( String name ) { XlsWorksheet ret = null ; if ( workbook != null ) { Sheet sheet = workbook . getSheet ( name ) ; if ( sheet != null ) ret = new XlsWorksheet ( sheet ) ; } else if ( writableWorkbook != null ) { Sheet sheet = writableWorkbook . getSheet ( name ) ; if ( sheet != null ) ret = new XlsWorksheet ( sheet ) ; } return ret ; } | Returns the worksheet with the given name in the workbook . | 111 | 13 |
10,689 | @ Override public XlsWorksheet createSheet ( FileColumn [ ] columns , List < String [ ] > lines , String sheetName ) throws IOException { // Create the worksheet and add the cells WritableSheet sheet = writableWorkbook . createSheet ( sheetName , 9999 ) ; // Append sheet try { appendRows ( sheet , columns , lines , sheetName ) ; } catch ( WriteException e ) { throw new IOException ( e ) ; } // Set the column to autosize int numColumns = sheet . getColumns ( ) ; for ( int i = 0 ; i < numColumns ; i ++ ) { CellView column = sheet . getColumnView ( i ) ; column . setAutosize ( true ) ; if ( columns != null && i < columns . length ) { CellFormat format = columns [ i ] . getCellFormat ( ) ; if ( format != null ) column . setFormat ( format ) ; } sheet . setColumnView ( i , column ) ; } return new XlsWorksheet ( sheet ) ; } | Creates a sheet in the workbook with the given name and lines of data . | 228 | 17 |
10,690 | @ Override public void appendToSheet ( FileColumn [ ] columns , List < String [ ] > lines , String sheetName ) throws IOException { try { XlsWorksheet sheet = getSheet ( sheetName ) ; if ( sheet != null ) appendRows ( ( WritableSheet ) sheet . getSheet ( ) , columns , lines , sheetName ) ; } catch ( WriteException e ) { throw new IOException ( e ) ; } } | Adds the given lines of data to an existing sheet in the workbook . | 98 | 15 |
10,691 | private void appendRows ( WritableSheet sheet , FileColumn [ ] columns , List < String [ ] > lines , String sheetName ) throws WriteException { WritableFont headerFont = new WritableFont ( WritableFont . ARIAL , 10 , WritableFont . BOLD ) ; WritableCellFormat headerFormat = new WritableCellFormat ( headerFont ) ; WritableCellFeatures features = new WritableCellFeatures ( ) ; features . removeDataValidation ( ) ; int size = sheet . getRows ( ) ; for ( int i = 0 ; i < lines . size ( ) ; i ++ ) { String [ ] line = lines . get ( i ) ; if ( ( i + size ) > MAX_ROWS ) { logger . severe ( "the worksheet '" + sheetName + "' has exceeded the maximum rows and will be truncated" ) ; break ; } for ( int j = 0 ; j < line . length ; j ++ ) { WritableCell cell = null ; String data = line [ j ] ; if ( data == null ) data = "" ; // Get a cell with the correct formatting if ( columns != null && j < columns . length ) { cell = getCell ( columns [ j ] , j , i + size , data ) ; } else // Try to figure out the type of the column { try { double num = Double . parseDouble ( data ) ; cell = new Number ( j , i + size , num ) ; } catch ( NumberFormatException e ) { cell = new Label ( j , i + size , data ) ; } } if ( cell != null ) { if ( ( i + size ) == 0 && hasHeaders ( ) ) cell . setCellFormat ( headerFormat ) ; else cell . setCellFeatures ( features ) ; sheet . addCell ( cell ) ; } } } } | Appends the given lines to the bottom of the given sheet . | 391 | 13 |
10,692 | public void setCellFormatAttributes ( WritableCellFormat cellFormat , FileColumn column ) { try { if ( cellFormat != null && column != null ) { Alignment a = Alignment . GENERAL ; short align = column . getAlign ( ) ; if ( align == FileColumn . ALIGN_CENTRE ) a = Alignment . CENTRE ; else if ( align == FileColumn . ALIGN_LEFT ) a = Alignment . LEFT ; else if ( align == FileColumn . ALIGN_RIGHT ) a = Alignment . RIGHT ; else if ( align == FileColumn . ALIGN_JUSTIFY ) a = Alignment . JUSTIFY ; else if ( align == FileColumn . ALIGN_FILL ) a = Alignment . FILL ; cellFormat . setAlignment ( a ) ; cellFormat . setWrap ( column . getWrap ( ) ) ; } } catch ( WriteException e ) { logger . severe ( StringUtilities . serialize ( e ) ) ; } } | Sets the cell attributes from the given column . | 215 | 10 |
10,693 | @ Override public void close ( ) { if ( workbook != null ) workbook . close ( ) ; try { if ( writableWorkbook != null ) writableWorkbook . close ( ) ; } catch ( IOException e ) { } catch ( WriteException e ) { } } | Close the workbook . | 61 | 5 |
10,694 | public static List < Range < Date > > getDateRanges ( Date from , Date to , final Period periodGranulation ) throws InvalidRangeException { if ( from . after ( to ) ) { throw buildInvalidRangeException ( from , to ) ; } if ( periodGranulation == Period . SINGLE ) { @ SuppressWarnings ( "unchecked" ) ArrayList < Range < Date > > list = newArrayList ( Range . getInstance ( from , to ) ) ; return list ; } to = formatToStartOfDay ( to ) ; from = formatToStartOfDay ( from ) ; List < Range < Date > > dateRanges = Lists . newArrayList ( ) ; Calendar calendar = buildCalendar ( from ) ; Date currentProcessDate = calendar . getTime ( ) ; for ( Date processEndDate = getDatePeriod ( to , periodGranulation ) . getUpperBound ( ) ; ! processEndDate . before ( currentProcessDate ) ; currentProcessDate = calendar . getTime ( ) ) { Date dateInRange = calendar . getTime ( ) ; Range < Date > dateRange = getDatePeriod ( dateInRange , periodGranulation ) ; dateRanges . add ( dateRange ) ; calendar . add ( periodGranulation . value , 1 ) ; } calendarCache . add ( calendar ) ; Range < Date > firstRange = dateRanges . get ( 0 ) ; if ( firstRange . getLowerBound ( ) . before ( from ) ) { dateRanges . set ( 0 , Range . getInstance ( from , firstRange . getUpperBound ( ) ) ) ; } int indexOfLastDateRange = dateRanges . size ( ) - 1 ; Range < Date > lastRange = dateRanges . get ( indexOfLastDateRange ) ; if ( lastRange . getUpperBound ( ) . after ( to ) ) { dateRanges . set ( indexOfLastDateRange , Range . getInstance ( lastRange . getLowerBound ( ) , to ) ) ; } return dateRanges ; } | Returns Range< ; Date> ; list between given date from and date to by period granulation . | 443 | 22 |
10,695 | public static Range < Date > getDatePeriod ( final Date date , final Period period ) { Calendar calendar = buildCalendar ( date ) ; Range < Date > dateRange = null ; Date startDate = calendar . getTime ( ) ; Date endDate = calendar . getTime ( ) ; if ( period != Period . DAY ) { for ( ; period . getValue ( date ) == period . getValue ( calendar . getTime ( ) ) ; calendar . add ( DAY_OF_MONTH , 1 ) ) { endDate = calendar . getTime ( ) ; } calendar . setTime ( date ) ; for ( ; period . getValue ( date ) == period . getValue ( calendar . getTime ( ) ) ; calendar . add ( DAY_OF_MONTH , - 1 ) ) { startDate = calendar . getTime ( ) ; } } calendarCache . add ( calendar ) ; dateRange = Range . getInstance ( startDate , endDate ) ; return dateRange ; } | Return Range< ; Date> ; by given date and period . | 208 | 15 |
10,696 | private static Calendar buildCalendar ( final Date date ) { Calendar calendar = buildCalendar ( ) ; calendar . setTime ( date ) ; return calendar ; } | Gets a calendar using the default time zone and locale . The Calendar returned is based on the given time in the default time zone with the default locale . | 33 | 31 |
10,697 | public synchronized void execute ( Runnable command ) { if ( active . get ( ) ) { stop ( ) ; this . command = command ; start ( ) ; } else { this . command = command ; } } | Executes the specified command continuously if the executor is started . | 45 | 13 |
10,698 | public boolean startsWith ( Name prefix ) { byte [ ] thisBytes = this . getByteArray ( ) ; int thisOffset = this . getByteOffset ( ) ; int thisLength = this . getByteLength ( ) ; byte [ ] prefixBytes = prefix . getByteArray ( ) ; int prefixOffset = prefix . getByteOffset ( ) ; int prefixLength = prefix . getByteLength ( ) ; int i = 0 ; while ( i < prefixLength && i < thisLength && thisBytes [ thisOffset + i ] == prefixBytes [ prefixOffset + i ] ) i ++ ; return i == prefixLength ; } | Does this name start with prefix? | 130 | 7 |
10,699 | @ Programmatic public DocumentTemplate createBlob ( final DocumentType type , final LocalDate date , final String atPath , final String fileSuffix , final boolean previewOnly , final Blob blob , final RenderingStrategy contentRenderingStrategy , final String subjectText , final RenderingStrategy subjectRenderingStrategy ) { final DocumentTemplate document = new DocumentTemplate ( type , date , atPath , fileSuffix , previewOnly , blob , contentRenderingStrategy , subjectText , subjectRenderingStrategy ) ; repositoryService . persistAndFlush ( document ) ; return document ; } | region > createBlob createClob createText | 131 | 10 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.