idx
int64
0
165k
question
stringlengths
73
5.81k
target
stringlengths
5
918
133,700
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 =...
Prints out usage information
133,701
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
133,702
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
133,703
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 ...
Reads a value for a given type
133,704
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
133,705
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/" + s...
This method is used to compile the Flickr URL from its parts .
133,706
public void setFromAddress ( final String name , final String fromAddress ) { fromRecipient = new Recipient ( name , fromAddress , null ) ; }
Sets the sender address .
133,707
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 .
133,708
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 .
133,709
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 .
133,710
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 .
133,711
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 ...
This method exemplifies multi - threaded image download from a list of urls . It uses 5 download threads .
133,712
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 .
133,713
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 ...
Returns the index of the centroid which is closer to the given descriptor .
133,714
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 . setReadT...
Reads a string from a URL
133,715
public static String readFileToString ( File f , String encoding ) throws IOException { return readStreamToString ( new FileInputStream ( f ) , encoding ) ; }
Reads a string from a file .
133,716
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 . toS...
Reads a string from a stream . Closes the stream after reading .
133,717
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...
Reads a byte array from a stream . Closes the stream after reading .
133,718
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 ) ; fo...
Converts an object to a JSON object
133,719
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 == Tra...
Append the PQ index with the given vector .
133,720
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 == Transf...
Computes and returns the k nearest neighbors of the query vector using the ADC approach .
133,721
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 ] = ...
Computes and returns the k nearest neighbors of the query internal id using the SDC approach .
133,722
protected OAuth createOAuth ( String consumerKey , String consumerSecret , String redirectUri ) { return new OAuth1 ( consumerKey , consumerSecret ) ; }
Creates an OAuth object
133,723
private void setSpacing ( ) { final int verticalSpacing = styledAttributes . getDimensionPixelOffset ( R . styleable . PinLock_keypadVerticalSpacing , 2 ) ; final int horizontalSpacing = styledAttributes . getDimensionPixelOffset ( R . styleable . PinLock_keypadHorizontalSpacing , 2 ) ; setVerticalSpacing ( verticalSpa...
Setting up vertical and horizontal spacing for the view
133,724
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 ...
Transforms the image into a vector and returns the result .
133,725
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:...
Example of SURF extraction multiVLAD aggregation and PCA - projection of a single image using this class .
133,726
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 ; ...
Copies all items from the given provider and sanitizes its IDs
133,727
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 = fir...
Generates a human - readable ID for an item
133,728
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
133,729
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 ) )...
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 .
133,730
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 { ret...
Returns the internal id assigned to the vector with the given id or - 1 if the id is not found . Accesses the BDB store!
133,731
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 ( nu...
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!
133,732
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 . intToE...
This method is used to set the geolocation of a previously indexed vector . If the geolocation is already set this method replaces it .
133,733
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 ...
This method is used to set the metadata of a previously indexed vector . If the metadata is already set this methods replaces it .
133,734
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 ) ) )...
This is a utility method that can be used to dump the contents of the idToIidDB to a txt file .
133,735
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 / ...
This method can be called to output indexing time measurements .
133,736
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 .
133,737
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 ...
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 .
133,738
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 .
133,739
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 { numPendi...
Takes and returns a vectorization result from the pool .
133,740
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 .
133,741
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
133,742
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 ) { ...
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 .
133,743
public static boolean isValid ( final String email , final EmailAddressValidationCriteria emailAddressValidationCriteria ) { return buildValidEmailPattern ( emailAddressValidationCriteria ) . matcher ( email ) . matches ( ) ; }
Validates an e - mail with given validation flags .
133,744
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 ) ...
Recursively convert a V8 array to a list and release it
133,745
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 ...
Recursively convert a V8 object to a map and release it
133,746
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...
Convert an array of object to a V8 array
133,747
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 .
133,748
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 .
133,749
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 ( ) / vectorLe...
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 .
133,750
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 .
133,751
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 DatabaseEntr...
Appends the persistent index with the given vector .
133,752
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 ....
Writes all vectors in a csv formated file . The id goes first followed by the vector .
133,753
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
133,754
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 ) ; re...
Checks if a given citation style is supported
133,755
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 ...
Calculates a list of available citation locales
133,756
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
133,757
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
133,758
public String getIndependentParentLink ( String style ) throws ParserConfigurationException , IOException , SAXException { DocumentBuilderFactory factory = DocumentBuilderFactory . newInstance ( ) ; DocumentBuilder builder = factory . newDocumentBuilder ( ) ; InputSource src = new InputSource ( new StringReader ( style...
Parse a string representing a dependent parent style and get link to its independent parent style
133,759
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
133,760
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 [ it...
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 .
133,761
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 ...
Finds strings similar to a string the user has entered and then generates a Did you mean one of these message
133,762
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 .
133,763
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
133,764
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
133,765
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 ( Ex...
parse all configuration files from the parfait directory
133,766
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 ...
parse a single configuration file from the parfait directory
133,767
public void clear ( ) { for ( String key : allKeys ( ) ) { mdcBridge . remove ( key ) ; } PER_THREAD_CONTEXTS . getUnchecked ( Thread . currentThread ( ) ) . clear ( ) ; }
Clears all values for the current thread .
133,768
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
133,769
@ 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 ( ) ...
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 ...
133,770
@ 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 ] ...
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...
133,771
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 .
133,772
public static TimeWindow of ( int resolution , long period , String name ) { return new TimeWindow ( resolution , period , name ) ; }
Factory method to create a new TimeWindow .
133,773
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 .
133,774
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 .
133,775
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 .
133,776
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 .
133,777
public static Version resolveVersion ( MinecraftDirectory minecraftDir , String version ) throws IOException { Objects . requireNonNull ( minecraftDir ) ; Objects . requireNonNull ( version ) ; if ( doesVersionExist ( minecraftDir , version ) ) { try { return getVersionParser ( ) . parseVersion ( resolveVersionHierarch...
Resolves the version .
133,778
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 .
133,779
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 .
133,780
public static < T > CombinedDownloadTask < T > single ( DownloadTask < T > task ) { Objects . requireNonNull ( task ) ; return new SingleCombinedTask < T > ( task ) ; }
Creates a CombinedDownloadTask from a DownloadTask .
133,781
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 ( randomCh...
Creates a random Strings consisting of alphanumeric characters with a length of 32 .
133,782
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 . createRand...
Generate invocation id if it doesn t exist in TraceeBackend and configuration asks for one
133,783
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...
Generate session id hash if it doesn t exist in TraceeBackend and configuration asks for one
133,784
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 serv...
Fetches the service configuration using the service name and the service version read from the environment variables .
133,785
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 .
133,786
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 ( "un...
Creates a new resource name from a template and a value assignment for variables .
133,787
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 .
133,788
public ResourceName withEndpoint ( String endpoint ) { return new ResourceName ( template , values , Preconditions . checkNotNull ( endpoint ) ) ; }
Returns a resource name with specified endpoint .
133,789
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 . getVal...
Sorts TypeDescriptors in topological order so that super class always precedes it s sub classes .
133,790
public static Distribution addSample ( double value , Distribution distribution ) { Builder builder = distribution . toBuilder ( ) ; switch ( distribution . getBucketOptionCase ( ) ) { case EXPLICIT_BUCKETS : updateStatistics ( value , builder ) ; updateExplicitBuckets ( value , builder ) ; return builder . build ( ) ;...
Updates as new distribution that contains value added to an existing one .
133,791
public synchronized void start ( ) { if ( running ) { log . atInfo ( ) . log ( "%s is already started" , this ) ; return ; } log . atInfo ( ) . log ( "starting %s" , this ) ; this . stopped = false ; this . running = true ; this . reportStopwatch . reset ( ) . start ( ) ; try { schedulerThread = threads . newThread ( n...
Starts processing .
133,792
public void stop ( ) { Preconditions . checkState ( running , "Cannot stop if it's not running" ) ; synchronized ( this ) { log . atInfo ( ) . log ( "stopping client background thread and flushing the report aggregator" ) ; for ( ReportRequest req : reportAggregator . clear ( ) ) { try { transport . services ( ) . repo...
Stops processing .
133,793
public CheckResponse check ( CheckRequest req ) { startIfStopped ( ) ; statistics . totalChecks . incrementAndGet ( ) ; Stopwatch w = Stopwatch . createStarted ( ticker ) ; CheckResponse resp = checkAggregator . check ( req ) ; statistics . totalCheckCacheLookupTimeMillis . addAndGet ( w . elapsed ( TimeUnit . MILLISEC...
Process a check request .
133,794
public void report ( ReportRequest req ) { startIfStopped ( ) ; statistics . totalReports . incrementAndGet ( ) ; statistics . reportedOperations . addAndGet ( req . getOperationsCount ( ) ) ; Stopwatch w = Stopwatch . createStarted ( ticker ) ; boolean reported = reportAggregator . report ( req ) ; statistics . totalR...
Process a report request .
133,795
public Set < TraceeBackendProvider > getBackendProviders ( ) { final Map < ClassLoader , Set < TraceeBackendProvider > > cacheCopy = providersPerClassloader ; final Set < TraceeBackendProvider > providerFromContextClassLoader = getTraceeProviderFromClassloader ( cacheCopy , GetClassLoader . fromContext ( ) ) ; if ( ! p...
Find correct backend provider for the current context classloader . If no context classloader is available a fallback with the classloader of this resolver class is taken
133,796
Set < TraceeBackendProvider > getDefaultTraceeBackendProvider ( ) { try { final ClassLoader classLoader = GetClassLoader . fromContext ( ) ; final Class < ? > slf4jTraceeBackendProviderClass = Class . forName ( "io.tracee.backend.slf4j.Slf4jTraceeBackendProvider" , true , classLoader ) ; final TraceeBackendProvider ins...
Loads the default implementation
133,797
public static java . util . Set < String > all ( ) { java . util . Set < String > set = new java . util . HashSet < String > ( ) ; set . add ( CLOUD_PLATFORM ) ; set . add ( SERVICECONTROL ) ; return java . util . Collections . unmodifiableSet ( set ) ; }
Returns an unmodifiable set that contains all scopes declared by this class .
133,798
public void filter ( final ClientRequestContext requestContext ) { if ( ! backend . isEmpty ( ) && backend . getConfiguration ( ) . shouldProcessContext ( OutgoingRequest ) ) { final Map < String , String > filtered = backend . getConfiguration ( ) . filterDeniedParams ( backend . copyToMap ( ) , OutgoingRequest ) ; re...
This method handles the outgoing request
133,799
public void filter ( final ClientRequestContext requestContext , final ClientResponseContext responseContext ) { final List < String > serializedHeaders = responseContext . getHeaders ( ) . get ( TraceeConstants . TPIC_HEADER ) ; if ( serializedHeaders != null && backend . getConfiguration ( ) . shouldProcessContext ( ...
This method handles the incoming response