idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
34,500 | protected int lobHashCode ( int seed , SymbolTableProvider symbolTableProvider ) { int result = seed ; if ( ! isNullValue ( ) ) { CRC32 crc = new CRC32 ( ) ; crc . update ( getBytes ( ) ) ; result ^= ( int ) crc . getValue ( ) ; } return hashTypeAnnotations ( result , symbolTableProvider ) ; } | Calculate LOB hash code as XOR of seed with CRC - 32 of the LOB data . This distinguishes BLOBs from CLOBs | 83 | 31 |
34,501 | public final boolean skipDoubleColon ( ) throws IOException { int c = skip_over_whitespace ( ) ; if ( c != ' ' ) { unread_char ( c ) ; return false ; } c = read_char ( ) ; if ( c != ' ' ) { unread_char ( c ) ; unread_char ( ' ' ) ; return false ; } return true ; } | peeks into the input stream to see if the next token would be a double colon . If indeed this is the case it skips the two colons and returns true . If not it unreads the 1 or 2 real characters it read and return false . It always consumes any preceding whitespace . | 87 | 60 |
34,502 | public final int peekNullTypeSymbol ( ) throws IOException { // the '.' has to follow the 'null' immediately int c = read_char ( ) ; if ( c != ' ' ) { unread_char ( c ) ; return IonTokenConstsX . KEYWORD_none ; } // we have a dot, start reading through the following non-whitespace // and we'll collect it so that we can... | peeks into the input stream to see if we have an unquoted symbol that resolves to one of the ion types . If it does it consumes the input and returns the type keyword id . If not is unreads the non - whitespace characters and the dot which the input argument c should be . | 625 | 61 |
34,503 | public final int peekLobStartPunctuation ( ) throws IOException { int c = skip_over_lob_whitespace ( ) ; if ( c == ' ' ) { //unread_char(c); return IonTokenConstsX . TOKEN_STRING_DOUBLE_QUOTE ; } if ( c != ' ' ) { unread_char ( c ) ; return IonTokenConstsX . TOKEN_ERROR ; } c = read_char ( ) ; if ( c != ' ' ) { unread_... | peeks into the input stream to see what non - whitespace character is coming up . If it is a double quote or a triple quote this returns true as either distinguished the contents of a lob as distinctly a clob . Otherwise it returns false . In either case it unreads whatever non - whitespace it read to decide . | 220 | 66 |
34,504 | protected final void skip_clob_close_punctuation ( ) throws IOException { int c = skip_over_clob_whitespace ( ) ; if ( c == ' ' ) { c = read_char ( ) ; if ( c == ' ' ) { return ; } unread_char ( c ) ; c = ' ' ; } unread_char ( c ) ; error ( "invalid closing puctuation for CLOB" ) ; } | Expects optional whitespace then }} | 100 | 7 |
34,505 | private final boolean skip_whitespace ( CommentStrategy commentStrategy ) throws IOException { boolean any_whitespace = false ; int c ; loop : for ( ; ; ) { c = read_char ( ) ; switch ( c ) { case - 1 : break loop ; case ' ' : case ' ' : // new line normalization and counting is handled in read_char case CharacterSeque... | Skips whitespace and applies the given CommentStrategy to any comments found . Finishes at the starting position of the next token . | 272 | 27 |
34,506 | private final boolean is_2_single_quotes_helper ( ) throws IOException { int c = read_char ( ) ; if ( c != ' ' ) { unread_char ( c ) ; return false ; } c = read_char ( ) ; if ( c != ' ' ) { unread_char ( c ) ; unread_char ( ' ' ) ; return false ; } return true ; } | this peeks ahead to see if the next two characters are single quotes . this would finish off a triple quote when the first quote has been read . if it succeeds it consumes the two quotes it reads . if it fails it unreads | 90 | 47 |
34,507 | private final int scan_negative_for_numeric_type ( int c ) throws IOException { assert ( c == ' ' ) ; c = read_char ( ) ; int t = scan_for_numeric_type ( c ) ; if ( t == IonTokenConstsX . TOKEN_TIMESTAMP ) { bad_token ( c ) ; } unread_char ( c ) ; // and the caller need to unread the '-' return t ; } | variant of scan_numeric_type where the passed in start character was preceded by a minus sign . this will also unread the minus sign . | 102 | 31 |
34,508 | protected void load_raw_characters ( StringBuilder sb ) throws IOException { int c = read_char ( ) ; for ( ; ; ) { c = read_char ( ) ; switch ( c ) { case CharacterSequence . CHAR_SEQ_ESCAPED_NEWLINE_SEQUENCE_1 : case CharacterSequence . CHAR_SEQ_ESCAPED_NEWLINE_SEQUENCE_2 : case CharacterSequence . CHAR_SEQ_ESCAPED_NE... | this is used to load a previously marked set of bytes into the StringBuilder without escaping . It expects the caller to have set a save point so that the EOF will stop us at the right time . This does handle UTF8 decoding and surrogate encoding as the bytes are transfered . | 242 | 57 |
34,509 | private final int skip_timestamp_past_digits ( int min , int max ) throws IOException { int c ; // scan the first min characters insuring they're digits while ( min > 0 ) { c = read_char ( ) ; if ( ! IonTokenConstsX . isDigit ( c ) ) { error ( "invalid character '" + ( char ) c + "' encountered in timestamp" ) ; } -- m... | Helper method for skipping embedded digits inside a timestamp value This overload skips at least min and at most max digits and errors if a non - digit is encountered in the first min characters read | 163 | 37 |
34,510 | private final int load_exponent ( StringBuilder sb ) throws IOException { int c = read_char ( ) ; if ( c == ' ' || c == ' ' ) { sb . append ( ( char ) c ) ; c = read_char ( ) ; } c = load_digits ( sb , c ) ; if ( c == ' ' ) { sb . append ( ( char ) c ) ; c = read_char ( ) ; c = load_digits ( sb , c ) ; } return c ; } | can unread it | 117 | 4 |
34,511 | private final int load_digits ( StringBuilder sb , int c ) throws IOException { if ( ! IonTokenConstsX . isDigit ( c ) ) { return c ; } sb . append ( ( char ) c ) ; return readNumeric ( sb , Radix . DECIMAL , NumericState . DIGIT ) ; } | Accumulates digits into the buffer starting with the given character . | 77 | 13 |
34,512 | protected void skip_over_lob ( int lobToken , SavePoint sp ) throws IOException { switch ( lobToken ) { case IonTokenConstsX . TOKEN_STRING_DOUBLE_QUOTE : skip_double_quoted_string ( sp ) ; skip_clob_close_punctuation ( ) ; break ; case IonTokenConstsX . TOKEN_STRING_TRIPLE_QUOTE : skip_triple_quoted_clob_string ( sp )... | Skips over the closing }} too . | 191 | 8 |
34,513 | public void writeRaw ( byte [ ] value , int start , int len ) throws IOException { startValue ( TID_RAW ) ; _writer . write ( value , start , len ) ; _patch . patchValue ( len ) ; closeValue ( ) ; } | just transfer the bytes into the current patch as proper ion binary serialization | 56 | 14 |
34,514 | int writeBytes ( OutputStream userstream ) throws IOException { if ( _patch . getParent ( ) != null ) { throw new IllegalStateException ( "Tried to flush while not on top-level" ) ; } try { BlockedByteInputStream datastream = new BlockedByteInputStream ( _manager . buffer ( ) ) ; int size = writeRecursive ( datastream ... | Writes everything we ve got into the output stream performing all necessary patches along the way . | 106 | 18 |
34,515 | private IonDatagramLite load_helper ( IonReader reader ) throws IOException { IonDatagramLite datagram = new IonDatagramLite ( _system , _catalog ) ; IonWriter writer = _Private_IonWriterFactory . makeWriter ( datagram ) ; writer . writeValues ( reader ) ; return datagram ; } | This doesn t wrap IOException because some callers need to propagate it . | 74 | 15 |
34,516 | IonStruct getIonRepresentation ( ) { synchronized ( this ) { IonStruct image = myImage ; if ( image == null ) { // Start a new image from scratch myImage = image = makeIonRepresentation ( myImageFactory ) ; } return image ; } } | Only valid on local symtabs that already have an _image_factory set . | 59 | 18 |
34,517 | private IonStruct makeIonRepresentation ( ValueFactory factory ) { IonStruct ionRep = factory . newEmptyStruct ( ) ; ionRep . addTypeAnnotation ( ION_SYMBOL_TABLE ) ; SymbolTable [ ] importedTables = getImportedTablesNoCopy ( ) ; if ( importedTables . length > 1 ) { IonList importsList = factory . newEmptyList ( ) ; fo... | NOT SYNCHRONIZED! Call only from a synch d method . | 303 | 17 |
34,518 | private void recordLocalSymbolInIonRep ( IonStruct ionRep , String symbolName , int sid ) { assert sid >= myFirstLocalSid ; ValueFactory sys = ionRep . getSystem ( ) ; // TODO this is crazy inefficient and not as reliable as it looks // since it doesn't handle the case where's theres more than one list IonValue syms = ... | NOT SYNCHRONIZED! Call within constructor or from synched method . | 215 | 17 |
34,519 | @ Override public int read ( ) throws IOException { int nextChar = super . read ( ) ; // process the character if ( nextChar != - 1 ) { if ( nextChar == ' ' ) { m_line ++ ; pushColumn ( m_column ) ; m_column = 0 ; } else if ( nextChar == ' ' ) { int aheadChar = super . read ( ) ; // if the lookahead is not a newline co... | Uses the push back implementation but normalizes newlines to \ n . | 181 | 15 |
34,520 | private void unreadImpl ( int c , boolean updateCounts ) throws IOException { if ( c != - 1 ) { if ( updateCounts ) { if ( c == ' ' ) { m_line -- ; m_column = popColumn ( ) ; } else { m_column -- ; } m_consumed -- ; } super . unread ( c ) ; } } | Performs ths actual unread operation . | 81 | 9 |
34,521 | public static void verifyBinaryVersionMarker ( Reader reader ) throws IonException { try { int pos = reader . position ( ) ; //reader.sync(); //reader.setPosition(0); byte [ ] bvm = new byte [ BINARY_VERSION_MARKER_SIZE ] ; int len = readFully ( reader , bvm ) ; if ( len < BINARY_VERSION_MARKER_SIZE ) { String message ... | Verifies that a reader starts with a valid Ion cookie throwing an exception if it does not . | 307 | 19 |
34,522 | public static int lenVarUInt ( long longVal ) { assert longVal >= 0 ; if ( longVal < ( 1L << ( 7 * 1 ) ) ) return 1 ; // 7 bits if ( longVal < ( 1L << ( 7 * 2 ) ) ) return 2 ; // 14 bits if ( longVal < ( 1L << ( 7 * 3 ) ) ) return 3 ; // 21 bits if ( longVal < ( 1L << ( 7 * 4 ) ) ) return 4 ; // 28 bits if ( longVal < ... | Variable - length high - bit - terminating integer 7 data bits per byte . | 221 | 15 |
34,523 | public static int lenIonTimestamp ( Timestamp di ) { if ( di == null ) return 0 ; int len = 0 ; switch ( di . getPrecision ( ) ) { case FRACTION : case SECOND : { BigDecimal fraction = di . getFractionalSecond ( ) ; if ( fraction != null ) { assert fraction . signum ( ) >= 0 && ! fraction . equals ( BigDecimal . ZERO )... | this method computes the output length of this timestamp value in the Ion binary format . It does not include the length of the typedesc byte that preceeds the actual value . The output length of a null value is 0 as a result this this . | 339 | 51 |
34,524 | private final int stateFirstInStruct ( ) { int new_state ; if ( hasName ( ) ) { new_state = S_NAME ; } else if ( hasMaxId ( ) ) { new_state = S_MAX_ID ; } else if ( hasImports ( ) ) { new_state = S_IMPORT_LIST ; } else if ( hasLocalSymbols ( ) ) { new_state = S_SYMBOL_LIST ; } else { new_state = S_STRUCT_CLOSE ; } retu... | details of the symbol table we re reading . | 119 | 9 |
34,525 | private int growBuffer ( int offset ) { assert offset < 0 ; byte [ ] oldBuf = myBuffer ; int oldLen = oldBuf . length ; byte [ ] newBuf = new byte [ ( - offset + oldLen ) << 1 ] ; // Double the buffer int oldBegin = newBuf . length - oldLen ; System . arraycopy ( oldBuf , 0 , newBuf , oldBegin , oldLen ) ; myBuffer = n... | Grows the current buffer and returns the updated offset . | 114 | 11 |
34,526 | private void writeIonValue ( IonValue value ) throws IonException { final int valueOffset = myBuffer . length - myOffset ; switch ( value . getType ( ) ) { // scalars case BLOB : writeIonBlobContent ( ( IonBlob ) value ) ; break ; case BOOL : writeIonBoolContent ( ( IonBool ) value ) ; break ; case CLOB : writeIonClobC... | Writes the IonValue and its nested values recursively including annotations . | 363 | 15 |
34,527 | private void writeSymbolsField ( SymbolTable symTab ) { // SymbolTable's APIs doesn't expose an Iterator to traverse declared // symbol strings in reverse order. As such, we utilize these two // indexes to traverse the strings in reverse. int importedMaxId = symTab . getImportedMaxId ( ) ; int maxId = symTab . getMaxId... | Write declared local symbol names if any exists . | 230 | 9 |
34,528 | private List < String > getPercolationMatches ( JsonMetric jsonMetric ) throws IOException { HttpURLConnection connection = openConnection ( "/" + currentIndexName + "/" + jsonMetric . type ( ) + "/_percolate" , "POST" ) ; if ( connection == null ) { LOGGER . error ( "Could not connect to any configured elasticsearch i... | Execute a percolation request for the specified metric | 361 | 11 |
34,529 | private void addJsonMetricToPercolationIfMatching ( JsonMetric < ? extends Metric > jsonMetric , List < JsonMetric > percolationMetrics ) { if ( percolationFilter != null && percolationFilter . matches ( jsonMetric . name ( ) , jsonMetric . value ( ) ) ) { percolationMetrics . add ( jsonMetric ) ; } } | Add metric to list of matched percolation if needed | 92 | 11 |
34,530 | private HttpURLConnection createNewConnectionIfBulkSizeReached ( HttpURLConnection connection , int entriesWritten ) throws IOException { if ( entriesWritten % bulkSize == 0 ) { closeConnection ( connection ) ; return openConnection ( "/_bulk" , "POST" ) ; } return connection ; } | Create a new connection when the bulk size has hit the limit Checked on every write of a metric | 66 | 20 |
34,531 | private void writeJsonMetric ( JsonMetric jsonMetric , ObjectWriter writer , OutputStream out ) throws IOException { writer . writeValue ( out , new BulkIndexOperationHeader ( currentIndexName , jsonMetric . type ( ) ) ) ; out . write ( "\n" . getBytes ( ) ) ; writer . writeValue ( out , jsonMetric ) ; out . write ( "\... | serialize a JSON metric over the outputstream in a bulk request | 102 | 13 |
34,532 | private HttpURLConnection openConnection ( String uri , String method ) { for ( String host : hosts ) { try { URL templateUrl = new URL ( "http://" + host + uri ) ; HttpURLConnection connection = ( HttpURLConnection ) templateUrl . openConnection ( ) ; connection . setRequestMethod ( method ) ; connection . setConnectT... | Open a new HttpUrlConnection in case it fails it tries for the next host in the configured list | 171 | 21 |
34,533 | private void checkForIndexTemplate ( ) { try { HttpURLConnection connection = openConnection ( "/_template/metrics_template" , "HEAD" ) ; if ( connection == null ) { LOGGER . error ( "Could not connect to any configured elasticsearch instances: {}" , Arrays . asList ( hosts ) ) ; return ; } connection . disconnect ( ) ... | This index template is automatically applied to all indices which start with the index name The index template simply configures the name not to be analyzed | 510 | 27 |
34,534 | public void post ( Notification event ) { for ( Map . Entry < Object , List < SubscriberMethod > > entry : listeners . entrySet ( ) ) { for ( SubscriberMethod method : entry . getValue ( ) ) { if ( method . eventTypeToInvokeOn . isInstance ( event ) ) { try { method . methodToInvokeOnEvent . invoke ( entry . getKey ( )... | Post an event to the bus . All subscribers to the event class type posted will be notified . | 224 | 19 |
34,535 | @ Override public Void call ( SQLDatabase db ) throws DocumentStoreException { /* Pick winner and mark the appropriate revision with the 'current' flag set - There can only be one winner in a tree (or set of trees - if there is no common root) at any one time, so if there is a new winner, we only have to mark the old w... | Execute the callable selecting and marking the new winning revision . | 761 | 13 |
34,536 | public static byte [ ] encryptAES ( SecretKey key , byte [ ] iv , byte [ ] unencryptedBytes ) throws NoSuchPaddingException , NoSuchAlgorithmException , InvalidAlgorithmParameterException , InvalidKeyException , BadPaddingException , IllegalBlockSizeException { Cipher aesCipher = Cipher . getInstance ( "AES/CBC/PKCS5Pa... | AES Encrypt a byte array | 173 | 7 |
34,537 | public static byte [ ] decryptAES ( SecretKey key , byte [ ] iv , byte [ ] encryptedBytes ) throws NoSuchPaddingException , NoSuchAlgorithmException , InvalidAlgorithmParameterException , InvalidKeyException , BadPaddingException , IllegalBlockSizeException { Cipher aesCipher = Cipher . getInstance ( "AES/CBC/PKCS5Padd... | Decrypt an AES encrypted byte array | 170 | 7 |
34,538 | public String getAsString ( String key ) { Object value = mValues . get ( key ) ; return value != null ? value . toString ( ) : null ; } | Gets a value and converts it to a String . | 36 | 11 |
34,539 | public int getVersion ( ) throws SQLException { try { return this . submit ( new VersionCallable ( ) ) . get ( ) ; } catch ( InterruptedException e ) { logger . log ( Level . SEVERE , "Failed to get database version" , e ) ; throw new SQLException ( e ) ; } catch ( ExecutionException e ) { logger . log ( Level . SEVERE... | Returns the current version of the database . | 114 | 8 |
34,540 | public < T > Future < T > submit ( SQLCallable < T > callable ) { return this . submitTaskToQueue ( new SQLQueueCallable < T > ( db , callable ) ) ; } | Submits a database task for execution | 46 | 7 |
34,541 | public < T > Future < T > submitTransaction ( SQLCallable < T > callable ) { return this . submitTaskToQueue ( new SQLQueueCallable < T > ( db , callable , true ) ) ; } | Submits a database task for execution in a transaction | 49 | 10 |
34,542 | public void shutdown ( ) { // If shutdown has already been called then we don't need to shutdown again if ( acceptTasks . getAndSet ( false ) ) { //pass straight to queue, tasks passed via submitTaskToQueue will now be blocked. Future < ? > close = queue . submit ( new Runnable ( ) { @ Override public void run ( ) { db... | Shuts down this database queue and closes the underlying database connection . Any tasks previously submitted for execution will still be executed however the queue will not accept additional tasks | 203 | 31 |
34,543 | private < T > Future < T > submitTaskToQueue ( SQLQueueCallable < T > callable ) { if ( acceptTasks . get ( ) ) { return queue . submit ( callable ) ; } else { throw new RejectedExecutionException ( "Database is closed" ) ; } } | Adds a task to the queue checking if the queue is still open to accepting tasks | 64 | 16 |
34,544 | public synchronized String getSQLiteVersion ( ) { if ( this . sqliteVersion == null ) { try { this . sqliteVersion = this . submit ( new SQLiteVersionCallable ( ) ) . get ( ) ; return sqliteVersion ; } catch ( InterruptedException e ) { logger . log ( Level . WARNING , "Could not determine SQLite version" , e ) ; } cat... | Returns the SQLite Version . | 129 | 6 |
34,545 | private boolean validateEncryptionKeyData ( KeyData data ) { if ( data . getIv ( ) . length != ENCRYPTIONKEYCHAINMANAGER_AES_IV_SIZE ) { LOGGER . warning ( "IV does not have the expected size: " + ENCRYPTIONKEYCHAINMANAGER_AES_IV_SIZE + " bytes" ) ; return false ; } return true ; } | PRIVATE HELPER METHODS | 92 | 8 |
34,546 | @ SuppressWarnings ( "unchecked" ) private List < DBParameter > parametersToIndexRevision ( DocumentRevision rev , String indexName , List < FieldSort > fieldNames ) { Misc . checkNotNull ( rev , "rev" ) ; Misc . checkNotNull ( indexName , "indexName" ) ; Misc . checkNotNull ( fieldNames , "fieldNames" ) ; int arrayCou... | Returns a List of DBParameters containing table name and ContentValues to index a document in an index . | 695 | 20 |
34,547 | private static SQLDatabase internalOpenSQLDatabase ( File dbFile , KeyProvider provider ) throws SQLException { boolean runningOnAndroid = Misc . isRunningOnAndroid ( ) ; boolean useSqlCipher = ( provider . getEncryptionKey ( ) != null ) ; try { if ( runningOnAndroid ) { if ( useSqlCipher ) { return ( SQLDatabase ) Cla... | Internal method for creating a SQLDatabase that allows a null filename to create an in - memory database which can be useful for performing checks but creating in - memory databases is not permitted from outside of this class hence the private visibility . | 363 | 45 |
34,548 | public Task createDocument ( Task task ) { DocumentRevision rev = new DocumentRevision ( ) ; rev . setBody ( DocumentBodyFactory . create ( task . asMap ( ) ) ) ; try { DocumentRevision created = this . mDocumentStore . database ( ) . create ( rev ) ; return Task . fromRevision ( created ) ; } catch ( DocumentException... | Creates a task assigning an ID . | 98 | 8 |
34,549 | public Task updateDocument ( Task task ) throws ConflictException , DocumentStoreException { DocumentRevision rev = task . getDocumentRevision ( ) ; rev . setBody ( DocumentBodyFactory . create ( task . asMap ( ) ) ) ; try { DocumentRevision updated = this . mDocumentStore . database ( ) . update ( rev ) ; return Task ... | Updates a Task document within the DocumentStore . | 95 | 10 |
34,550 | public void deleteDocument ( Task task ) throws ConflictException , DocumentNotFoundException , DocumentStoreException { this . mDocumentStore . database ( ) . delete ( task . getDocumentRevision ( ) ) ; } | Deletes a Task document within the DocumentStore . | 44 | 10 |
34,551 | protected static boolean validFieldName ( String fieldName ) { String [ ] parts = fieldName . split ( "\\." ) ; for ( String part : parts ) { if ( part . startsWith ( "$" ) ) { String msg = String . format ( "Field names cannot start with a $ in field %s" , part ) ; logger . log ( Level . SEVERE , msg ) ; return false ... | Validate the field name string is usable . | 93 | 9 |
34,552 | public static String tokenizerToJson ( Tokenizer tokenizer ) { Map < String , String > settingsMap = new HashMap < String , String > ( ) ; if ( tokenizer != null ) { settingsMap . put ( TOKENIZE , tokenizer . tokenizerName ) ; // safe to store args even if they are null settingsMap . put ( TOKENIZE_ARGS , tokenizer . t... | Convert Tokenizer into serialized options or empty map if null | 107 | 13 |
34,553 | public static UnindexedMatcher matcherWithSelector ( Map < String , Object > selector ) { ChildrenQueryNode root = buildExecutionTreeForSelector ( selector ) ; if ( root == null ) { return null ; } UnindexedMatcher matcher = new UnindexedMatcher ( ) ; matcher . root = root ; return matcher ; } | Return a new initialised matcher . | 78 | 8 |
34,554 | protected static boolean compareLT ( Object l , Object r ) { if ( l == null || r == null ) { return false ; // null fails all lt/gt/lte/gte tests } else if ( ! ( l instanceof String || l instanceof Number ) ) { String msg = String . format ( "Value in document not a Number or String: %s" , l ) ; logger . log ( Level . ... | 4 . BLOB | 255 | 4 |
34,555 | public List < String > documentIds ( ) { List < String > documentIds = new ArrayList < String > ( ) ; List < DocumentRevision > docs = CollectionUtils . newArrayList ( iterator ( ) ) ; for ( DocumentRevision doc : docs ) { documentIds . add ( doc . getId ( ) ) ; } return documentIds ; } | Returns a list of the document IDs in this query result . | 80 | 12 |
34,556 | public static List < String > createRevisionIdHistory ( DocumentRevs documentRevs ) { validateDocumentRevs ( documentRevs ) ; String latestRevision = documentRevs . getRev ( ) ; int generation = CouchUtils . generationFromRevId ( latestRevision ) ; assert generation == documentRevs . getRevisions ( ) . getStart ( ) ; L... | Create the list of the revision IDs in ascending order . | 145 | 11 |
34,557 | @ Override public List < DocumentRevision > delete ( final String id ) throws DocumentNotFoundException , DocumentStoreException { Misc . checkNotNull ( id , "ID" ) ; try { if ( id . startsWith ( CouchConstants . _local_prefix ) ) { String localId = id . substring ( CouchConstants . _local_prefix . length ( ) ) ; delet... | delete all leaf nodes | 232 | 4 |
34,558 | public static < T > T get ( Future < T > future ) throws ExecutionException { try { return future . get ( ) ; } catch ( InterruptedException e ) { logger . log ( Level . SEVERE , "Re-throwing InterruptedException as ExecutionException" ) ; throw new ExecutionException ( e ) ; } } | helper to avoid having to catch ExecutionExceptions | 70 | 10 |
34,559 | public static String join ( String separator , Collection < String > stringsToJoin ) { StringBuilder builder = new StringBuilder ( ) ; // Check if there is at least 1 element then use do/while to avoid trailing separator int index = stringsToJoin . size ( ) ; for ( String str : stringsToJoin ) { index -- ; if ( str != ... | Utility to join strings with a separator . Skips null strings and does not append a trailing separator . | 112 | 23 |
34,560 | public static void checkNotNull ( Object param , String errorMessagePrefix ) throws IllegalArgumentException { checkArgument ( param != null , ( errorMessagePrefix != null ? errorMessagePrefix : "Parameter" ) + " must not be null." ) ; } | Check that a parameter is not null and throw IllegalArgumentException with a message of errorMessagePrefix + must not be null . if it is null defaulting to Parameter must not be null . . | 57 | 42 |
34,561 | public static void checkNotNullOrEmpty ( String param , String errorMessagePrefix ) throws IllegalArgumentException { checkNotNull ( param , errorMessagePrefix ) ; checkArgument ( ! param . isEmpty ( ) , ( errorMessagePrefix != null ? errorMessagePrefix : "Parameter" ) + " must not be empty." ) ; } | Check that a string parameter is not null or empty and throw IllegalArgumentException with a message of errorMessagePrefix + must not be empty . if it is empty defaulting to Parameter must not be empty . | 75 | 44 |
34,562 | private void setup ( ) { try { this . partBoundary = ( "--" + boundary ) . getBytes ( "UTF-8" ) ; this . trailingBoundary = ( "--" + boundary + "--" ) . getBytes ( "UTF-8" ) ; this . contentType = "content-type: application/json" . getBytes ( "UTF-8" ) ; } catch ( UnsupportedEncodingException e ) { throw new RuntimeExc... | common constructor stuff | 181 | 3 |
34,563 | public static void updateAllIndexes ( List < Index > indexes , Database database , SQLDatabaseQueue queue ) throws QueryException { IndexUpdater updater = new IndexUpdater ( database , queue ) ; updater . updateAllIndexes ( indexes ) ; } | Update all indexes in a set . | 56 | 7 |
34,564 | public static void updateIndex ( String indexName , List < FieldSort > fieldNames , Database database , SQLDatabaseQueue queue ) throws QueryException { IndexUpdater updater = new IndexUpdater ( database , queue ) ; updater . updateIndex ( indexName , fieldNames ) ; } | Update a single index . | 62 | 5 |
34,565 | @ JsonAnySetter public void setOthers ( String name , Object value ) { if ( name . startsWith ( "_" ) ) { // Just be defensive throw new RuntimeException ( "This is a reserved field, and should not be treated as document content." ) ; } this . others . put ( name , value ) ; } | Jackson will automatically put any field it can not find match to this | 70 | 13 |
34,566 | @ SuppressWarnings ( "unchecked" ) public static Map < String , Object > normaliseAndValidateQuery ( Map < String , Object > query ) throws QueryException { boolean isWildCard = false ; if ( query . isEmpty ( ) ) { isWildCard = true ; } // First expand the query to include a leading compound predicate // if there isn't... | Expand implicit operators in a query and validate | 596 | 9 |
34,567 | @ SuppressWarnings ( "unchecked" ) private static void validateSelector ( Map < String , Object > selector ) throws QueryException { String topLevelOp = ( String ) selector . keySet ( ) . toArray ( ) [ 0 ] ; // top level op can only be $and or $or after normalisation if ( topLevelOp . equals ( AND ) || topLevelOp . equ... | we are going to need to walk the query tree to validate it before executing it | 151 | 16 |
34,568 | @ SuppressWarnings ( "unchecked" ) private static void validateCompoundOperatorClauses ( List < Object > clauses , Boolean [ ] textClauseLimitReached ) throws QueryException { for ( Object obj : clauses ) { if ( ! ( obj instanceof Map ) ) { String msg = String . format ( "Operator argument must be a Map %s" , clauses .... | This method runs the list of clauses making up the selector through a series of validation steps and returns whether the clause list is valid or not . | 404 | 28 |
34,569 | public InputStream getInputStream ( File file , Attachment . Encoding encoding ) throws IOException { // First, open a stream to the raw bytes on disk. // Then, if we have a key assume the file is encrypted, so add a stream // to the chain which decrypts the data as we read from disk. // Finally, decode (unzip) the dat... | Return a stream to be used to read from the file on disk . | 265 | 14 |
34,570 | public OutputStream getOutputStream ( File file , Attachment . Encoding encoding ) throws IOException { // First, open a stream to the raw bytes on disk. // Then, if we have a key assume the file should be encrypted before writing, // so wrap the file stream in a stream which encrypts during writing. // If the attachme... | Get stream for writing attachment data to disk . | 397 | 9 |
34,571 | public void addValueToKey ( K key , V value ) { this . addValuesToKey ( key , Collections . singletonList ( value ) ) ; } | Add a value to the map under the existing key or creating a new key if it does not yet exist . | 34 | 22 |
34,572 | public void addValuesToKey ( K key , Collection < V > valueCollection ) { if ( ! valueCollection . isEmpty ( ) ) { // Create a new collection to store the values (will be changed to internal type by call // to putIfAbsent anyway) List < V > collectionToAppendValuesOn = new ArrayList < V > ( ) ; List < V > existing = th... | Add a collection of one or more values to the map under the existing key or creating a new key if it does not yet exist in the map . | 145 | 30 |
34,573 | private String queryAsString ( Map < String , Object > query ) { ArrayList < String > queryParts = new ArrayList < String > ( query . size ( ) ) ; for ( Map . Entry < String , Object > entry : query . entrySet ( ) ) { String value = this . encodeQueryParameter ( entry . getValue ( ) . toString ( ) ) ; String key = this... | Joins the entries in a map into a URL - encoded query string . | 138 | 15 |
34,574 | void replicationComplete ( ) { reloadTasksFromModel ( ) ; Toast . makeText ( getApplicationContext ( ) , R . string . replication_completed , Toast . LENGTH_LONG ) . show ( ) ; dismissDialog ( DIALOG_PROGRESS ) ; } | Called by TasksModel when it receives a replication complete callback . TasksModel takes care of calling this on the main thread . | 60 | 27 |
34,575 | void replicationError ( ) { Log . i ( LOG_TAG , "error()" ) ; reloadTasksFromModel ( ) ; Toast . makeText ( getApplicationContext ( ) , R . string . replication_error , Toast . LENGTH_LONG ) . show ( ) ; dismissDialog ( DIALOG_PROGRESS ) ; } | Called by TasksModel when it receives a replication error callback . TasksModel takes care of calling this on the main thread . | 73 | 27 |
34,576 | protected static PreparedAttachment prepareAttachment ( String attachmentsDir , AttachmentStreamFactory attachmentStreamFactory , Attachment attachment , long length , long encodedLength ) throws AttachmentException { PreparedAttachment pa = new PreparedAttachment ( attachment , attachmentsDir , length , attachmentStre... | prepare an attachment and check validity of length and encodedLength metadata | 241 | 13 |
34,577 | public static Map < String , SavedAttachment > findExistingAttachments ( Map < String , ? extends Attachment > attachments ) { Map < String , SavedAttachment > existingAttachments = new HashMap < String , SavedAttachment > ( ) ; for ( Map . Entry < String , ? extends Attachment > a : attachments . entrySet ( ) ) { if (... | Return a map of the existing attachments in the map passed in . | 125 | 13 |
34,578 | public static Map < String , Attachment > findNewAttachments ( Map < String , ? extends Attachment > attachments ) { Map < String , Attachment > newAttachments = new HashMap < String , Attachment > ( ) ; for ( Map . Entry < String , ? extends Attachment > a : attachments . entrySet ( ) ) { if ( ! ( a instanceof SavedAt... | Return a map of the new attachments in the map passed in . | 115 | 13 |
34,579 | public static void copyAttachment ( SQLDatabase db , long parentSequence , long newSequence , String filename ) throws SQLException { Cursor c = null ; try { c = db . rawQuery ( SQL_ATTACHMENTS_SELECT , new String [ ] { filename , String . valueOf ( parentSequence ) } ) ; copyCursorValuesToNewSequence ( db , c , newSeq... | Copy a single attachment for a given revision to a new revision . | 109 | 13 |
34,580 | public static void purgeAttachments ( SQLDatabase db , String attachmentsDir ) { // it's easier to deal with Strings since java doesn't know how to compare byte[]s Set < String > currentKeys = new HashSet < String > ( ) ; Cursor c = null ; try { // delete attachment table entries for revs which have been purged db . de... | Called by DatabaseImpl on the execution queue this needs to have the db passed to it . | 535 | 19 |
34,581 | static String generateFilenameForKey ( SQLDatabase db , String keyString ) throws NameGenerationException { String filename = null ; long result = - 1 ; // -1 is error for insert call int tries = 0 ; while ( result == - 1 && tries < 200 ) { byte [ ] randomBytes = new byte [ 20 ] ; filenameRandom . nextBytes ( randomByt... | Iterate candidate filenames generated from the filenameRandom generator until we find one which doesn t already exist . | 219 | 22 |
34,582 | public void put ( int index , long value ) { if ( desc . get ( index ) != Cursor . FIELD_TYPE_INTEGER ) { throw new IllegalArgumentException ( "Inserting an integer, but expecting " + getTypeName ( desc . get ( index ) ) ) ; } this . values . add ( index , value ) ; } | Internally we always store the SQLite number as long | 76 | 11 |
34,583 | private URI addAuthInterceptorIfRequired ( URI uri ) { String uriProtocol = uri . getScheme ( ) ; String uriHost = uri . getHost ( ) ; String uriPath = uri . getRawPath ( ) ; int uriPort = getDefaultPort ( uri ) ; setUserInfo ( uri ) ; setAuthInterceptor ( uriHost , uriPath , uriProtocol , uriPort ) ; return scrubUri (... | - else add cookie interceptor if needed | 127 | 8 |
34,584 | public E username ( String username ) { Misc . checkNotNull ( username , "username" ) ; this . username = username ; //noinspection unchecked return ( E ) this ; } | Sets the username to use when authenticating with the server . | 39 | 13 |
34,585 | public E password ( String password ) { Misc . checkNotNull ( password , "password" ) ; this . password = password ; //noinspection unchecked return ( E ) this ; } | Sets the password to use when authenticating with the server . | 39 | 13 |
34,586 | @ Override public List < Index > listIndexes ( ) throws QueryException { try { return DatabaseImpl . get ( dbQueue . submit ( new ListIndexesCallable ( ) ) ) ; } catch ( ExecutionException e ) { String msg = "Failed to list indexes" ; logger . log ( Level . SEVERE , msg , e ) ; throw new QueryException ( msg , e ) ; } ... | Get a list of indexes and their definitions as a Map . | 87 | 12 |
34,587 | private Index ensureIndexed ( List < FieldSort > fieldNames , String indexName , IndexType indexType , Tokenizer tokenizer ) throws QueryException { // synchronized to prevent race conditions in IndexCreator when looking for existing indexes // which have the same name or definition synchronized ( this ) { return Index... | Add a single possibly compound index for the given field names . | 93 | 12 |
34,588 | @ Override public void deleteIndex ( final String indexName ) throws QueryException { Misc . checkNotNullOrEmpty ( indexName , "indexName" ) ; Future < Void > result = dbQueue . submitTransaction ( new DeleteIndexCallable ( indexName ) ) ; try { result . get ( ) ; } catch ( ExecutionException e ) { String message = "Ex... | Delete an index . | 159 | 4 |
34,589 | @ Override public void refreshAllIndexes ( ) throws QueryException { List < Index > indexes = listIndexes ( ) ; IndexUpdater . updateAllIndexes ( indexes , database , dbQueue ) ; } | Update all indexes . | 46 | 4 |
34,590 | public QueryResult find ( Map < String , Object > query , final List < Index > indexes , long skip , long limit , List < String > fields , final List < FieldSort > sortDocument ) throws QueryException { // // Validate inputs // fields = normaliseFields ( fields ) ; // will throw IllegalArgumentException if there are in... | Execute the query passed using the selection of index definition provided . | 545 | 13 |
34,591 | private void validateFields ( List < String > fields ) { if ( fields == null ) { return ; } List < String > badFields = new ArrayList < String > ( ) ; for ( String field : fields ) { if ( field . contains ( "." ) ) { badFields . add ( field ) ; } } if ( ! badFields . isEmpty ( ) ) { String msg = String . format ( "Proj... | Checks if the fields are valid . | 144 | 8 |
34,592 | private List < String > sortIds ( Set < String > docIdSet , List < FieldSort > sortDocument , List < Index > indexes , SQLDatabase db ) throws QueryException { boolean smallResultSet = ( docIdSet . size ( ) < SMALL_RESULT_SET_SIZE_THRESHOLD ) ; SqlParts orderBy = sqlToSortIds ( docIdSet , sortDocument , indexes ) ; Lis... | Return ordered list of document IDs using provided indexes . | 348 | 10 |
34,593 | protected static SqlParts sqlToSortIds ( Set < String > docIdSet , List < FieldSort > sortDocument , List < Index > indexes ) throws QueryException { String chosenIndex = chooseIndexForSort ( sortDocument , indexes ) ; if ( chosenIndex == null ) { String msg = String . format ( Locale . ENGLISH , "No single index can s... | Return SQL to get ordered list of docIds . | 536 | 11 |
34,594 | public static String generateNextRevisionId ( String revisionId ) { validateRevisionId ( revisionId ) ; int generation = generationFromRevId ( revisionId ) ; String digest = createUUID ( ) ; return Integer . toString ( generation + 1 ) + "-" + digest ; } | DBObject IDs have a generation count a hyphen and a UUID . | 61 | 15 |
34,595 | public static AndroidSQLCipherSQLite open ( File path , KeyProvider provider ) { //Call SQLCipher-based method for opening database, or creating if database not found SQLiteDatabase db = SQLiteDatabase . openOrCreateDatabase ( path , KeyUtils . sqlCipherKeyForKeyProvider ( provider ) , null ) ; return new AndroidSQLCip... | Constructor for creating SQLCipher - based SQLite database . | 85 | 13 |
34,596 | protected void upgradePreferences ( ) { String alarmDueElapsed = "com.cloudant.sync.replication.PeriodicReplicationService.alarmDueElapsed" ; if ( mPrefs . contains ( alarmDueElapsed ) ) { // These are old style preferences. We need to rewrite them in the new form that allows // multiple replication policies. String al... | If the stored preferences are in the old format upgrade them to the new format so that the app continues to work after upgrade to this version . | 367 | 28 |
34,597 | public synchronized void startPeriodicReplication ( ) { if ( ! isPeriodicReplicationEnabled ( ) ) { setPeriodicReplicationEnabled ( true ) ; AlarmManager alarmManager = ( AlarmManager ) getSystemService ( Context . ALARM_SERVICE ) ; Intent alarmIntent = new Intent ( this , clazz ) ; alarmIntent . setAction ( PeriodicRe... | Start periodic replications . | 349 | 5 |
34,598 | public synchronized void stopPeriodicReplication ( ) { if ( isPeriodicReplicationEnabled ( ) ) { setPeriodicReplicationEnabled ( false ) ; AlarmManager alarmManager = ( AlarmManager ) getSystemService ( Context . ALARM_SERVICE ) ; Intent alarmIntent = new Intent ( this , clazz ) ; alarmIntent . setAction ( PeriodicRepl... | Stop replications currently in progress and cancel future scheduled replications . | 166 | 13 |
34,599 | private void setPeriodicReplicationEnabled ( boolean running ) { SharedPreferences . Editor editor = mPrefs . edit ( ) ; editor . putBoolean ( constructKey ( PERIODIC_REPLICATION_ENABLED_SUFFIX ) , running ) ; editor . apply ( ) ; } | Set a flag in SharedPreferences to indicate whether periodic replications are enabled . | 66 | 16 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.