idx int64 0 41.2k | question stringlengths 83 4.15k | target stringlengths 5 715 |
|---|---|---|
10,000 | private int computeNearestCentroid ( double [ ] vector ) { int centroidIndex = - 1 ; double minDistance = Double . MAX_VALUE ; for ( int i = 0 ; i < numCentroids ; i ++ ) { double distance = 0 ; for ( int j = 0 ; j < vectorLength ; j ++ ) { distance += ( coarseQuantizer [ i ] [ j ] - vector [ j ] ) * ( coarseQuantizer [ i ] [ j ] - vector [ j ] ) ; if ( distance >= minDistance ) { break ; } } if ( distance < minDistance ) { minDistance = distance ; centroidIndex = i ; } } return centroidIndex ; } | Finds and returns the index of the coarse quantizer s centroid which is closer to the given vector . |
10,001 | protected boolean checkCitationIds ( List < String > citationIds , ItemDataProvider provider ) { for ( String id : citationIds ) { if ( provider . retrieveItem ( id ) == null ) { String message = "unknown citation id: " + id ; List < String > availableIds = Arrays . asList ( provider . getIds ( ) ) ; if ( ! availableIds . isEmpty ( ) ) { Collection < String > mins = Levenshtein . findSimilar ( availableIds , id ) ; if ( mins . size ( ) > 0 ) { if ( mins . size ( ) == 1 ) { message += "\n\nDid you mean this?" ; } else { message += "\n\nDid you mean one of these?" ; } for ( String m : mins ) { message += "\n\t" + m ; } } } error ( message ) ; return false ; } } return true ; } | Checks the citation IDs provided on the command line |
10,002 | public Map < String , CSLItemData > toItemData ( BibTeXDatabase db ) { Map < String , CSLItemData > result = new HashMap < > ( ) ; for ( Map . Entry < Key , BibTeXEntry > e : db . getEntries ( ) . entrySet ( ) ) { result . put ( e . getKey ( ) . getValue ( ) , toItemData ( e . getValue ( ) ) ) ; } return result ; } | Converts the given database to a map of CSL citation items |
10,003 | public CSLType toType ( Key type ) { String s = type . getValue ( ) ; if ( s . equalsIgnoreCase ( TYPE_ARTICLE ) ) { return CSLType . ARTICLE_JOURNAL ; } else if ( s . equalsIgnoreCase ( TYPE_PROCEEDINGS ) ) { return CSLType . BOOK ; } else if ( s . equalsIgnoreCase ( TYPE_MANUAL ) ) { return CSLType . BOOK ; } else if ( s . equalsIgnoreCase ( TYPE_BOOK ) ) { return CSLType . BOOK ; } else if ( s . equalsIgnoreCase ( TYPE_PERIODICAL ) ) { return CSLType . BOOK ; } else if ( s . equalsIgnoreCase ( TYPE_BOOKLET ) ) { return CSLType . PAMPHLET ; } else if ( s . equalsIgnoreCase ( TYPE_INBOOK ) ) { return CSLType . CHAPTER ; } else if ( s . equalsIgnoreCase ( TYPE_INCOLLECTION ) ) { return CSLType . CHAPTER ; } else if ( s . equalsIgnoreCase ( TYPE_INPROCEEDINGS ) ) { return CSLType . PAPER_CONFERENCE ; } else if ( s . equalsIgnoreCase ( TYPE_CONFERENCE ) ) { return CSLType . PAPER_CONFERENCE ; } else if ( s . equalsIgnoreCase ( TYPE_MASTERSTHESIS ) ) { return CSLType . THESIS ; } else if ( s . equalsIgnoreCase ( TYPE_PHDTHESIS ) ) { return CSLType . THESIS ; } else if ( s . equalsIgnoreCase ( TYPE_TECHREPORT ) ) { return CSLType . REPORT ; } else if ( s . equalsIgnoreCase ( TYPE_PATENT ) ) { return CSLType . PATENT ; } else if ( s . equalsIgnoreCase ( TYPE_ELECTRONIC ) ) { return CSLType . WEBPAGE ; } else if ( s . equalsIgnoreCase ( TYPE_ONLINE ) ) { return CSLType . WEBPAGE ; } else if ( s . equalsIgnoreCase ( TYPE_WWW ) ) { return CSLType . WEBPAGE ; } else if ( s . equalsIgnoreCase ( TYPE_STANDARD ) ) { return CSLType . LEGISLATION ; } else if ( s . equalsIgnoreCase ( TYPE_UNPUBLISHED ) ) { return CSLType . MANUSCRIPT ; } return CSLType . ARTICLE ; } | Converts a BibTeX type to a CSL type |
10,004 | public static CitationIDIndexPair fromJson ( List < ? > arr ) { String citationId = ( String ) arr . get ( 0 ) ; int noteIndex = ( ( Number ) arr . get ( 1 ) ) . intValue ( ) ; return new CitationIDIndexPair ( citationId , noteIndex ) ; } | Converts a JSON array to a CitationIDIndexPair object . |
10,005 | public static String sanitize ( String s ) { StringBuilder sb = new StringBuilder ( ) ; for ( int i = 0 ; i < s . length ( ) ; ++ i ) { char c = s . charAt ( i ) ; switch ( c ) { case '\u00c0' : case '\u00c1' : case '\u00c3' : case '\u00c4' : sb . append ( 'A' ) ; break ; case '\u00c8' : case '\u00c9' : case '\u00cb' : sb . append ( 'E' ) ; break ; case '\u00cc' : case '\u00cd' : case '\u00cf' : sb . append ( 'I' ) ; break ; case '\u00d2' : case '\u00d3' : case '\u00d5' : case '\u00d6' : sb . append ( 'O' ) ; break ; case '\u00d9' : case '\u00da' : case '\u00dc' : sb . append ( 'U' ) ; break ; case '\u00e0' : case '\u00e1' : case '\u00e3' : case '\u00e4' : sb . append ( 'a' ) ; break ; case '\u00e8' : case '\u00e9' : case '\u00eb' : sb . append ( 'e' ) ; break ; case '\u00ec' : case '\u00ed' : case '\u00ef' : sb . append ( 'i' ) ; break ; case '\u00f2' : case '\u00f3' : case '\u00f6' : case '\u00f5' : sb . append ( 'o' ) ; break ; case '\u00f9' : case '\u00fa' : case '\u00fc' : sb . append ( 'u' ) ; break ; case '\u00d1' : sb . append ( 'N' ) ; break ; case '\u00f1' : sb . append ( 'n' ) ; break ; case '\u010c' : sb . append ( 'C' ) ; break ; case '\u0160' : sb . append ( 'S' ) ; break ; case '\u017d' : sb . append ( 'Z' ) ; break ; case '\u010d' : sb . append ( 'c' ) ; break ; case '\u0161' : sb . append ( 's' ) ; break ; case '\u017e' : sb . append ( 'z' ) ; break ; case '\u00df' : sb . append ( "ss" ) ; break ; default : if ( ( c >= 'a' && c <= 'z' ) || ( c >= 'A' && c <= 'Z' ) || ( c >= '0' && c <= '9' ) ) { sb . append ( c ) ; } else { sb . append ( '_' ) ; } break ; } } return sb . toString ( ) ; } | Sanitizes a string so it can be used as an identifier |
10,006 | public static String escapeJava ( String s ) { if ( s == null ) { return null ; } StringBuilder sb = new StringBuilder ( Math . min ( 2 , s . length ( ) * 3 / 2 ) ) ; for ( int i = 0 ; i < s . length ( ) ; ++ i ) { char c = s . charAt ( i ) ; if ( c == '\b' ) { sb . append ( "\\b" ) ; } else if ( c == '\n' ) { sb . append ( "\\n" ) ; } else if ( c == '\t' ) { sb . append ( "\\t" ) ; } else if ( c == '\f' ) { sb . append ( "\\f" ) ; } else if ( c == '\r' ) { sb . append ( "\\r" ) ; } else if ( c == '\\' ) { sb . append ( "\\\\" ) ; } else if ( c == '"' ) { sb . append ( "\\\"" ) ; } else if ( c < 32 || c > 0x7f ) { sb . append ( "\\u" ) ; sb . append ( hex4 ( c ) ) ; } else { sb . append ( c ) ; } } return sb . toString ( ) ; } | Escapes characters in the given string according to Java rules |
10,007 | private static String hex4 ( char c ) { char [ ] r = new char [ ] { '0' , '0' , '0' , '0' } ; int i = 3 ; while ( c > 0 ) { r [ i ] = HEX_DIGITS [ c & 0xF ] ; c >>>= 4 ; -- i ; } return new String ( r ) ; } | Converts the given character to a four - digit hexadecimal string |
10,008 | public double [ ] [ ] extractFeatures ( BufferedImage image ) throws Exception { long start = System . currentTimeMillis ( ) ; double [ ] [ ] features = extractFeaturesInternal ( image ) ; totalNumberInterestPoints += features . length ; totalExtractionTime += System . currentTimeMillis ( ) - start ; return features ; } | Any normalizations of the features should be performed in the specific classes! |
10,009 | protected void error ( String msg ) { System . err . println ( CSLToolContext . current ( ) . getToolName ( ) + ": " + msg ) ; } | Outputs an error message |
10,010 | protected void usage ( ) { String footnotes = null ; if ( ! getOptions ( ) . getCommands ( ) . isEmpty ( ) ) { footnotes = "Use `" + CSLToolContext . current ( ) . getToolName ( ) + " help <command>' to read about a specific command." ; } String name = CSLToolContext . current ( ) . getToolName ( ) ; String usageName = getUsageName ( ) ; if ( usageName != null && ! usageName . isEmpty ( ) ) { name += " " + usageName ; } String unknownArguments = OptionIntrospector . getUnknownArgumentName ( getClassesToIntrospect ( ) ) ; OptionParser . usage ( name , getUsageDescription ( ) , getOptions ( ) , unknownArguments , footnotes , new PrintWriter ( System . out , true ) ) ; } | Prints out usage information |
10,011 | public Map < String , Object > parseObject ( ) throws IOException { Type t = lexer . readNextToken ( ) ; if ( t != Type . START_OBJECT ) { throw new IOException ( "Unexpected token: " + t ) ; } return parseObjectInternal ( ) ; } | Parses an object into a map |
10,012 | public List < Object > parseArray ( ) throws IOException { Type t = lexer . readNextToken ( ) ; if ( t != Type . START_ARRAY ) { throw new IOException ( "Unexpected token: " + t ) ; } return parseArrayInternal ( ) ; } | Parses an array |
10,013 | private Object readValue ( Type t ) throws IOException { switch ( t ) { case START_OBJECT : return parseObjectInternal ( ) ; case START_ARRAY : return parseArrayInternal ( ) ; case STRING : return lexer . readString ( ) ; case NUMBER : return lexer . readNumber ( ) ; case TRUE : return true ; case FALSE : return false ; case NULL : return null ; default : throw new IOException ( "Unexpected token: " + t ) ; } } | Reads a value for a given type |
10,014 | public static Result parse ( String [ ] args , Collection < Class < ? extends Command > > excluded ) throws IntrospectionException , InvalidOptionException { List < Class < ? extends Command > > classes = new ArrayList < > ( ) ; return getCommandClass ( args , 0 , classes , new HashSet < > ( excluded ) ) ; } | Parses arguments of a shell command line |
10,015 | private static String decodeUrl ( String endcodedUrl ) { String imageSize = "z" ; String [ ] parts = endcodedUrl . split ( "_" ) ; String farmId = parts [ 0 ] ; String serverId = parts [ 1 ] ; String identidier = parts [ 2 ] ; String secret = parts [ 3 ] ; String url = "https://farm" + farmId + ".staticflickr.com/" + serverId + "/" + identidier + "_" + secret + "_" + imageSize + ".jpg" ; return url ; } | This method is used to compile the Flickr URL from its parts . |
10,016 | public void setFromAddress ( final String name , final String fromAddress ) { fromRecipient = new Recipient ( name , fromAddress , null ) ; } | Sets the sender address . |
10,017 | public void submitImageDownloadTask ( String URL , String id ) { Callable < ImageDownloadResult > call = new ImageDownload ( URL , id , downloadFolder , saveThumb , saveOriginal , followRedirects ) ; pool . submit ( call ) ; numPendingTasks ++ ; } | Submits a new image download task . |
10,018 | public void submitHadoopDownloadTask ( String URL , String id ) { Callable < ImageDownloadResult > call = new HadoopImageDownload ( URL , id , followRedirects ) ; pool . submit ( call ) ; numPendingTasks ++ ; } | Submits a new hadoop image download task . |
10,019 | public ImageDownloadResult getImageDownloadResult ( ) throws Exception { Future < ImageDownloadResult > future = pool . poll ( ) ; if ( future == null ) { return null ; } else { try { ImageDownloadResult imdr = future . get ( ) ; return imdr ; } catch ( Exception e ) { throw e ; } finally { numPendingTasks -- ; } } } | Gets an image download results from the pool . |
10,020 | public ImageDownloadResult getImageDownloadResultWait ( ) throws Exception { try { ImageDownloadResult imdr = pool . take ( ) . get ( ) ; return imdr ; } catch ( Exception e ) { throw e ; } finally { numPendingTasks -- ; } } | Gets an image download result from the pool waiting if necessary . |
10,021 | public static void downloadFromUrlsFile ( String dowloadFolder , String urlsFile , int numUrls , int urlsToSkip ) throws Exception { long start = System . currentTimeMillis ( ) ; int numThreads = 10 ; BufferedReader in = new BufferedReader ( new FileReader ( new File ( urlsFile ) ) ) ; for ( int i = 0 ; i < urlsToSkip ; i ++ ) { in . readLine ( ) ; } ImageDownloader downloader = new ImageDownloader ( dowloadFolder , numThreads ) ; int submittedCounter = 0 ; int completedCounter = 0 ; int failedCounter = 0 ; String line = "" ; while ( true ) { String url ; String id = "" ; while ( submittedCounter < numUrls && downloader . canAcceptMoreTasks ( ) ) { line = in . readLine ( ) ; url = line . split ( "\\s+" ) [ 1 ] ; id = line . split ( "\\s+" ) [ 0 ] ; downloader . submitImageDownloadTask ( url , id ) ; submittedCounter ++ ; } if ( completedCounter + failedCounter < submittedCounter ) { try { downloader . getImageDownloadResultWait ( ) ; completedCounter ++ ; System . out . println ( completedCounter + " downloads completed!" ) ; } catch ( Exception e ) { failedCounter ++ ; System . out . println ( failedCounter + " downloads failed!" ) ; System . out . println ( e . getMessage ( ) ) ; } } if ( completedCounter + failedCounter == numUrls ) { downloader . shutDown ( ) ; in . close ( ) ; break ; } } long end = System . currentTimeMillis ( ) ; System . out . println ( "Total time: " + ( end - start ) + " ms" ) ; System . out . println ( "Downloaded images: " + completedCounter ) ; System . out . println ( "Failed images: " + failedCounter ) ; } | This method exemplifies multi - threaded image download from a list of urls . It uses 5 download threads . |
10,022 | public static void main ( String [ ] args ) throws Exception { String dowloadFolder = "images/" ; String urlsFile = "urls.txt" ; int numUrls = 1000 ; int urlsToSkip = 0 ; downloadFromUrlsFile ( dowloadFolder , urlsFile , numUrls , urlsToSkip ) ; } | Calls the downloadFromUrlsFile . |
10,023 | protected int computeNearestCentroid ( double [ ] descriptor ) { int centroidIndex = - 1 ; double minDistance = Double . MAX_VALUE ; for ( int i = 0 ; i < numCentroids ; i ++ ) { double distance = 0 ; for ( int j = 0 ; j < descriptorLength ; j ++ ) { distance += ( codebook [ i ] [ j ] - descriptor [ j ] ) * ( codebook [ i ] [ j ] - descriptor [ j ] ) ; if ( distance >= minDistance ) { break ; } } if ( distance < minDistance ) { minDistance = distance ; centroidIndex = i ; } } return centroidIndex ; } | Returns the index of the centroid which is closer to the given descriptor . |
10,024 | public static String readURLToString ( URL u , String encoding ) throws IOException { for ( int i = 0 ; i < 30 ; ++ i ) { URLConnection conn = u . openConnection ( ) ; if ( conn instanceof HttpURLConnection ) { HttpURLConnection hconn = ( HttpURLConnection ) conn ; hconn . setConnectTimeout ( 15000 ) ; hconn . setReadTimeout ( 15000 ) ; switch ( hconn . getResponseCode ( ) ) { case HttpURLConnection . HTTP_MOVED_PERM : case HttpURLConnection . HTTP_MOVED_TEMP : String location = hconn . getHeaderField ( "Location" ) ; u = new URL ( u , location ) ; continue ; } } return readStreamToString ( conn . getInputStream ( ) , encoding ) ; } throw new IOException ( "Too many HTTP redirects" ) ; } | Reads a string from a URL |
10,025 | public static String readFileToString ( File f , String encoding ) throws IOException { return readStreamToString ( new FileInputStream ( f ) , encoding ) ; } | Reads a string from a file . |
10,026 | public static String readStreamToString ( InputStream is , String encoding ) throws IOException { try { StringBuilder sb = new StringBuilder ( ) ; byte [ ] buf = new byte [ 1024 * 10 ] ; int read ; while ( ( read = is . read ( buf ) ) >= 0 ) { sb . append ( new String ( buf , 0 , read , encoding ) ) ; } return sb . toString ( ) ; } finally { is . close ( ) ; } } | Reads a string from a stream . Closes the stream after reading . |
10,027 | public static byte [ ] readStream ( InputStream is ) throws IOException { try { ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; byte [ ] buf = new byte [ 1024 * 10 ] ; int read ; while ( ( read = is . read ( buf ) ) >= 0 ) { baos . write ( buf , 0 , read ) ; } return baos . toByteArray ( ) ; } finally { is . close ( ) ; } } | Reads a byte array from a stream . Closes the stream after reading . |
10,028 | private static Object toJson ( Object obj , JsonBuilderFactory factory ) { if ( obj instanceof JsonObject ) { return ( ( JsonObject ) obj ) . toJson ( factory . createJsonBuilder ( ) ) ; } else if ( obj . getClass ( ) . isArray ( ) ) { List < Object > r = new ArrayList < > ( ) ; int len = Array . getLength ( obj ) ; for ( int i = 0 ; i < len ; ++ i ) { Object ao = Array . get ( obj , i ) ; r . add ( toJson ( ao , factory ) ) ; } return r ; } else if ( obj instanceof Collection ) { Collection < ? > coll = ( Collection < ? > ) obj ; List < Object > r = new ArrayList < > ( ) ; for ( Object ao : coll ) { r . add ( toJson ( ao , factory ) ) ; } return r ; } else if ( obj instanceof Map ) { Map < ? , ? > m = ( Map < ? , ? > ) obj ; Map < String , Object > r = new LinkedHashMap < > ( ) ; for ( Map . Entry < ? , ? > e : m . entrySet ( ) ) { String key = toJson ( e . getKey ( ) , factory ) . toString ( ) ; Object value = toJson ( e . getValue ( ) , factory ) ; r . put ( key , value ) ; } return r ; } return obj ; } | Converts an object to a JSON object |
10,029 | protected void indexVectorInternal ( double [ ] vector ) throws Exception { if ( vector . length != vectorLength ) { throw new Exception ( "The dimensionality of the vector is wrong!" ) ; } if ( transformation == TransformationType . RandomRotation ) { vector = rr . rotate ( vector ) ; } else if ( transformation == TransformationType . RandomPermutation ) { vector = rp . permute ( vector ) ; } int [ ] pqCode = new int [ numSubVectors ] ; for ( int i = 0 ; i < numSubVectors ; i ++ ) { int fromIdex = i * subVectorLength ; int toIndex = fromIdex + subVectorLength ; double [ ] subvector = Arrays . copyOfRange ( vector , fromIdex , toIndex ) ; pqCode [ i ] = computeNearestProductIndex ( subvector , i ) ; } if ( numProductCentroids <= 256 ) { byte [ ] pqByteCode = transformToByte ( pqCode ) ; if ( loadIndexInMemory ) { pqByteCodes . add ( pqByteCode ) ; } appendPersistentIndex ( pqByteCode ) ; } else { short [ ] pqShortCode = transformToShort ( pqCode ) ; if ( loadIndexInMemory ) { pqShortCodes . add ( pqShortCode ) ; } appendPersistentIndex ( pqShortCode ) ; } } | Append the PQ index with the given vector . |
10,030 | private BoundedPriorityQueue < Result > computeKnnADC ( int k , double [ ] qVector ) { BoundedPriorityQueue < Result > nn = new BoundedPriorityQueue < Result > ( new Result ( ) , k ) ; if ( transformation == TransformationType . RandomRotation ) { qVector = rr . rotate ( qVector ) ; } else if ( transformation == TransformationType . RandomPermutation ) { qVector = rp . permute ( qVector ) ; } double [ ] [ ] lookUpTable = computeLookupADC ( qVector ) ; for ( int i = 0 ; i < loadCounter ; i ++ ) { double l2distance = 0 ; int codeStart = i * numSubVectors ; if ( numProductCentroids <= 256 ) { byte [ ] pqCode = pqByteCodes . toArray ( codeStart , numSubVectors ) ; for ( int j = 0 ; j < pqCode . length ; j ++ ) { l2distance += lookUpTable [ j ] [ pqCode [ j ] + 128 ] ; } } else { short [ ] pqCode = pqShortCodes . toArray ( codeStart , numSubVectors ) ; for ( int j = 0 ; j < pqCode . length ; j ++ ) { l2distance += lookUpTable [ j ] [ pqCode [ j ] ] ; } } nn . offer ( new Result ( i , l2distance ) ) ; } return nn ; } | Computes and returns the k nearest neighbors of the query vector using the ADC approach . |
10,031 | private BoundedPriorityQueue < Result > computeKnnSDC ( int k , int iid ) { BoundedPriorityQueue < Result > nn = new BoundedPriorityQueue < Result > ( new Result ( ) , k ) ; int [ ] pqCodeQuery = new int [ numSubVectors ] ; for ( int m = 0 ; m < numSubVectors ; m ++ ) { if ( pqByteCodes != null ) { pqCodeQuery [ m ] = pqByteCodes . getQuick ( iid * numSubVectors + m ) ; } else { pqCodeQuery [ m ] = pqShortCodes . getQuick ( iid * numSubVectors + m ) ; } } double lowest = Double . MAX_VALUE ; for ( int i = 0 ; i < loadCounter ; i ++ ) { double l2distance = 0 ; for ( int j = 0 ; j < numSubVectors ; j ++ ) { int pqSubCode = pqByteCodes . getQuick ( i * numSubVectors + j ) ; int pqSubCodeQuery = pqCodeQuery [ j ] ; if ( pqByteCodes != null ) { pqSubCode += 128 ; pqSubCodeQuery += 128 ; } for ( int m = 0 ; m < subVectorLength ; m ++ ) { l2distance += ( productQuantizer [ j ] [ pqSubCode ] [ m ] - productQuantizer [ j ] [ pqSubCodeQuery ] [ m ] ) * ( productQuantizer [ j ] [ pqSubCode ] [ m ] - productQuantizer [ j ] [ pqSubCodeQuery ] [ m ] ) ; if ( l2distance > lowest ) { break ; } } if ( l2distance > lowest ) { break ; } } nn . offer ( new Result ( i , l2distance ) ) ; if ( i >= k ) { lowest = nn . last ( ) . getDistance ( ) ; } } return nn ; } | Computes and returns the k nearest neighbors of the query internal id using the SDC approach . |
10,032 | protected OAuth createOAuth ( String consumerKey , String consumerSecret , String redirectUri ) { return new OAuth1 ( consumerKey , consumerSecret ) ; } | Creates an OAuth object |
10,033 | private void setSpacing ( ) { final int verticalSpacing = styledAttributes . getDimensionPixelOffset ( R . styleable . PinLock_keypadVerticalSpacing , 2 ) ; final int horizontalSpacing = styledAttributes . getDimensionPixelOffset ( R . styleable . PinLock_keypadHorizontalSpacing , 2 ) ; setVerticalSpacing ( verticalSpacing ) ; setHorizontalSpacing ( horizontalSpacing ) ; } | Setting up vertical and horizontal spacing for the view |
10,034 | public double [ ] transformToVector ( ) throws Exception { if ( vectorLength > vladAggregator . getVectorLength ( ) || vectorLength <= 0 ) { throw new Exception ( "Vector length should be between 1 and " + vladAggregator . getVectorLength ( ) ) ; } double [ ] [ ] features ; if ( image == null ) { try { image = ImageIO . read ( new File ( imageFolder + imageFilename ) ) ; } catch ( IllegalArgumentException e ) { System . out . println ( "Exception: " + e . getMessage ( ) + " | Image: " + imageFilename ) ; image = ImageIOGreyScale . read ( new File ( imageFolder + imageFilename ) ) ; } } ImageScaling scale = new ImageScaling ( maxImageSizeInPixels ) ; try { image = scale . maxPixelsScaling ( image ) ; } catch ( Exception e ) { throw new Exception ( "Exception thrown when scaling the image!\n" + e . getMessage ( ) ) ; } features = featureExtractor . extractFeatures ( image ) ; double [ ] vladVector = vladAggregator . aggregate ( features ) ; if ( vladVector . length == vectorLength ) { return vladVector ; } else { double [ ] projected = pcaProjector . sampleToEigenSpace ( vladVector ) ; return projected ; } } | Transforms the image into a vector and returns the result . |
10,035 | public static void main ( String args [ ] ) throws Exception { String imageFolder = "C:/images/" ; String imagFilename = "test.jpg" ; String [ ] codebookFiles = { "C:/codebook1.csv" , "C:/codebook2.csv" , "C:/codebook3.csv" , "C:/codebook4.csv" } ; int [ ] numCentroids = { 64 , 64 , 64 , 64 } ; String pcaFilename = "C:/pca.txt" ; int initialLength = numCentroids . length * numCentroids [ 0 ] * AbstractFeatureExtractor . SURFLength ; int targetLength = 128 ; ImageVectorization imvec = new ImageVectorization ( imageFolder , imagFilename , targetLength , 512 * 384 ) ; ImageVectorization . setFeatureExtractor ( new SURFExtractor ( ) ) ; double [ ] [ ] [ ] codebooks = AbstractFeatureAggregator . readQuantizers ( codebookFiles , numCentroids , AbstractFeatureExtractor . SURFLength ) ; ImageVectorization . setVladAggregator ( new VladAggregatorMultipleVocabularies ( codebooks ) ) ; if ( targetLength < initialLength ) { PCA pca = new PCA ( targetLength , 1 , initialLength , true ) ; pca . loadPCAFromFile ( pcaFilename ) ; ImageVectorization . setPcaProjector ( pca ) ; } imvec . setDebug ( true ) ; ImageVectorizationResult imvr = imvec . call ( ) ; System . out . println ( imvr . getImageName ( ) + ": " + Arrays . toString ( imvr . getImageVector ( ) ) ) ; } | Example of SURF extraction multiVLAD aggregation and PCA - projection of a single image using this class . |
10,036 | private static CSLItemData [ ] sanitizeItems ( ItemDataProvider provider ) { Set < String > knownIds = new LinkedHashSet < > ( ) ; CSLDateParser dateParser = new CSLDateParser ( ) ; String [ ] ids = provider . getIds ( ) ; CSLItemData [ ] result = new CSLItemData [ ids . length ] ; for ( int i = 0 ; i < ids . length ; ++ i ) { String id = ids [ i ] ; CSLItemData item = provider . retrieveItem ( id ) ; String newId = makeId ( item , dateParser ) ; newId = uniquify ( newId , knownIds ) ; knownIds . add ( newId ) ; item = new CSLItemDataBuilder ( item ) . id ( newId ) . build ( ) ; result [ i ] = item ; } return result ; } | Copies all items from the given provider and sanitizes its IDs |
10,037 | private static String makeId ( CSLItemData item , CSLDateParser dateParser ) { if ( item . getAuthor ( ) == null || item . getAuthor ( ) . length == 0 ) { return item . getId ( ) ; } CSLName firstAuthor = item . getAuthor ( ) [ 0 ] ; String a = firstAuthor . getFamily ( ) ; if ( a == null || a . isEmpty ( ) ) { a = firstAuthor . getGiven ( ) ; if ( a == null || a . isEmpty ( ) ) { a = firstAuthor . getLiteral ( ) ; if ( a == null || a . isEmpty ( ) ) { return item . getId ( ) ; } } } a = StringHelper . sanitize ( a ) ; int year = getYear ( item . getIssued ( ) , dateParser ) ; if ( year < 0 ) { year = getYear ( item . getContainer ( ) , dateParser ) ; if ( year < 0 ) { year = getYear ( item . getOriginalDate ( ) , dateParser ) ; if ( year < 0 ) { year = getYear ( item . getEventDate ( ) , dateParser ) ; if ( year < 0 ) { year = getYear ( item . getSubmitted ( ) , dateParser ) ; } } } } if ( year >= 0 ) { a = a + year ; } return a ; } | Generates a human - readable ID for an item |
10,038 | private static String uniquify ( String id , Set < String > knownIds ) { int n = 10 ; String olda = id ; while ( knownIds . contains ( id ) ) { id = olda + Integer . toString ( n , Character . MAX_RADIX ) ; ++ n ; } return id ; } | Makes the given ID unique |
10,039 | public synchronized boolean indexVector ( String id , double [ ] vector ) throws Exception { long startIndexing = System . currentTimeMillis ( ) ; if ( loadCounter >= maxNumVectors ) { System . out . println ( "Maximum index capacity reached, no more vectors can be indexed!" ) ; return false ; } if ( isIndexed ( id ) ) { System . out . println ( "Vector '" + id + "' already indexed!" ) ; return false ; } long startMapping = System . currentTimeMillis ( ) ; createMapping ( id ) ; totalIdMappingTime += System . currentTimeMillis ( ) - startMapping ; long startInternalIndexing = System . currentTimeMillis ( ) ; indexVectorInternal ( vector ) ; totalInternalVectorIndexingTime += System . currentTimeMillis ( ) - startInternalIndexing ; loadCounter ++ ; if ( loadCounter % 100 == 0 ) { System . out . println ( new Date ( ) + " # indexed vectors: " + loadCounter ) ; } totalVectorIndexingTime += System . currentTimeMillis ( ) - startIndexing ; return true ; } | Updates the index with the given vector . This is a synchronized method i . e . when a thread calls this method all other threads wait for the first thread to complete before executing the method . This ensures that the persistent BDB store will remain consistent when multiple threads call the indexVector method . |
10,040 | public int getInternalId ( String id ) { DatabaseEntry key = new DatabaseEntry ( ) ; StringBinding . stringToEntry ( id , key ) ; DatabaseEntry data = new DatabaseEntry ( ) ; if ( ( idToIidDB . get ( null , key , data , null ) == OperationStatus . SUCCESS ) ) { return IntegerBinding . entryToInt ( data ) ; } else { return - 1 ; } } | Returns the internal id assigned to the vector with the given id or - 1 if the id is not found . Accesses the BDB store! |
10,041 | public String getId ( int iid ) { if ( iid < 0 || iid > loadCounter ) { System . out . println ( "Internal id " + iid + " is out of range!" ) ; return null ; } DatabaseEntry key = new DatabaseEntry ( ) ; IntegerBinding . intToEntry ( iid , key ) ; DatabaseEntry data = new DatabaseEntry ( ) ; if ( ( iidToIdDB . get ( null , key , data , null ) == OperationStatus . SUCCESS ) ) { return StringBinding . entryToString ( data ) ; } else { System . out . println ( "Internal id " + iid + " is in range but id was not found.." ) ; System . out . println ( "Index is probably corrupted" ) ; System . exit ( 0 ) ; return null ; } } | Returns the id of the vector which was assigned the given internal id or null if the internal id does not exist . Accesses the BDB store! |
10,042 | public boolean setGeolocation ( int iid , double latitude , double longitude ) { if ( iid < 0 || iid > loadCounter ) { System . out . println ( "Internal id " + iid + " is out of range!" ) ; return false ; } DatabaseEntry key = new DatabaseEntry ( ) ; DatabaseEntry data = new DatabaseEntry ( ) ; IntegerBinding . intToEntry ( iid , key ) ; TupleOutput output = new TupleOutput ( ) ; output . writeDouble ( latitude ) ; output . writeDouble ( longitude ) ; TupleBinding . outputToEntry ( output , data ) ; if ( iidToGeolocationDB . put ( null , key , data ) == OperationStatus . SUCCESS ) { return true ; } else { return false ; } } | This method is used to set the geolocation of a previously indexed vector . If the geolocation is already set this method replaces it . |
10,043 | public boolean setMetadata ( int iid , Object metaData ) { if ( iid < 0 || iid > loadCounter ) { System . out . println ( "Internal id " + iid + " is out of range!" ) ; return false ; } MetaDataEntity mde = new MetaDataEntity ( iid , metaData ) ; PrimaryIndex < Integer , MetaDataEntity > primaryIndex = iidToMetadataDB . getPrimaryIndex ( Integer . class , MetaDataEntity . class ) ; if ( primaryIndex . contains ( iid ) ) { primaryIndex . put ( null , mde ) ; return true ; } else { return false ; } } | This method is used to set the metadata of a previously indexed vector . If the metadata is already set this methods replaces it . |
10,044 | public void dumpidToIidDB ( String dumpFilename ) throws Exception { DatabaseEntry foundKey = new DatabaseEntry ( ) ; DatabaseEntry foundData = new DatabaseEntry ( ) ; ForwardCursor cursor = idToIidDB . openCursor ( null , null ) ; BufferedWriter out = new BufferedWriter ( new FileWriter ( new File ( dumpFilename ) ) ) ; while ( cursor . getNext ( foundKey , foundData , LockMode . DEFAULT ) == OperationStatus . SUCCESS ) { int iid = IntegerBinding . entryToInt ( foundData ) ; String id = StringBinding . entryToString ( foundKey ) ; out . write ( id + " " + iid + "\n" ) ; } cursor . close ( ) ; out . close ( ) ; } | This is a utility method that can be used to dump the contents of the idToIidDB to a txt file . |
10,045 | public void outputIndexingTimes ( ) { System . out . println ( ( double ) totalInternalVectorIndexingTime / loadCounter + " ms => internal indexing time" ) ; System . out . println ( ( double ) totalIdMappingTime / loadCounter + " ms => id mapping time" ) ; System . out . println ( ( double ) totalVectorIndexingTime / loadCounter + " ms => total indexing time" ) ; outputIndexingTimesInternal ( ) ; } | This method can be called to output indexing time measurements . |
10,046 | public void close ( ) { if ( dbEnv != null ) { iidToIdDB . close ( ) ; idToIidDB . close ( ) ; if ( useGeolocation ) { iidToGeolocationDB . close ( ) ; } if ( useMetaData ) { iidToMetadataDB . close ( ) ; } closeInternal ( ) ; dbEnv . close ( ) ; } else { System . out . println ( "BDB environment is null!" ) ; } } | This method closes the open BDB environment and databases . |
10,047 | public void savePCAToFile ( String PCAFileName ) throws Exception { if ( isPcaInitialized ) { throw new Exception ( "Cannot save, PCA is initialized!" ) ; } if ( V_t == null ) { throw new Exception ( "Cannot save to file, PCA matrix is null!" ) ; } BufferedWriter out = new BufferedWriter ( new FileWriter ( PCAFileName ) ) ; for ( int i = 0 ; i < sampleSize - 1 ; i ++ ) { out . write ( means . get ( i ) + " " ) ; } out . write ( means . get ( sampleSize - 1 ) + "\n" ) ; for ( int i = 0 ; i < numComponents - 1 ; i ++ ) { out . write ( W . get ( i , i ) + " " ) ; } out . write ( W . get ( numComponents - 1 , numComponents - 1 ) + "\n" ) ; for ( int i = 0 ; i < numComponents ; i ++ ) { for ( int j = 0 ; j < sampleSize - 1 ; j ++ ) { out . write ( V_t . get ( i , j ) + " " ) ; } out . write ( V_t . get ( i , sampleSize - 1 ) + "\n" ) ; } out . close ( ) ; } | Writes the means the eigenvalues and the PCA matrix to a text file . The 1st row of the file contains the training sample means per component the 2nd row contains the eigenvalues in descending order and subsequent rows contain contain the eigenvectors in descending eigenvalue order . |
10,048 | public void submitImageVectorizationTask ( String imageFolder , String imageName ) { Callable < ImageVectorizationResult > call = new ImageVectorization ( imageFolder , imageName , targetVectorLength , maxImageSizeInPixels ) ; pool . submit ( call ) ; numPendingTasks ++ ; } | Submits a new image vectorization task for an image that is stored in the disk and has not yet been read into a BufferedImage object . |
10,049 | public ImageVectorizationResult getImageVectorizationResult ( ) throws Exception { Future < ImageVectorizationResult > future = pool . poll ( ) ; if ( future == null ) { return null ; } else { try { ImageVectorizationResult imvr = future . get ( ) ; return imvr ; } catch ( Exception e ) { throw e ; } finally { numPendingTasks -- ; } } } | Takes and returns a vectorization result from the pool . |
10,050 | public ImageVectorizationResult getImageVectorizationResultWait ( ) throws Exception { try { ImageVectorizationResult imvr = pool . take ( ) . get ( ) ; return imvr ; } catch ( Exception e ) { throw e ; } finally { numPendingTasks -- ; } } | Gets an image vectorization result from the pool waiting if necessary . |
10,051 | public List < String > getHeaders ( String name ) { Map < String , List < String > > fields = conn . getHeaderFields ( ) ; if ( fields == null ) { return null ; } return fields . get ( name ) ; } | Gets the values of a named response header field |
10,052 | public double [ ] aggregate ( ArrayList < double [ ] > descriptors ) throws Exception { double [ ] multiVlad = new double [ vectorLength ] ; int vectorShift = 0 ; for ( int i = 0 ; i < vladAggregators . length ; i ++ ) { double [ ] subVlad = vladAggregators [ i ] . aggregate ( descriptors ) ; if ( normalizationsOn ) { Normalization . normalizePower ( subVlad , 0.5 ) ; Normalization . normalizeL2 ( subVlad ) ; } System . arraycopy ( subVlad , 0 , multiVlad , vectorShift , subVlad . length ) ; vectorShift += vladAggregators [ i ] . getNumCentroids ( ) * vladAggregators [ i ] . getDescriptorLength ( ) ; } if ( vladAggregators . length > 1 && normalizationsOn ) { Normalization . normalizeL2 ( multiVlad ) ; } return multiVlad ; } | Takes as input an ArrayList of double arrays which contains the set of local descriptors of an image . Returns the multiVLAD representation of the image using the codebooks supplied in the constructor . |
10,053 | public static boolean isValid ( final String email , final EmailAddressValidationCriteria emailAddressValidationCriteria ) { return buildValidEmailPattern ( emailAddressValidationCriteria ) . matcher ( email ) . matches ( ) ; } | Validates an e - mail with given validation flags . |
10,054 | private List < Object > convertArray ( V8Array arr ) { List < Object > l = new ArrayList < > ( ) ; for ( int i = 0 ; i < arr . length ( ) ; ++ i ) { Object o = arr . get ( i ) ; if ( o instanceof V8Array ) { o = convert ( ( V8Array ) o , List . class ) ; } else if ( o instanceof V8Object ) { o = convert ( ( V8Object ) o , Map . class ) ; } l . add ( o ) ; } return l ; } | Recursively convert a V8 array to a list and release it |
10,055 | private Map < String , Object > convertObject ( V8Object obj ) { if ( obj . isUndefined ( ) ) { return null ; } Map < String , Object > r = new LinkedHashMap < > ( ) ; for ( String k : obj . getKeys ( ) ) { Object o = obj . get ( k ) ; if ( o instanceof V8Array ) { o = convert ( ( V8Array ) o , List . class ) ; } else if ( o instanceof V8Object ) { o = convert ( ( V8Object ) o , Map . class ) ; } r . put ( k , o ) ; } return r ; } | Recursively convert a V8 object to a map and release it |
10,056 | private V8Array convertArguments ( Object [ ] args , Set < V8Value > newValues ) { V8Array result = new V8Array ( runtime ) ; newValues . add ( result ) ; for ( int i = 0 ; i < args . length ; ++ i ) { Object o = args [ i ] ; if ( o == null ) { result . push ( V8Value . NULL ) ; } else if ( o instanceof JsonObject || o instanceof Collection || o . getClass ( ) . isArray ( ) || o instanceof Map ) { V8Object v = runtime . executeObjectScript ( "(" + createJsonBuilder ( ) . toJson ( o ) . toString ( ) + ")" ) ; newValues . add ( v ) ; result . push ( v ) ; } else if ( o instanceof String ) { result . push ( ( String ) o ) ; } else if ( o instanceof Integer ) { result . push ( ( Integer ) o ) ; } else if ( o instanceof Boolean ) { result . push ( ( Boolean ) o ) ; } else if ( o instanceof Double ) { result . push ( ( Double ) o ) ; } else if ( o instanceof ItemDataProvider ) { o = new ItemDataProviderWrapper ( ( ItemDataProvider ) o ) ; V8Object v8o = convertJavaObject ( o ) ; newValues . add ( v8o ) ; result . push ( v8o ) ; } else if ( o instanceof AbbreviationProvider ) { o = new AbbreviationProviderWrapper ( ( AbbreviationProvider ) o ) ; V8Object v8o = convertJavaObject ( o ) ; newValues . add ( v8o ) ; result . push ( v8o ) ; } else if ( o instanceof VariableWrapper ) { o = new VariableWrapperWrapper ( ( VariableWrapper ) o ) ; V8Object v8o = convertJavaObject ( o ) ; newValues . add ( v8o ) ; result . push ( v8o ) ; } else if ( o instanceof V8ScriptRunner || o instanceof LocaleProvider ) { V8Object v8o = convertJavaObject ( o ) ; newValues . add ( v8o ) ; result . push ( v8o ) ; } else if ( o instanceof V8Value ) { V8Value v = ( V8Value ) o ; result . push ( v ) ; } else { throw new IllegalArgumentException ( "Unsupported argument: " + o . getClass ( ) ) ; } } return result ; } | Convert an array of object to a V8 array |
10,057 | private V8Object convertJavaObject ( Object o ) { V8Object v8o = new V8Object ( runtime ) ; Method [ ] methods = o . getClass ( ) . getMethods ( ) ; for ( Method m : methods ) { v8o . registerJavaMethod ( o , m . getName ( ) , m . getName ( ) , m . getParameterTypes ( ) ) ; } return v8o ; } | Convert a Java object to a V8 object . Register all methods of the Java object as functions in the created V8 object . |
10,058 | protected void indexVectorInternal ( double [ ] vector ) throws Exception { if ( vector . length != vectorLength ) { throw new Exception ( "The dimensionality of the vector is wrong!" ) ; } appendPersistentIndex ( vector ) ; if ( loadIndexInMemory ) { vectorsList . add ( vector ) ; } } | Append the vectors array with the given vector . The iid of this vector will be equal to the current value of the loadCounter . |
10,059 | protected BoundedPriorityQueue < Result > computeNearestNeighborsInternal ( int k , double [ ] queryVector ) throws Exception { BoundedPriorityQueue < Result > nn = new BoundedPriorityQueue < Result > ( new Result ( ) , k ) ; double lowest = Double . MAX_VALUE ; for ( int i = 0 ; i < ( vectorsList . size ( ) / vectorLength ) ; i ++ ) { boolean skip = false ; int startIndex = i * vectorLength ; double l2distance = 0 ; for ( int j = 0 ; j < vectorLength ; j ++ ) { l2distance += ( queryVector [ j ] - vectorsList . getQuick ( startIndex + j ) ) * ( queryVector [ j ] - vectorsList . getQuick ( startIndex + j ) ) ; if ( l2distance > lowest ) { skip = true ; break ; } } if ( ! skip ) { nn . offer ( new Result ( i , l2distance ) ) ; if ( i >= k ) { lowest = nn . last ( ) . getDistance ( ) ; } } } return nn ; } | Computes the k - nearest neighbors of the given query vector . The search is exhaustive but includes some optimizations that make it faster especially for high dimensional vectors . |
10,060 | protected BoundedPriorityQueue < Result > computeNearestNeighborsInternal ( int k , int iid ) throws Exception { double [ ] queryVector = getVector ( iid ) ; return computeNearestNeighborsInternal ( k , queryVector ) ; } | Computes the k - nearest neighbors of the vector with the given internal id . The search is exhaustive but includes some optimizations that make it faster especially for high dimensional vectors . |
10,061 | private void appendPersistentIndex ( double [ ] vector ) { TupleOutput output = new TupleOutput ( ) ; for ( int i = 0 ; i < vectorLength ; i ++ ) { output . writeDouble ( vector [ i ] ) ; } DatabaseEntry data = new DatabaseEntry ( ) ; TupleBinding . outputToEntry ( output , data ) ; DatabaseEntry key = new DatabaseEntry ( ) ; IntegerBinding . intToEntry ( loadCounter , key ) ; iidToVectorDB . put ( null , key , data ) ; } | Appends the persistent index with the given vector . |
10,062 | public void toCSV ( String fileName ) throws Exception { BufferedWriter out = new BufferedWriter ( new FileWriter ( new File ( fileName ) ) ) ; for ( int i = 0 ; i < loadCounter ; i ++ ) { String identifier = getId ( i ) ; double [ ] vector = getVector ( i ) ; out . write ( identifier ) ; for ( int k = 0 ; k < vector . length ; k ++ ) { out . write ( "," + vector [ k ] ) ; } out . write ( "\n" ) ; out . flush ( ) ; } out . close ( ) ; } | Writes all vectors in a csv formated file . The id goes first followed by the vector . |
10,063 | public static List < String > getSupportedOutputFormats ( ) throws IOException { ScriptRunner runner = getRunner ( ) ; try { return runner . callMethod ( "getSupportedFormats" , List . class ) ; } catch ( ScriptRunnerException e ) { throw new IllegalStateException ( "Could not get supported formats" , e ) ; } } | Calculates a list of supported output formats |
10,064 | public static boolean supportsStyle ( String style ) { String styleFileName = style ; if ( ! styleFileName . endsWith ( ".csl" ) ) { styleFileName = styleFileName + ".csl" ; } if ( ! styleFileName . startsWith ( "/" ) ) { styleFileName = "/" + styleFileName ; } URL url = CSL . class . getResource ( styleFileName ) ; return ( url != null ) ; } | Checks if a given citation style is supported |
10,065 | public static Set < String > getSupportedLocales ( ) throws IOException { Set < String > locales = getAvailableFiles ( "locales-" , "en-US" , "xml" ) ; try { List < String > baseLocales = getRunner ( ) . callMethod ( "getBaseLocales" , List . class ) ; locales . addAll ( baseLocales ) ; } catch ( ScriptRunnerException e ) { } return locales ; } | Calculates a list of available citation locales |
10,066 | private boolean isStyle ( String style ) { for ( int i = 0 ; i < style . length ( ) ; ++ i ) { char c = style . charAt ( i ) ; if ( ! Character . isWhitespace ( c ) ) { return ( c == '<' ) ; } } return false ; } | Checks if the given String contains the serialized XML representation of a style |
10,067 | private boolean isDependent ( String style ) { if ( ! style . trim ( ) . startsWith ( "<" ) ) { return false ; } Pattern p = Pattern . compile ( "rel\\s*=\\s*\"\\s*independent-parent\\s*\"" ) ; Matcher m = p . matcher ( style ) ; return m . find ( ) ; } | Test if the given string represents a dependent style |
10,068 | public String getIndependentParentLink ( String style ) throws ParserConfigurationException , IOException , SAXException { DocumentBuilderFactory factory = DocumentBuilderFactory . newInstance ( ) ; DocumentBuilder builder = factory . newDocumentBuilder ( ) ; InputSource src = new InputSource ( new StringReader ( style ) ) ; Document doc = builder . parse ( src ) ; NodeList links = doc . getElementsByTagName ( "link" ) ; for ( int i = 0 ; i < links . getLength ( ) ; ++ i ) { Node n = links . item ( i ) ; Node relAttr = n . getAttributes ( ) . getNamedItem ( "rel" ) ; if ( relAttr != null ) { if ( "independent-parent" . equals ( relAttr . getTextContent ( ) ) ) { Node hrefAttr = n . getAttributes ( ) . getNamedItem ( "href" ) ; if ( hrefAttr != null ) { return hrefAttr . getTextContent ( ) ; } } } } return null ; } | Parse a string representing a dependent parent style and get link to its independent parent style |
10,069 | public void setOutputFormat ( String format ) { try { runner . callMethod ( engine , "setOutputFormat" , format ) ; outputFormat = format ; } catch ( ScriptRunnerException e ) { throw new IllegalArgumentException ( "Could not set output format" , e ) ; } } | Sets the processor s output format |
10,070 | public static Bibliography makeAdhocBibliography ( String style , String outputFormat , CSLItemData ... items ) throws IOException { ItemDataProvider provider = new ListItemDataProvider ( items ) ; try ( CSL csl = new CSL ( provider , style ) ) { csl . setOutputFormat ( outputFormat ) ; String [ ] ids = new String [ items . length ] ; for ( int i = 0 ; i < items . length ; ++ i ) { ids [ i ] = items [ i ] . getId ( ) ; } csl . registerCitationItems ( ids ) ; return csl . makeBibliography ( ) ; } } | Creates an ad hoc bibliography from the given citation items . Calling this method is rather expensive as it initializes the CSL processor . If you need to create bibliographies multiple times in your application you should create the processor yourself and cache it if necessary . |
10,071 | public static String getDidYouMeanString ( Collection < String > available , String it ) { String message = "" ; Collection < String > mins = Levenshtein . findSimilar ( available , it ) ; if ( mins . size ( ) > 0 ) { if ( mins . size ( ) == 1 ) { message += "Did you mean this?" ; } else { message += "Did you mean one of these?" ; } for ( String m : mins ) { message += "\n\t" + m ; } } return message ; } | Finds strings similar to a string the user has entered and then generates a Did you mean one of these message |
10,072 | public double [ ] rotate ( double [ ] vector ) { DenseMatrix64F transformed = new DenseMatrix64F ( 1 , vector . length ) ; DenseMatrix64F original = DenseMatrix64F . wrap ( 1 , vector . length , vector ) ; CommonOps . mult ( original , randomMatrix , transformed ) ; return transformed . getData ( ) ; } | Randomly rotates a vector using the random rotation matrix that was created in the constructor . |
10,073 | public static Throwable getCause ( Throwable e ) { Throwable cause = null ; Throwable result = e ; while ( null != ( cause = result . getCause ( ) ) && ( result != cause ) ) { result = cause ; } return result ; } | find the root cause of an exception for nested BeansException case |
10,074 | public static void setupProperties ( String propertyAndValue , String separator ) { String [ ] tokens = propertyAndValue . split ( separator , 2 ) ; if ( tokens . length == 2 ) { String name = MonitoringViewProperties . PARFAIT + "." + tokens [ 0 ] ; String value = tokens [ 1 ] ; System . setProperty ( name , value ) ; } } | extract properties from arguments properties files or intuition |
10,075 | public static List < Specification > parseAllSpecifications ( ) { List < Specification > allMonitorables = new ArrayList < > ( ) ; try { File [ ] files = new File ( PATHNAME ) . listFiles ( ) ; if ( files != null ) { for ( File file : files ) { allMonitorables . addAll ( parseSpecification ( file ) ) ; } } } catch ( Exception e ) { } if ( allMonitorables . size ( ) < 1 ) { InputStream res = ParfaitAgent . class . getResourceAsStream ( RESOURCE ) ; allMonitorables . addAll ( parseInputSpecification ( res ) ) ; } return allMonitorables ; } | parse all configuration files from the parfait directory |
10,076 | public static List < Specification > parseSpecification ( File file ) { List < Specification > monitorables = new ArrayList < > ( ) ; try { InputStream stream = new FileInputStream ( file ) ; monitorables = parseInputSpecification ( stream ) ; } catch ( Exception e ) { logger . error ( String . format ( "Ignoring file %s" , file . getName ( ) ) ) ; } return monitorables ; } | parse a single configuration file from the parfait directory |
10,077 | public void clear ( ) { for ( String key : allKeys ( ) ) { mdcBridge . remove ( key ) ; } PER_THREAD_CONTEXTS . getUnchecked ( Thread . currentThread ( ) ) . clear ( ) ; } | Clears all values for the current thread . |
10,078 | public Map < String , Object > forThread ( Thread t ) { return new HashMap < String , Object > ( PER_THREAD_CONTEXTS . getUnchecked ( t ) ) ; } | Retrieves a copy of the thread context for the given thread |
10,079 | @ SuppressWarnings ( "unchecked" ) public synchronized < T > T registerOrReuse ( Monitorable < T > monitorable ) { String name = monitorable . getName ( ) ; if ( monitorables . containsKey ( name ) ) { Monitorable < ? > existingMonitorableWithSameName = monitorables . get ( name ) ; if ( monitorable . getSemantics ( ) . equals ( existingMonitorableWithSameName . getSemantics ( ) ) && monitorable . getUnit ( ) . equals ( existingMonitorableWithSameName . getUnit ( ) ) ) { return ( T ) existingMonitorableWithSameName ; } else { throw new IllegalArgumentException ( String . format ( "Cannot reuse the same name %s for a monitorable with different Semantics or Unit: requested=%s, existing=%s" , name , monitorable , existingMonitorableWithSameName ) ) ; } } else { monitorables . put ( name , monitorable ) ; notifyListenersOfNewMonitorable ( monitorable ) ; return ( T ) monitorable ; } } | Registers the monitorable if it does not already exist but otherwise returns an already registered Monitorable with the same name Semantics and UNnit definition . This method is useful when objects appear and disappear and then return and the lifecycle of the application requires an attempt to recreate the Monitorable without knowing if it has already been created . |
10,080 | @ GuardedBy ( "lock" ) private void cleanState ( ) { long eventTime = timeSource . get ( ) ; long bucketsToSkip = ( eventTime - headTime ) / window . getResolution ( ) ; while ( bucketsToSkip > 0 ) { headIndex = ( headIndex + 1 ) % interimValues . length ; bucketsToSkip -- ; overallValue -= interimValues [ headIndex ] ; interimValues [ headIndex ] = 0L ; headTime += window . getResolution ( ) ; } } | Clean out old data from the buckets getting us ready to enter a new bucket . interimValues headTime and headIndex comprise a circular buffer of the last n sub - values and the start time of the head bucket . On each write or get we progressively clear out entries in the circular buffer until headTime is within one tick of the current time ; we have then found the correct bucket . |
10,081 | private void writeToc ( ByteBuffer dataFileBuffer , TocType tocType , int entryCount , int firstEntryOffset ) { dataFileBuffer . putInt ( tocType . identifier ) ; dataFileBuffer . putInt ( entryCount ) ; dataFileBuffer . putLong ( firstEntryOffset ) ; } | Writes out a PCP MMV table - of - contents block . |
10,082 | public static TimeWindow of ( int resolution , long period , String name ) { return new TimeWindow ( resolution , period , name ) ; } | Factory method to create a new TimeWindow . |
10,083 | public Set < Library > getMissingLibraries ( MinecraftDirectory minecraftDir ) { Set < Library > missing = new LinkedHashSet < > ( ) ; for ( Library library : libraries ) if ( library . isMissing ( minecraftDir ) ) missing . add ( library ) ; return Collections . unmodifiableSet ( missing ) ; } | Returns the missing libraries in the given minecraft directory . |
10,084 | public synchronized void refreshWithToken ( String clientToken , String accessToken ) throws AuthenticationException { authResult = authenticationService . refresh ( Objects . requireNonNull ( clientToken ) , Objects . requireNonNull ( accessToken ) ) ; } | Refreshes the current session manually using token . |
10,085 | public BigDecimal getBigDecimal ( int index ) throws JSONException { Object object = this . get ( index ) ; try { return new BigDecimal ( object . toString ( ) ) ; } catch ( Exception e ) { throw new JSONException ( "JSONArray[" + index + "] could not convert to BigDecimal." ) ; } } | Get the BigDecimal value associated with an index . |
10,086 | public BigDecimal optBigDecimal ( int index , BigDecimal defaultValue ) { try { return this . getBigDecimal ( index ) ; } catch ( Exception e ) { return defaultValue ; } } | Get the optional BigDecimal value associated with an index . The defaultValue is returned if there is no value for the index or if the value is not a number and cannot be converted to a number . |
10,087 | public static Version resolveVersion ( MinecraftDirectory minecraftDir , String version ) throws IOException { Objects . requireNonNull ( minecraftDir ) ; Objects . requireNonNull ( version ) ; if ( doesVersionExist ( minecraftDir , version ) ) { try { return getVersionParser ( ) . parseVersion ( resolveVersionHierarchy ( version , minecraftDir ) , PlatformDescription . current ( ) ) ; } catch ( JSONException e ) { throw new IOException ( "Couldn't parse version json: " + version , e ) ; } } else { return null ; } } | Resolves the version . |
10,088 | public BigDecimal getBigDecimal ( String key ) throws JSONException { Object object = this . get ( key ) ; try { return new BigDecimal ( object . toString ( ) ) ; } catch ( Exception e ) { throw new JSONException ( "JSONObject[" + quote ( key ) + "] could not be converted to BigDecimal." ) ; } } | Get the BigDecimal value associated with a key . |
10,089 | public BigDecimal optBigDecimal ( String key , BigDecimal defaultValue ) { try { return this . getBigDecimal ( key ) ; } catch ( Exception e ) { return defaultValue ; } } | Get an optional BigDecimal associated with a key or the defaultValue if there is no such key or if its value is not a number . If the value is a string an attempt will be made to evaluate it as a number . |
10,090 | public static < T > CombinedDownloadTask < T > single ( DownloadTask < T > task ) { Objects . requireNonNull ( task ) ; return new SingleCombinedTask < T > ( task ) ; } | Creates a CombinedDownloadTask from a DownloadTask . |
10,091 | public static String createRandomAlphanumeric ( final int length ) { final Random r = ThreadLocalRandom . current ( ) ; final char [ ] randomChars = new char [ length ] ; for ( int i = 0 ; i < length ; ++ i ) { randomChars [ i ] = ALPHANUMERICS [ r . nextInt ( ALPHANUMERICS . length ) ] ; } return new String ( randomChars ) ; } | Creates a random Strings consisting of alphanumeric characters with a length of 32 . |
10,092 | public static void generateInvocationIdIfNecessary ( final TraceeBackend backend ) { if ( backend != null && ! backend . containsKey ( TraceeConstants . INVOCATION_ID_KEY ) && backend . getConfiguration ( ) . shouldGenerateInvocationId ( ) ) { backend . put ( TraceeConstants . INVOCATION_ID_KEY , Utilities . createRandomAlphanumeric ( backend . getConfiguration ( ) . generatedInvocationIdLength ( ) ) ) ; } } | Generate invocation id if it doesn t exist in TraceeBackend and configuration asks for one |
10,093 | public static void generateSessionIdIfNecessary ( final TraceeBackend backend , final String sessionId ) { if ( backend != null && ! backend . containsKey ( TraceeConstants . SESSION_ID_KEY ) && backend . getConfiguration ( ) . shouldGenerateSessionId ( ) ) { backend . put ( TraceeConstants . SESSION_ID_KEY , Utilities . createAlphanumericHash ( sessionId , backend . getConfiguration ( ) . generatedSessionIdLength ( ) ) ) ; } } | Generate session id hash if it doesn t exist in TraceeBackend and configuration asks for one |
10,094 | public Service get ( ) { String serviceName = this . environment . getVariable ( SERVICE_NAME_KEY ) ; if ( Strings . isNullOrEmpty ( serviceName ) ) { String errorMessage = String . format ( "Environment variable '%s' is not set" , SERVICE_NAME_KEY ) ; throw new IllegalArgumentException ( errorMessage ) ; } String serviceVersion = this . environment . getVariable ( SERVICE_VERSION_KEY ) ; return fetch ( serviceName , serviceVersion ) ; } | Fetches the service configuration using the service name and the service version read from the environment variables . |
10,095 | public static ResourceName create ( PathTemplate template , String path ) { ImmutableMap < String , String > values = template . match ( path ) ; if ( values == null ) { throw new ValidationException ( "path '%s' does not match template '%s'" , path , template ) ; } return new ResourceName ( template , values , null ) ; } | Creates a new resource name based on given template and path . The path must match the template otherwise null is returned . |
10,096 | public static ResourceName create ( PathTemplate template , Map < String , String > values ) { if ( ! values . keySet ( ) . containsAll ( template . vars ( ) ) ) { Set < String > unbound = Sets . newLinkedHashSet ( template . vars ( ) ) ; unbound . removeAll ( values . keySet ( ) ) ; throw new ValidationException ( "unbound variables: %s" , unbound ) ; } return new ResourceName ( template , values , null ) ; } | Creates a new resource name from a template and a value assignment for variables . |
10,097 | public static ResourceName createFromFullName ( PathTemplate template , String path ) { ImmutableMap < String , String > values = template . matchFromFullName ( path ) ; if ( values == null ) { return null ; } return new ResourceName ( template , values , null ) ; } | Creates a new resource name based on given template and path where the path contains an endpoint . If the path does not match null is returned . |
10,098 | public ResourceName withEndpoint ( String endpoint ) { return new ResourceName ( template , values , Preconditions . checkNotNull ( endpoint ) ) ; } | Returns a resource name with specified endpoint . |
10,099 | static ImmutableMap < String , TypeDescriptor > verifyAndSort ( Map < String , TypeDescriptor > typesByAlias ) { List < String > sorted = new ArrayList < > ( ) ; for ( Map . Entry < String , TypeDescriptor > entry : typesByAlias . entrySet ( ) ) { String alias = entry . getKey ( ) ; TypeDescriptor type = entry . getValue ( ) ; int i = sorted . size ( ) - 1 ; for ( ; i >= 0 ; i -- ) { TypeDescriptor other = typesByAlias . get ( sorted . get ( i ) ) ; if ( other . isSuperTypeOf ( type . getRawType ( ) ) ) { break ; } } sorted . add ( i + 1 , alias ) ; } ImmutableMap . Builder < String , TypeDescriptor > result = ImmutableMap . builder ( ) ; for ( String alias : sorted ) { result . put ( alias , typesByAlias . get ( alias ) ) ; } return result . build ( ) ; } | Sorts TypeDescriptors in topological order so that super class always precedes it s sub classes . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.