idx int64 0 41.2k | question stringlengths 74 4.21k | target stringlengths 5 888 |
|---|---|---|
5,300 | public void forEachNode ( IntProcedure proc , GraphEventType evt ) throws ContradictionException { int type ; if ( evt == GraphEventType . REMOVE_NODE ) { type = GraphDelta . NR ; for ( int i = frozenFirst [ type ] ; i < frozenLast [ type ] ; i ++ ) { if ( delta . getCause ( i , type ) != propagator ) { proc . execute ( delta . get ( i , type ) ) ; } } } else if ( evt == GraphEventType . ADD_NODE ) { type = GraphDelta . NE ; for ( int i = frozenFirst [ type ] ; i < frozenLast [ type ] ; i ++ ) { if ( delta . getCause ( i , type ) != propagator ) { proc . execute ( delta . get ( i , type ) ) ; } } } else { throw new UnsupportedOperationException ( ) ; } } | Applies proc to every vertex which has just been removed or enforced depending on evt . |
5,301 | public void forEachArc ( PairProcedure proc , GraphEventType evt ) throws ContradictionException { if ( evt == GraphEventType . REMOVE_ARC ) { for ( int i = frozenFirst [ 2 ] ; i < frozenLast [ 2 ] ; i ++ ) { if ( delta . getCause ( i , GraphDelta . AR_TAIL ) != propagator ) { proc . execute ( delta . get ( i , GraphDelta . AR_TAIL ) , delta . get ( i , GraphDelta . AR_HEAD ) ) ; } } } else if ( evt == GraphEventType . ADD_ARC ) { for ( int i = frozenFirst [ 3 ] ; i < frozenLast [ 3 ] ; i ++ ) { if ( delta . getCause ( i , GraphDelta . AE_TAIL ) != propagator ) { proc . execute ( delta . get ( i , GraphDelta . AE_TAIL ) , delta . get ( i , GraphDelta . AE_HEAD ) ) ; } } } else { throw new UnsupportedOperationException ( ) ; } } | Applies proc to every arc which has just been removed or enforced depending on evt . |
5,302 | private Set < Integer > getGLBCCNodes ( int cc ) { Set < Integer > ccNodes = new HashSet < > ( ) ; for ( int i = GLBCCFinder . getCCFirstNode ( ) [ cc ] ; i >= 0 ; i = GLBCCFinder . getCCNextNode ( ) [ i ] ) { ccNodes . add ( i ) ; } return ccNodes ; } | Retrieve the nodes of a GLB CC . |
5,303 | private static int quantizeCoefficients ( double [ ] coefficients , int [ ] dest , int order , int precision ) { assert ( precision >= 2 && precision <= 15 ) ; assert ( coefficients . length >= order + 1 ) ; assert ( dest . length >= order + 1 ) ; if ( precision < 2 || precision > 15 ) throw new IllegalArgumentException ( "Error! precision must be between 2 and 15, inclusive." ) ; int shiftApplied = 0 ; int maxValAllowed = ( 1 << ( precision - 2 ) ) - 1 ; int minValAllowed = - 1 * maxValAllowed - 1 ; double maxVal = 0 ; for ( int i = 1 ; i <= order ; i ++ ) { double temp = coefficients [ i ] ; if ( temp < 0 ) temp *= - 1 ; if ( temp > maxVal ) maxVal = temp ; } for ( shiftApplied = 15 ; shiftApplied > 0 ; shiftApplied -- ) { int temp = ( int ) ( maxVal * ( 1 << shiftApplied ) ) ; if ( temp <= maxValAllowed ) break ; } if ( maxVal > maxValAllowed ) { for ( int i = 1 ; i <= order ; i ++ ) { double temp = coefficients [ i ] ; if ( temp < 0 ) temp = temp * - 1 ; if ( temp > maxValAllowed ) { if ( coefficients [ i ] < 0 ) dest [ i ] = minValAllowed ; else dest [ i ] = maxValAllowed ; } else dest [ i ] = ( int ) coefficients [ i ] ; } } else { for ( int i = 1 ; i <= order ; i ++ ) { double temp = coefficients [ i ] * ( 1 << shiftApplied ) ; temp = ( temp > 0 ) ? temp + 0.5 : temp - 0.5 ; dest [ i ] = ( int ) temp ; } } return shiftApplied ; } | Quantize coefficients to integer values of the given precision and calculate the shift needed . |
5,304 | public void unregister ( final Context context , final Callback < Void > callback ) { new AsyncTask < Void , Void , Exception > ( ) { protected Exception doInBackground ( Void ... params ) { try { if ( ( deviceToken == null ) || ( deviceToken . trim ( ) . equals ( "" ) ) ) { throw new IllegalStateException ( DEVICE_ALREADY_UNREGISTERED ) ; } if ( instanceId == null ) { instanceId = firebaseInstanceIdProvider . get ( context ) ; } String token = Tasks . await ( instanceId . getInstanceId ( ) , 30 , TimeUnit . SECONDS ) . getToken ( ) ; FirebaseMessaging firebaseMessaging = firebaseMessagingProvider . get ( context ) ; for ( String catgory : categories ) { firebaseMessaging . unsubscribeFromTopic ( catgory ) ; } firebaseMessaging . unsubscribeFromTopic ( variantId ) ; instanceId . deleteInstanceId ( ) ; HttpProvider provider = httpProviderProvider . get ( deviceRegistryURL , TIMEOUT ) ; setPasswordAuthentication ( variantId , secret , provider ) ; try { provider . delete ( deviceToken ) ; deviceToken = "" ; removeSavedPostData ( context . getApplicationContext ( ) ) ; return null ; } catch ( HttpException ex ) { return ex ; } } catch ( Exception ex ) { return ex ; } } @ SuppressWarnings ( "unchecked" ) protected void onPostExecute ( Exception result ) { if ( result == null ) { callback . onSuccess ( null ) ; } else { callback . onFailure ( result ) ; } } } . execute ( ( Void ) null ) ; } | Unregister device from Unified Push Server . |
5,305 | public void sendMetrics ( final UnifiedPushMetricsMessage metricsMessage , final Callback < UnifiedPushMetricsMessage > callback ) { new AsyncTask < Void , Void , Exception > ( ) { protected Exception doInBackground ( Void ... params ) { try { if ( ( metricsMessage . getMessageId ( ) == null ) || ( metricsMessage . getMessageId ( ) . trim ( ) . equals ( "" ) ) ) { throw new IllegalStateException ( "Message ID cannot be null or blank" ) ; } HttpProvider provider = httpProviderProvider . get ( metricsURL , TIMEOUT ) ; setPasswordAuthentication ( variantId , secret , provider ) ; try { provider . put ( metricsMessage . getMessageId ( ) , "" ) ; return null ; } catch ( HttpException ex ) { return ex ; } } catch ( Exception ex ) { return ex ; } } @ SuppressWarnings ( "unchecked" ) protected void onPostExecute ( Exception result ) { if ( result == null ) { callback . onSuccess ( metricsMessage ) ; } else { callback . onFailure ( result ) ; } } } . execute ( ( Void ) null ) ; } | Send a confirmation the message was opened |
5,306 | private void removeSavedPostData ( Context appContext ) { preferenceProvider . get ( appContext ) . edit ( ) . remove ( String . format ( REGISTRAR_PREFERENCE_TEMPLATE , senderId ) ) . commit ( ) ; } | We are no longer registered . We do not need to respond to changes in registration token . |
5,307 | private String getOldToken ( Context appContext ) { String jsonData = preferenceProvider . get ( appContext ) . getString ( String . format ( REGISTRAR_PREFERENCE_TEMPLATE , senderId ) , "" ) ; if ( jsonData . isEmpty ( ) ) { return "" ; } JsonObject jsonedPreferences = new JsonParser ( ) . parse ( jsonData ) . getAsJsonObject ( ) ; try { return jsonedPreferences . get ( "deviceToken" ) . getAsString ( ) ; } catch ( Exception ignore ) { Log . w ( TAG , ignore . getMessage ( ) , ignore ) ; return "" ; } } | Returns the most recently used deviceToken |
5,308 | public static int beginResidual ( boolean useFiveBitParam , byte order , EncodedElement ele ) { ele = ele . getEnd ( ) ; int paramSize = ( useFiveBitParam ) ? 1 : 0 ; ele . addInt ( paramSize , 2 ) ; ele . addInt ( order , 4 ) ; return 6 ; } | Create the residual headers for a FLAC stream . |
5,309 | public void run ( ) { boolean process = true ; synchronized ( this ) { BlockEncodeRequest ber = manager . getWaitingRequest ( ) ; if ( ber != null && ber . frameNumber < 0 ) ber = null ; while ( ber != null && process ) { if ( ber . frameNumber < 0 ) { process = false ; } else { ber . encodedSamples = frame . encodeSamples ( ber . samples , ber . count , ber . start , ber . skip , ber . result , ber . frameNumber ) ; ber . valid = true ; manager . returnFinishedRequest ( ber ) ; ber = manager . getWaitingRequest ( ) ; } } manager . notifyFrameThreadExit ( this ) ; } } | Run method . This FrameThread will get a BlockEncodeRequest from the BlockThreadManager encode the block return it to the manager then repeat . If no BlockEncodeRequest is available or if it recieves a request with the frameNumber field set to a negative value it will break the loop and end notifying the manager it has ended . |
5,310 | public void write ( byte data ) throws IOException { fos . write ( data ) ; if ( position + 1 > size ) size = position + 1 ; position += 1 ; } | Write a byte to this stream . |
5,311 | public void addSamples ( int [ ] samples , int count ) { assert ( count * streamConfig . getChannelCount ( ) <= samples . length ) ; if ( samples . length < count * streamConfig . getChannelCount ( ) ) throw new IllegalArgumentException ( "count given exceeds samples array bounds" ) ; sampleLock . lock ( ) ; try { int channels = streamConfig . getChannelCount ( ) ; int maxBlock = streamConfig . getMaxBlockSize ( ) ; if ( unfilledRequest == null ) unfilledRequest = prepareRequest ( maxBlock , channels ) ; int remaining = count ; int offset = 0 ; while ( remaining > 0 ) { int newRemaining = unfilledRequest . addInterleavedSamples ( samples , offset , remaining , maxBlock ) ; offset += ( remaining - newRemaining ) * channels ; remaining = newRemaining ; if ( unfilledRequest . isFull ( maxBlock ) ) { this . preparedRequests . add ( unfilledRequest ) ; unfilledRequest = null ; } if ( remaining > 0 ) { unfilledRequest = prepareRequest ( maxBlock , channels ) ; } } } finally { sampleLock . unlock ( ) ; } } | Add samples to the encoder so they may then be encoded . This method uses breaks the samples into blocks which will then be made available to encode . |
5,312 | private void checkForThreadErrors ( ) throws IOException { if ( error == true && childException != null ) { error = false ; IOException temp = childException ; childException = null ; throw temp ; } } | Attempts to throw a stored exception that had been caught from a child thread . This method should be called regularly in any public method to let the calling thread know a problem occured . |
5,313 | public int encodeSamples ( int count , final boolean end ) throws IOException { int encodedCount = 0 ; streamLock . lock ( ) ; try { checkForThreadErrors ( ) ; int channels = streamConfig . getChannelCount ( ) ; boolean encodeError = false ; while ( count > 0 && preparedRequests . size ( ) > 0 && ! encodeError ) { BlockEncodeRequest ber = preparedRequests . peek ( ) ; int encodedSamples = encodeRequest ( ber , channels ) ; if ( encodedSamples < 0 ) { System . err . println ( "FLACEncoder::encodeSamples : Error in encoding" ) ; encodeError = true ; break ; } preparedRequests . poll ( ) ; encodedCount += encodedSamples ; count -= encodedSamples ; } if ( end ) { if ( threadManager != null ) threadManager . stop ( ) ; if ( count > 0 && unfilledRequest != null && unfilledRequest . count >= count ) { BlockEncodeRequest ber = unfilledRequest ; int encodedSamples = encodeRequest ( ber , channels ) ; if ( encodedSamples < 0 ) { System . err . println ( "FLACEncoder::encodeSamples : (end)Error in encoding" ) ; count = - 1 ; } else { count -= encodedSamples ; encodedCount += encodedSamples ; unfilledRequest = null ; } } if ( count <= 0 ) { closeFLACStream ( ) ; } } else if ( end == true ) { if ( DEBUG_LEV > 30 ) System . err . println ( "End set but not done. Error possible. " + "This can also happen if number of samples requested to " + "encode exeeds available samples" ) ; } } finally { streamLock . unlock ( ) ; } return encodedCount ; } | Attempt to Encode a certain number of samples . Encodes as close to count as possible . |
5,314 | public void setOutputStream ( FLACOutputStream fos ) { if ( fos == null ) throw new IllegalArgumentException ( "FLACOutputStream fos must not be null." ) ; if ( flacWriter == null ) flacWriter = new FLACStreamController ( fos , streamConfig ) ; else flacWriter . setFLACOutputStream ( fos ) ; } | Set the output stream to use . This must not be called while an encode process is active or a flac stream is already opened . |
5,315 | public Status encode ( File inputFile , File outputFile ) { Status status = Status . FULL_ENCODE ; this . outFile = outputFile ; AudioInputStream sin = null ; AudioFormat format = null ; try { sin = AudioSystem . getAudioInputStream ( inputFile ) ; } catch ( IOException e ) { status = Status . FILE_IO_ERROR ; } catch ( UnsupportedAudioFileException e ) { status = Status . UNSUPPORTED_FILE ; } finally { if ( status != Status . FULL_ENCODE ) { try { sin . close ( ) ; } catch ( IOException e ) { } return status ; } } try { format = sin . getFormat ( ) ; adjustConfigurations ( format ) ; openStream ( ) ; AudioStreamEncoder . encodeAudioInputStream ( sin , MAX_READ , flac , useThreads ) ; } catch ( IOException e ) { status = Status . FILE_IO_ERROR ; } catch ( IllegalArgumentException e ) { status = Status . GENERAL_ERROR ; String message = e . getMessage ( ) ; if ( message . equals ( Status . UNSUPPORTED_SAMPLE_SIZE . name ( ) ) ) status = Status . UNSUPPORTED_SAMPLE_SIZE ; else throw e ; } finally { try { sin . close ( ) ; } catch ( IOException e ) { } } return status ; } | Encode the given input wav file to an output file . |
5,316 | private Difference createNullObject ( ) { Difference difference = new Difference ( ) ; difference . setClassName ( "" ) ; difference . setMethod ( "" ) ; difference . setField ( "" ) ; difference . setFrom ( "" ) ; difference . setTo ( "" ) ; difference . setJustification ( bundle . getString ( "report.clirr.api.changes.unjustified" ) ) ; return difference ; } | Use a null object to avoid doing null checks everywhere . |
5,317 | private boolean matches4000 ( ApiDifference apiDiff ) { throwIfMissing ( false , false , false , true ) ; String newIface = getArgs ( apiDiff ) [ 0 ] ; newIface = newIface . replace ( '.' , '/' ) ; return SelectorUtils . matchPath ( to , newIface , "/" , true ) ; } | Added interface to the set of implemented interfaces |
5,318 | private boolean matches4001 ( ApiDifference apiDiff ) { throwIfMissing ( false , false , false , true ) ; String removedIface = getArgs ( apiDiff ) [ 0 ] ; removedIface = removedIface . replace ( '.' , '/' ) ; return SelectorUtils . matchPath ( to , removedIface , "/" , true ) ; } | Removed interface from the set of implemented interfaces |
5,319 | private boolean matches5000 ( ApiDifference apiDiff ) { throwIfMissing ( false , false , false , true ) ; String newSuperclass = getArgs ( apiDiff ) [ 0 ] ; newSuperclass = newSuperclass . replace ( '.' , '/' ) ; return SelectorUtils . matchPath ( to , newSuperclass , "/" , true ) ; } | Added class to the set of superclasses |
5,320 | private boolean matches5001 ( ApiDifference apiDiff ) { throwIfMissing ( false , false , false , true ) ; String removedSuperclass = getArgs ( apiDiff ) [ 0 ] ; removedSuperclass = removedSuperclass . replace ( '.' , '/' ) ; return SelectorUtils . matchPath ( to , removedSuperclass , "/" , true ) ; } | Removed class from the set of superclasses |
5,321 | private boolean matches6004 ( ApiDifference apiDiff ) { throwIfMissing ( true , false , true , true ) ; if ( ! SelectorUtils . matchPath ( field , apiDiff . getAffectedField ( ) ) ) { return false ; } String [ ] args = getArgs ( apiDiff ) ; String diffFrom = args [ 0 ] ; String diffTo = args [ 1 ] ; return SelectorUtils . matchPath ( from , diffFrom ) && SelectorUtils . matchPath ( to , diffTo ) ; } | field type changed |
5,322 | private boolean matches7000 ( ApiDifference apiDiff ) { throwIfMissing ( false , true , false , false ) ; return SelectorUtils . matchPath ( method , removeVisibilityFromMethodSignature ( apiDiff ) ) ; } | method now in superclass |
5,323 | private boolean matches7005 ( List < ApiDifference > apiDiffs ) { throwIfMissing ( false , true , false , true ) ; ApiDifference firstDiff = apiDiffs . get ( 0 ) ; String methodSig = removeVisibilityFromMethodSignature ( firstDiff ) ; if ( ! SelectorUtils . matchPath ( method , methodSig ) ) { return false ; } String newMethodSig = getNewMethodSignature ( methodSig , apiDiffs ) ; return SelectorUtils . matchPath ( to , newMethodSig ) ; } | Method Argument Type changed |
5,324 | private boolean matches7006 ( ApiDifference apiDiff ) { throwIfMissing ( false , true , false , true ) ; String methodSig = removeVisibilityFromMethodSignature ( apiDiff ) ; if ( ! SelectorUtils . matchPath ( method , methodSig ) ) { return false ; } String newRetType = getArgs ( apiDiff ) [ 0 ] ; return SelectorUtils . matchPath ( to , newRetType ) ; } | Method Return Type changed |
5,325 | private boolean matches10000 ( ApiDifference apiDiff ) { throwIfMissing ( false , false , true , true ) ; int fromVersion = 0 ; int toVersion = 0 ; try { fromVersion = Integer . parseInt ( from ) ; } catch ( NumberFormatException e ) { throw new IllegalArgumentException ( "Failed to parse the \"from\" parameter as a number for " + this ) ; } try { toVersion = Integer . parseInt ( to ) ; } catch ( NumberFormatException e ) { throw new IllegalArgumentException ( "Failed to parse the \"to\" parameter as a number for " + this ) ; } String [ ] args = getArgs ( apiDiff ) ; int reportedOld = Integer . parseInt ( args [ 0 ] ) ; int reportedNew = Integer . parseInt ( args [ 1 ] ) ; return fromVersion == reportedOld && toVersion == reportedNew ; } | Class format version increased |
5,326 | public List < Address > getFromLocation ( final double latitude , final double longitude , final int maxResults , final boolean parseAddressComponents ) throws GeocoderException { if ( latitude < - 90.0 || latitude > 90.0 ) { throw new IllegalArgumentException ( "latitude == " + latitude ) ; } if ( longitude < - 180.0 || longitude > 180.0 ) { throw new IllegalArgumentException ( "longitude == " + longitude ) ; } if ( isLimitExceeded ( ) ) { throw GeocoderException . forQueryOverLimit ( ) ; } final Uri . Builder uriBuilder = buildBaseRequestUri ( ) . appendQueryParameter ( "sensor" , "true" ) . appendQueryParameter ( "latlng" , latitude + "," + longitude ) ; final byte [ ] data ; try { data = download ( uriBuilder . toString ( ) ) ; } catch ( IOException e ) { throw new GeocoderException ( e ) ; } return Parser . parseJson ( data , maxResults , parseAddressComponents ) ; } | Returns an array of Addresses that are known to describe the area immediately surrounding the given latitude and longitude . The returned addresses will be localized for the locale provided to this class s constructor . |
5,327 | public List < Address > getFromLocationName ( final String locationName , final int maxResults , final boolean parseAddressComponents ) throws GeocoderException { if ( locationName == null ) { throw new IllegalArgumentException ( "locationName == null" ) ; } if ( isLimitExceeded ( ) ) { throw GeocoderException . forQueryOverLimit ( ) ; } final Uri . Builder uriBuilder = buildBaseRequestUri ( ) . appendQueryParameter ( "sensor" , "false" ) . appendQueryParameter ( "address" , locationName ) ; final String url = uriBuilder . toString ( ) ; byte [ ] data ; try { data = download ( url ) ; } catch ( IOException e ) { throw new GeocoderException ( e ) ; } try { return Parser . parseJson ( data , maxResults , parseAddressComponents ) ; } catch ( GeocoderException e ) { if ( e . getStatus ( ) == Status . OVER_QUERY_LIMIT ) { try { Thread . sleep ( 2000 ) ; } catch ( InterruptedException e1 ) { return new ArrayList < > ( ) ; } try { data = download ( url ) ; } catch ( IOException ioe ) { throw new GeocoderException ( ioe ) ; } try { return Parser . parseJson ( data , maxResults , parseAddressComponents ) ; } catch ( GeocoderException e1 ) { if ( e1 . getStatus ( ) == Status . OVER_QUERY_LIMIT ) { setAllowedDate ( System . currentTimeMillis ( ) + 86400000L ) ; } throw e1 ; } } else { throw e ; } } } | Returns an array of Addresses that are known to describe the named location which may be a place name such as Dalvik Iceland an address such as 1600 Amphitheatre Parkway Mountain View CA an airport code such as SFO etc .. The returned addresses will be localized for the locale provided to this class s constructor . |
5,328 | private static byte [ ] download ( String url ) throws IOException { InputStream is = null ; ByteArrayOutputStream os = null ; try { final URL u = new URL ( url ) ; final URLConnection connection = u . openConnection ( ) ; connection . connect ( ) ; is = connection . getInputStream ( ) ; os = new ByteArrayOutputStream ( ) ; final byte [ ] buffer = new byte [ 4096 ] ; int read ; while ( true ) { read = is . read ( buffer , 0 , buffer . length ) ; if ( read == - 1 ) { break ; } os . write ( buffer , 0 , read ) ; } return os . toByteArray ( ) ; } finally { if ( is != null ) { try { is . close ( ) ; } catch ( IOException ignored ) { } } if ( os != null ) { try { os . close ( ) ; } catch ( IOException ignored ) { } } } } | Downloads data to buffer |
5,329 | private void setAllowedDate ( final long date ) { mAllowedDate = date ; if ( mSharedPreferences == null ) { mSharedPreferences = mContext . getSharedPreferences ( PREFERENCES_GEOCODER , Context . MODE_PRIVATE ) ; } final Editor e = mSharedPreferences . edit ( ) ; e . putLong ( KEY_ALLOW , date ) ; e . apply ( ) ; } | Sets date after which next geocoding query is allowed |
5,330 | private long getAllowedDate ( ) { if ( mSharedPreferences == null ) { mSharedPreferences = mContext . getSharedPreferences ( PREFERENCES_GEOCODER , Context . MODE_PRIVATE ) ; mAllowedDate = mSharedPreferences . getLong ( KEY_ALLOW , 0 ) ; } return mAllowedDate ; } | Returns date after which the next geocoding query is allowed |
5,331 | public static BufferedReader resource ( String resourcePath ) throws IOException { InputStream is = IOUtils . class . getClassLoader ( ) . getResourceAsStream ( resourcePath ) ; if ( is != null ) { return new BufferedReader ( new InputStreamReader ( is , UTF_8 ) ) ; } else { File file = new File ( resourcePath ) ; if ( file . exists ( ) ) { return fileReader ( file ) ; } else { throw new IllegalArgumentException ( "resource does not exist " + resourcePath ) ; } } } | Read a resource from the classpath or fallback to treating it as a file . |
5,332 | public long byteCount ( Object object ) { try { CountingOutputStream cos = new CountingOutputStream ( new OutputStream ( ) { public void write ( int b ) throws IOException { } } ) ; ObjectOutputStream os = new ObjectOutputStream ( cos ) ; os . writeObject ( object ) ; os . flush ( ) ; os . close ( ) ; return cos . getCount ( ) ; } catch ( IOException e ) { throw new IllegalStateException ( "error serializing object: " + e . getMessage ( ) , e ) ; } } | Calculate the serialized object size in bytes . This is a good indication of how much memory the object roughly takes . Note that this is typically not exactly the same for many objects . |
5,333 | public static String [ ] getStringArrayProperty ( Configuration config , String key ) throws DeployerConfigurationException { try { return config . getStringArray ( key ) ; } catch ( Exception e ) { throw new DeployerConfigurationException ( "Failed to retrieve property '" + key + "'" , e ) ; } } | Returns the specified String array property from the configuration . A String array property is normally specified as a String with values separated by commas in the configuration . |
5,334 | @ SuppressWarnings ( "unchecked" ) public static List < HierarchicalConfiguration > getConfigurationsAt ( HierarchicalConfiguration config , String key ) throws DeployerConfigurationException { try { return config . configurationsAt ( key ) ; } catch ( Exception e ) { throw new DeployerConfigurationException ( "Failed to retrieve sub-configurations at '" + key + "'" , e ) ; } } | Returns the sub - configuration tree whose root is the specified key . |
5,335 | public void highlight ( ) { final JTabbedPane parent = ( JTabbedPane ) this . getUiComponent ( ) . getParent ( ) ; for ( int i = 0 ; i < parent . getTabCount ( ) ; i ++ ) { String title = parent . getTitleAt ( i ) ; if ( getTabCaption ( ) . equals ( title ) ) { final JLabel label = new JLabel ( getTabCaption ( ) ) ; label . setForeground ( new Color ( 0xff6633 ) ) ; parent . setTabComponentAt ( i , label ) ; Timer timer = new Timer ( ) ; TimerTask task = new TimerTask ( ) { public void run ( ) { label . setForeground ( Color . black ) ; } } ; timer . schedule ( task , 3000 ) ; break ; } } } | Highlights the tab using Burp s color scheme . The highlight disappears after 3 seconds . |
5,336 | public final String setHeader ( String name , String value ) { sortedHeaders = null ; return headers . put ( name , value ) ; } | Sets a header field value based on its name . |
5,337 | public static SimpleStringTrie from ( Map < String , ? > map ) { SimpleStringTrie st = new SimpleStringTrie ( ) ; map . keySet ( ) . forEach ( key -> st . add ( key ) ) ; return st ; } | Useful if you want to build a trie for an existing map so you can figure out a matching prefix that has an entry |
5,338 | public void add ( String input ) { TrieNode currentNode = root ; for ( char c : input . toCharArray ( ) ) { Map < Character , TrieNode > children = currentNode . getChildren ( ) ; TrieNode matchingNode = children . get ( c ) ; if ( matchingNode != null ) { currentNode = matchingNode ; } else { TrieNode newNode = new TrieNode ( ) ; children . put ( c , newNode ) ; currentNode = newNode ; } } currentNode . end = true ; } | Add a string to the trie . |
5,339 | public Optional < String > get ( String input ) { TrieNode currentNode = root ; int i = 0 ; for ( char c : input . toCharArray ( ) ) { TrieNode nextNode = currentNode . getChildren ( ) . get ( c ) ; if ( nextNode != null ) { i ++ ; currentNode = nextNode ; } else { if ( i > 0 && currentNode . isLeaf ( ) ) { return Optional . of ( input . substring ( 0 , i ) ) ; } } } if ( i > 0 && currentNode . isLeaf ( ) ) { return Optional . of ( input . substring ( 0 , i ) ) ; } return Optional . empty ( ) ; } | Return the longest matching prefix of the input string that was added to the trie . |
5,340 | public void copyFrom ( final CopyFrom obj ) { final FeedInformationImpl info = ( FeedInformationImpl ) obj ; setAuthor ( info . getAuthor ( ) ) ; setBlock ( info . getBlock ( ) ) ; getCategories ( ) . clear ( ) ; if ( info . getCategories ( ) != null ) { getCategories ( ) . addAll ( info . getCategories ( ) ) ; } setComplete ( info . getComplete ( ) ) ; setNewFeedUrl ( info . getNewFeedUrl ( ) ) ; setExplicit ( info . getExplicit ( ) ) ; try { if ( info . getImage ( ) != null ) { setImage ( new URL ( info . getImage ( ) . toExternalForm ( ) ) ) ; } } catch ( final MalformedURLException e ) { LOG . debug ( "Error copying URL:" + info . getImage ( ) , e ) ; } if ( info . getKeywords ( ) != null ) { setKeywords ( info . getKeywords ( ) . clone ( ) ) ; } setOwnerEmailAddress ( info . getOwnerEmailAddress ( ) ) ; setOwnerName ( info . getOwnerName ( ) ) ; setSubtitle ( info . getSubtitle ( ) ) ; setSummary ( info . getSummary ( ) ) ; } | Required by the ROME API |
5,341 | public static < I , O > BoolExprPattern < I , O > matches ( Function < I , Boolean > expr , Function < I , O > f ) { return new BoolExprPattern < I , O > ( expr , f ) ; } | Allows you use a lambda to match on an input . |
5,342 | public static < I , O > Optional < O > evaluate ( I input , Pattern < I , O > ... patterns ) { return new PatternEvaluator < > ( patterns ) . evaluate ( input ) ; } | Creates an evaluator and then evaluates the value right away . |
5,343 | public void setToolDefault ( int tool , boolean enabled ) { switch ( tool ) { case IBurpExtenderCallbacks . TOOL_PROXY : if ( mCallbacks . loadExtensionSetting ( SETTING_PROXY ) == null ) { jCheckBoxProxy . setSelected ( enabled ) ; } break ; case IBurpExtenderCallbacks . TOOL_REPEATER : if ( mCallbacks . loadExtensionSetting ( SETTING_REPEATER ) == null ) { jCheckBoxRepeater . setSelected ( enabled ) ; } break ; case IBurpExtenderCallbacks . TOOL_SCANNER : if ( mCallbacks . loadExtensionSetting ( SETTING_SCANNER ) == null ) { jCheckBoxScanner . setSelected ( enabled ) ; } break ; case IBurpExtenderCallbacks . TOOL_INTRUDER : if ( mCallbacks . loadExtensionSetting ( SETTING_INTRUDER ) == null ) { jCheckBoxIntruder . setSelected ( enabled ) ; } break ; case IBurpExtenderCallbacks . TOOL_SEQUENCER : if ( mCallbacks . loadExtensionSetting ( SETTING_SEQUENCER ) == null ) { jCheckBoxProxy . setSelected ( enabled ) ; } break ; case IBurpExtenderCallbacks . TOOL_SPIDER : if ( mCallbacks . loadExtensionSetting ( SETTING_SPIDER ) == null ) { jCheckBoxSpider . setSelected ( enabled ) ; } break ; case IBurpExtenderCallbacks . TOOL_EXTENDER : if ( mCallbacks . loadExtensionSetting ( SETTING_EXTENDER ) == null ) { jCheckBoxExtender . setSelected ( enabled ) ; } break ; default : break ; } } | Allows the developer to set the default value for selected tools not every tool makes sense for every extension |
5,344 | public boolean isToolSelected ( int tool ) { boolean selected = false ; switch ( tool ) { case IBurpExtenderCallbacks . TOOL_PROXY : selected = jCheckBoxProxy . isSelected ( ) ; break ; case IBurpExtenderCallbacks . TOOL_REPEATER : selected = jCheckBoxRepeater . isSelected ( ) ; break ; case IBurpExtenderCallbacks . TOOL_SCANNER : selected = jCheckBoxScanner . isSelected ( ) ; break ; case IBurpExtenderCallbacks . TOOL_INTRUDER : selected = jCheckBoxIntruder . isSelected ( ) ; break ; case IBurpExtenderCallbacks . TOOL_SEQUENCER : selected = jCheckBoxSequencer . isSelected ( ) ; break ; case IBurpExtenderCallbacks . TOOL_SPIDER : selected = jCheckBoxSpider . isSelected ( ) ; break ; case IBurpExtenderCallbacks . TOOL_EXTENDER : selected = jCheckBoxExtender . isSelected ( ) ; break ; case IBurpExtenderCallbacks . TOOL_TARGET : break ; default : break ; } return selected ; } | Returns true if the requested tool is selected in the GUI |
5,345 | public String create ( Consumer < JWTCreator . Builder > jwtBuilderConsumer ) { Date issueTime = new Date ( ) ; Date expirationTime = new Date ( issueTime . getTime ( ) + defaultExpirationMs ) ; JWTCreator . Builder builder = JWT . create ( ) . withIssuer ( issuer ) . withIssuedAt ( issueTime ) . withExpiresAt ( expirationTime ) ; jwtBuilderConsumer . accept ( builder ) ; return sign ( builder ) ; } | Creates a JWT token . |
5,346 | public String sign ( JWTCreator . Builder builder ) { return builder . sign ( Algorithm . ECDSA512 ( ecPublicKey , ecPrivateKey ) ) ; } | Sign the jwt builder . Use this if you want to control issueing time expiration time and issuer . |
5,347 | public void setAvatar ( final Link newavatar ) { final Link old = getAvatar ( ) ; if ( old != null ) { getOtherLinks ( ) . remove ( old ) ; } newavatar . setRel ( "avatar" ) ; getOtherLinks ( ) . add ( newavatar ) ; } | Set the value of avatar |
5,348 | public static long safeAbs ( long number ) { if ( Long . MIN_VALUE == number ) { return Long . MAX_VALUE ; } else { return java . lang . Math . abs ( number ) ; } } | Java Math . abs has an issue with Long and Integer MIN_VALUE where it returns MIN_VALUE . |
5,349 | public static long pow ( long l , int exp ) { BigInteger bi = BigInteger . valueOf ( l ) . pow ( exp ) ; if ( bi . compareTo ( BigInteger . valueOf ( Long . MAX_VALUE ) ) > 0 || bi . compareTo ( BigInteger . valueOf ( Long . MIN_VALUE ) ) < 0 ) { throw new IllegalArgumentException ( "pow(" + l + "," + exp + ") exceeds Long.MAX_VALUE" ) ; } return bi . longValue ( ) ; } | Java . lang . pow only works on doubles ; this fixes that . Safe version of pow that relies on BigInteger that can raise a long to an int exponential . Uses BigInteger internally to ensure this is done correctly and does a check on the value to ensure it can safely be converted into a long |
5,350 | @ Scheduled ( cron = "${deployer.main.targets.cleanup.cron}" ) public void cleanupAllTargets ( ) { try { logger . info ( "Starting cleanup for all targets" ) ; targetService . getAllTargets ( ) . forEach ( Target :: cleanup ) ; } catch ( TargetServiceException e ) { logger . error ( "Error getting loaded targets" , e ) ; } } | Performs a cleanup on all loaded targets . |
5,351 | public static String urlEncode ( String s ) { try { return URLEncoder . encode ( s , StandardCharsets . UTF_8 . name ( ) ) ; } catch ( UnsupportedEncodingException e ) { throw new IllegalStateException ( "get a jdk that actually supports utf-8" , e ) ; } } | Url encode a string and don t throw a checked exception . Uses UTF - 8 as per RFC 3986 . |
5,352 | public static String urlDecode ( String s ) { try { return URLDecoder . decode ( s , StandardCharsets . UTF_8 . name ( ) ) ; } catch ( UnsupportedEncodingException e ) { throw new IllegalStateException ( "get a jdk that actually supports utf-8" , e ) ; } } | Url decode a string and don t throw a checked exception . Uses UTF - 8 as per RFC 3986 . |
5,353 | @ RequestMapping ( value = MEMORY_URL , method = RequestMethod . GET ) public ResponseEntity < List < MemoryMonitor > > memoryStats ( ) { return new ResponseEntity < > ( MemoryMonitor . getMemoryStats ( ) , HttpStatus . OK ) ; } | Uses Crafter Commons Memory Monitor POJO to get current JVM Memory stats . |
5,354 | @ RequestMapping ( value = STATUS_URL , method = RequestMethod . GET ) public ResponseEntity < StatusMonitor > status ( ) { return new ResponseEntity < > ( StatusMonitor . getCurrentStatus ( ) , HttpStatus . OK ) ; } | Uses Crafter Commons Status Monitor POJO to get current System status . |
5,355 | @ RequestMapping ( value = VERSION_URL , method = RequestMethod . GET ) public ResponseEntity < VersionMonitor > version ( ) throws IOException { try { final VersionMonitor monitor = VersionMonitor . getVersion ( MonitorController . class ) ; return new ResponseEntity < > ( monitor , HttpStatus . OK ) ; } catch ( IOException ex ) { LOGGER . error ( "Unable to read manifest file" , ex ) ; throw new IOException ( "Unable to read manifest file" , ex ) ; } } | Uses Crafter Commons Status Version POJO to get current Deployment and JVM runtime and version information . |
5,356 | public static String getSelection ( byte [ ] message , int [ ] offsets ) { if ( offsets == null || message == null ) return "" ; if ( offsets . length < 2 || offsets [ 0 ] == offsets [ 1 ] ) return "" ; byte [ ] selection = Arrays . copyOfRange ( message , offsets [ 0 ] , offsets [ 1 ] ) ; return new String ( selection ) ; } | Returns the user - selected text in the passed array . |
5,357 | public static String noNulls ( String test , String output , String defaultOutput ) { if ( isEmpty ( test ) ) { return defaultOutput ; } return output ; } | Outputs the String output if the test String is not empty otherwise outputs default |
5,358 | public static List < String > getFileAsLines ( String sFileName ) throws Exception { FileInputStream fIn = null ; BufferedReader fileReader = null ; try { fIn = new FileInputStream ( sFileName ) ; fileReader = new BufferedReader ( new InputStreamReader ( fIn ) ) ; ArrayList < String > output = new ArrayList < String > ( ) ; String line = null ; while ( ( line = fileReader . readLine ( ) ) != null ) { output . add ( line ) ; } return output ; } catch ( Exception e ) { throw e ; } finally { fIn . close ( ) ; fileReader . close ( ) ; } } | Returns the contents of an ASCII file as a List of Strings . |
5,359 | public boolean isEmpty ( ) { return CollectionUtils . isEmpty ( createdFiles ) && CollectionUtils . isEmpty ( updatedFiles ) && CollectionUtils . isEmpty ( deletedFiles ) ; } | Returns true if there are not created updated or deleted files . |
5,360 | public static Git cloneRemoteRepository ( String remoteName , String remoteUrl , String branch , GitAuthenticationConfigurator authConfigurator , File localFolder , String bigFileThreshold , Integer compression , Boolean fileMode ) throws GitAPIException , IOException { CloneCommand command = Git . cloneRepository ( ) ; command . setRemote ( remoteName ) ; command . setURI ( remoteUrl ) ; command . setDirectory ( localFolder ) ; if ( StringUtils . isNotEmpty ( branch ) ) { command . setCloneAllBranches ( false ) ; command . setBranchesToClone ( Collections . singletonList ( Constants . R_HEADS + branch ) ) ; command . setBranch ( branch ) ; } if ( authConfigurator != null ) { authConfigurator . configureAuthentication ( command ) ; } Git git = command . call ( ) ; StoredConfig config = git . getRepository ( ) . getConfig ( ) ; if ( StringUtils . isEmpty ( bigFileThreshold ) ) { bigFileThreshold = BIG_FILE_THRESHOLD_DEFAULT ; } if ( compression == null ) { compression = COMPRESSION_DEFAULT ; } if ( fileMode == null ) { fileMode = FILE_MODE_DEFAULT ; } config . setString ( CORE_CONFIG_SECTION , null , BIG_FILE_THRESHOLD_CONFIG_PARAM , bigFileThreshold ) ; config . setInt ( CORE_CONFIG_SECTION , null , COMPRESSION_CONFIG_PARAM , compression ) ; config . setBoolean ( CORE_CONFIG_SECTION , null , FILE_MODE_CONFIG_PARAM , fileMode ) ; config . save ( ) ; return git ; } | Clones a remote repository into a specific local folder . |
5,361 | public static PullResult pull ( Git git , String remoteName , String remoteUrl , String branch , MergeStrategy mergeStrategy , GitAuthenticationConfigurator authConfigurator ) throws GitAPIException , URISyntaxException { addRemote ( git , remoteName , remoteUrl ) ; PullCommand command = git . pull ( ) ; command . setRemote ( remoteName ) ; command . setRemoteBranchName ( branch ) ; if ( mergeStrategy != null ) { command . setStrategy ( mergeStrategy ) ; } if ( authConfigurator != null ) { authConfigurator . configureAuthentication ( command ) ; } return command . call ( ) ; } | Execute a Git pull . |
5,362 | public static Iterable < PushResult > push ( Git git , String remote , String branch , GitAuthenticationConfigurator authConfigurator ) throws GitAPIException { PushCommand push = git . push ( ) ; push . setRemote ( remote ) ; if ( StringUtils . isNotEmpty ( branch ) ) { push . setRefSpecs ( new RefSpec ( Constants . HEAD + ":" + Constants . R_HEADS + branch ) ) ; } if ( authConfigurator != null ) { authConfigurator . configureAuthentication ( push ) ; } return push . call ( ) ; } | Executes a git push . |
5,363 | public static void cleanup ( String repoPath ) throws GitAPIException , IOException { openRepository ( new File ( repoPath ) ) . gc ( ) . call ( ) ; } | Executes a git gc . |
5,364 | private static void addRemote ( Git git , String remoteName , String remoteUrl ) throws GitAPIException , URISyntaxException { String currentUrl = git . getRepository ( ) . getConfig ( ) . getString ( "remote" , remoteName , "url" ) ; if ( StringUtils . isNotEmpty ( currentUrl ) ) { if ( ! currentUrl . equals ( remoteUrl ) ) { RemoteSetUrlCommand remoteSetUrl = git . remoteSetUrl ( ) ; remoteSetUrl . setName ( remoteName ) ; remoteSetUrl . setUri ( new URIish ( remoteUrl ) ) ; remoteSetUrl . call ( ) ; } } else { RemoteAddCommand remoteAdd = git . remoteAdd ( ) ; remoteAdd . setName ( remoteName ) ; remoteAdd . setUri ( new URIish ( remoteUrl ) ) ; remoteAdd . call ( ) ; } } | Adds a remote if it doesn t exist . If the remote exists but the URL is different updates the URL |
5,365 | public static < T > Optional < T > evaluate ( Supplier < Optional < T > > ... suppliers ) { for ( Supplier < Optional < T > > s : suppliers ) { Optional < T > maybe = s . get ( ) ; if ( maybe . isPresent ( ) ) { return maybe ; } } return Optional . empty ( ) ; } | Evaluate supplier stategies that produce Optionals until one returns something . This implements the strategy pattern with a simple varargs of suppliers that produce an Optional T . You can use this to use several strategies to calculate a T . |
5,366 | public static String privateKey2String ( PrivateKey key ) { PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec ( key . getEncoded ( ) ) ; return new String ( Base64 . getEncoder ( ) . encode ( spec . getEncoded ( ) ) , StandardCharsets . UTF_8 ) ; } | Put this in a safe place obviously . |
5,367 | public static String publicKey2String ( PublicKey key ) { X509EncodedKeySpec spec = new X509EncodedKeySpec ( key . getEncoded ( ) ) ; return new String ( Base64 . getEncoder ( ) . encode ( spec . getEncoded ( ) ) , StandardCharsets . UTF_8 ) ; } | This is what you can share . |
5,368 | @ JsonProperty ( "duration" ) public Long getDuration ( ) { if ( start != null && end != null ) { return start . until ( end , ChronoUnit . MILLIS ) ; } else { return null ; } } | Returns the duration of the deployment . |
5,369 | public MatchRule getMatchRule ( int index ) { if ( index < rules . size ( ) ) { return rules . get ( index ) ; } return null ; } | Get an existing match rule of the scan . |
5,370 | protected List < IScanIssue > processIssues ( List < ScannerMatch > matches , IHttpRequestResponse baseRequestResponse ) { List < IScanIssue > issues = new ArrayList < > ( ) ; if ( ! matches . isEmpty ( ) ) { Collections . sort ( matches ) ; List < int [ ] > startStop = new ArrayList < > ( 1 ) ; for ( ScannerMatch match : matches ) { callbacks . printOutput ( "Processing match: " + match ) ; callbacks . printOutput ( " start: " + match . getStart ( ) + " end: " + match . getEnd ( ) + " full match: " + match . getFullMatch ( ) + " group: " + match . getMatchGroup ( ) ) ; startStop . add ( new int [ ] { match . getStart ( ) , match . getEnd ( ) } ) ; } issues . add ( getScanIssue ( baseRequestResponse , matches , startStop ) ) ; callbacks . printOutput ( "issues: " + issues . size ( ) ) ; } return issues ; } | Process scanner matches into a list of reportable issues . |
5,371 | private void setCustomTypeface ( Context context , AttributeSet attrs ) { DEFAULT_TYPEFACE = TypefaceType . getDefaultTypeface ( context ) ; if ( isInEditMode ( ) || attrs == null || Build . VERSION . SDK_INT < Build . VERSION_CODES . HONEYCOMB ) { return ; } TypedArray styledAttrs = context . obtainStyledAttributes ( attrs , R . styleable . TypefaceView ) ; Integer fontInt = styledAttrs . getInt ( R . styleable . TypefaceView_tv_typeface , DEFAULT_TYPEFACE ) ; styledAttrs . recycle ( ) ; mCurrentTypeface = TypefaceType . getTypeface ( fontInt ) ; Typeface typeface = getFont ( context , mCurrentTypeface . getAssetFileName ( ) ) ; setTypeface ( typeface ) ; } | Sets the typeface for the view |
5,372 | public static Typeface getFont ( Context context , String fontName ) { synchronized ( cache ) { if ( ! cache . containsKey ( fontName ) ) { try { Typeface t = Typeface . createFromAsset ( context . getAssets ( ) , fontName ) ; cache . put ( fontName , t ) ; } catch ( Exception e ) { return null ; } } return cache . get ( fontName ) ; } } | Avoid reloading assets every time |
5,373 | public static String createHash ( char [ ] password ) throws NoSuchAlgorithmException , InvalidKeySpecException { SecureRandom random = new SecureRandom ( ) ; byte [ ] salt = new byte [ SALT_BYTE_SIZE ] ; random . nextBytes ( salt ) ; byte [ ] hash = pbkdf2 ( password , salt , PBKDF2_ITERATIONS , HASH_BYTE_SIZE ) ; return PBKDF2_ITERATIONS + ":" + toHex ( salt ) + ":" + toHex ( hash ) ; } | Returns a salted PBKDF2 hash of the password . |
5,374 | private static boolean slowEquals ( byte [ ] a , byte [ ] b ) { int diff = a . length ^ b . length ; for ( int i = 0 ; i < a . length && i < b . length ; i ++ ) { diff |= a [ i ] ^ b [ i ] ; } return diff == 0 ; } | Compares two byte arrays in length - constant time . This comparison method is used so that password hashes cannot be extracted from an on - line system using a timing attack and then attacked off - line . |
5,375 | public void setThumbnail ( final Link newthumbnail ) { Link old = null ; for ( final Link l : getOtherLinks ( ) ) { if ( "thumbnail" . equals ( l . getRel ( ) ) ) { old = l ; break ; } } if ( old != null ) { getOtherLinks ( ) . remove ( old ) ; newthumbnail . setRel ( "thumbnail" ) ; } getOtherLinks ( ) . add ( newthumbnail ) ; } | Set the value of thumbnail |
5,376 | public List < ICookie > getCookies ( ) { String cookies = getHeader ( "Cookie" ) ; List < ICookie > output = new ArrayList < > ( ) ; if ( Utils . isEmpty ( cookies ) ) { return output ; } for ( String cookieStr : cookies . split ( "[; ]+" ) ) { String [ ] pair = cookieStr . split ( "=" , 2 ) ; output . add ( new Cookie ( pair [ 0 ] , pair [ 1 ] ) ) ; } return output ; } | Gets the value of the Cookie header |
5,377 | public void setParameter ( String name , String value ) { sortedParams = null ; parameters . add ( new Parameter ( name , value ) ) ; } | Sets a parameter value based on its name . |
5,378 | private void parseParameters ( String input ) { for ( String param : input . split ( "&" ) ) { String [ ] pair = param . split ( "=" ) ; String name = ( pair . length > 0 ) ? pair [ 0 ] : null ; String value = ( pair . length > 1 ) ? pair [ 1 ] : null ; if ( name != null ) { setParameter ( name , value ) ; } } } | Parses a String of HTTP parameters into the internal parameters data structure . No input checking or decoding is performed! |
5,379 | public void verify ( String token , Consumer < Verification > verificationConsumer ) throws JWTVerificationException , IllegalArgumentException { Verification verifierBuilder = JWT . require ( Algorithm . ECDSA512 ( ecPublicKey , null ) ) . withIssuer ( issuer ) ; verificationConsumer . accept ( verifierBuilder ) ; JWTVerifier verifier = verifierBuilder . build ( ) ; verifier . verify ( token ) ; } | Verifies the token . |
5,380 | @ RequestMapping ( value = GET_PENDING_DEPLOYMENTS_URL , method = RequestMethod . GET ) public ResponseEntity < Collection < Deployment > > getPendingDeployments ( @ PathVariable ( ENV_PATH_VAR_NAME ) String env , @ PathVariable ( SITE_NAME_PATH_VAR_NAME ) String siteName ) throws DeployerException { Target target = targetService . getTarget ( env , siteName ) ; Collection < Deployment > deployments = target . getPendingDeployments ( ) ; return new ResponseEntity < > ( deployments , RestServiceUtils . setLocationHeader ( new HttpHeaders ( ) , BASE_URL + GET_PENDING_DEPLOYMENTS_URL , env , siteName ) , HttpStatus . OK ) ; } | Gets the pending deployments for a target . |
5,381 | @ RequestMapping ( value = GET_CURRENT_DEPLOYMENT_URL , method = RequestMethod . GET ) public ResponseEntity < Deployment > getCurrentDeployment ( @ PathVariable ( ENV_PATH_VAR_NAME ) String env , @ PathVariable ( SITE_NAME_PATH_VAR_NAME ) String siteName ) throws DeployerException { Target target = targetService . getTarget ( env , siteName ) ; Deployment deployment = target . getCurrentDeployment ( ) ; return new ResponseEntity < > ( deployment , RestServiceUtils . setLocationHeader ( new HttpHeaders ( ) , BASE_URL + GET_CURRENT_DEPLOYMENT_URL , env , siteName ) , HttpStatus . OK ) ; } | Gets the current deployment for a target . |
5,382 | private boolean loadMatchRules ( String rulesUrl ) { try { if ( rulesUrl != null && rulesUrl . toLowerCase ( ) . startsWith ( "file:" ) ) { return loadMatchRulesFromFile ( rulesUrl ) ; } mCallbacks . printOutput ( "Loading match rules from: " + rulesUrl ) ; URL url = new URL ( rulesUrl ) ; IHttpService service = new HttpService ( url ) ; HttpRequest request = new HttpRequest ( url ) ; byte [ ] responseBytes = mCallbacks . makeHttpRequest ( service . getHost ( ) , service . getPort ( ) , HttpService . PROTOCOL_HTTPS . equalsIgnoreCase ( service . getProtocol ( ) ) , request . getBytes ( ) ) ; if ( responseBytes == null ) return false ; HttpResponse response = HttpResponse . parseMessage ( responseBytes ) ; Reader is = new StringReader ( response . getBody ( ) ) ; BufferedReader reader = new BufferedReader ( is ) ; processMatchRules ( reader ) ; return true ; } catch ( IOException e ) { scan . printStackTrace ( e ) ; } catch ( Exception e ) { scan . printStackTrace ( e ) ; } return false ; } | Load match rules from a URL |
5,383 | private boolean loadMatchRulesFromJar ( String rulesUrl ) { try { mCallbacks . printOutput ( "Loading match rules from local jar: " + rulesUrl ) ; InputStream in = getClass ( ) . getClassLoader ( ) . getResourceAsStream ( rulesUrl ) ; BufferedReader reader = new BufferedReader ( new InputStreamReader ( in ) ) ; processMatchRules ( reader ) ; return true ; } catch ( IOException e ) { scan . printStackTrace ( e ) ; } catch ( NumberFormatException e ) { scan . printStackTrace ( e ) ; } return false ; } | Load match rules from within the jar |
5,384 | private boolean loadMatchRulesFromFile ( String rulesUrl ) { try { mCallbacks . printOutput ( "Loading match rules from file: " + rulesUrl ) ; InputStream in = new URL ( rulesUrl ) . openStream ( ) ; BufferedReader reader = new BufferedReader ( new InputStreamReader ( in , "UTF-8" ) ) ; processMatchRules ( reader ) ; return true ; } catch ( IOException e ) { scan . printStackTrace ( e ) ; } catch ( NumberFormatException e ) { scan . printStackTrace ( e ) ; } return false ; } | Load match rules from a file URL |
5,385 | public static GenderEnumeration findByValue ( final String value ) { if ( value == null ) { return null ; } final String gender = value . toUpperCase ( ) ; if ( gender . charAt ( 0 ) == 'M' ) { return GenderEnumeration . MALE ; } else if ( gender . charAt ( 0 ) == 'F' ) { return GenderEnumeration . FEMALE ; } else { return null ; } } | Returns the proper instance based on the string value |
5,386 | public static String bitString ( long number ) { return String . format ( Locale . ROOT , "%064d" , new BigInteger ( Long . toBinaryString ( number ) ) ) ; } | Get a String representations of the bit in a 64 bit long . |
5,387 | public void login ( String token ) { TokenAuth tokenAuth = new TokenAuth ( token ) ; Object [ ] methodArgs = new Object [ 1 ] ; methodArgs [ 0 ] = tokenAuth ; getDDP ( ) . call ( "login" , methodArgs , new DDPListener ( ) { public void onResult ( Map < String , Object > jsonFields ) { handleLoginResult ( jsonFields ) ; } } ) ; } | Logs in using resume token |
5,388 | public boolean registerUser ( String username , String email , String password ) { if ( ( ( username == null ) && ( email == null ) ) || ( password == null ) ) { return false ; } Object [ ] methodArgs = new Object [ 1 ] ; Map < String , Object > options = new HashMap < > ( ) ; methodArgs [ 0 ] = options ; if ( username != null ) { options . put ( "username" , username ) ; } if ( email != null ) { options . put ( "email" , email ) ; } options . put ( "password" , password ) ; getDDP ( ) . call ( "createUser" , methodArgs , new DDPListener ( ) { public void onResult ( Map < String , Object > jsonFields ) { handleLoginResult ( jsonFields ) ; } } ) ; return true ; } | Register s user into Meteor s accounts - password system |
5,389 | public void forgotPassword ( String email ) { if ( email == null ) { return ; } Object [ ] methodArgs = new Object [ 1 ] ; Map < String , Object > options = new HashMap < > ( ) ; methodArgs [ 0 ] = options ; options . put ( "email" , email ) ; getDDP ( ) . call ( "forgotPassword" , methodArgs , new DDPListener ( ) { public void onResult ( Map < String , Object > jsonFields ) { handleLoginResult ( jsonFields ) ; } } ) ; } | Sends password reset mail to specified email address |
5,390 | public static Type getType ( TypeSystem typeSystem , String name ) throws AnalysisEngineProcessException { Type type = typeSystem . getType ( name ) ; if ( type == null ) { throw new OpenNlpAnnotatorProcessException ( ExceptionMessages . TYPE_NOT_FOUND , new Object [ ] { name } ) ; } return type ; } | Retrieves a type of the given name from the given type system . |
5,391 | private static void checkFeatureType ( Feature feature , String expectedType ) throws AnalysisEngineProcessException { if ( ! feature . getRange ( ) . getName ( ) . equals ( expectedType ) ) { throw new OpenNlpAnnotatorProcessException ( ExceptionMessages . WRONG_FEATURE_TYPE , new Object [ ] { feature . getName ( ) , expectedType } ) ; } } | Checks if the given feature has the expected type otherwise an exception is thrown . |
5,392 | public static Feature getRequiredFeature ( Type type , String featureName , String rangeType ) throws AnalysisEngineProcessException { Feature feature = getRequiredFeature ( type , featureName ) ; checkFeatureType ( feature , rangeType ) ; return feature ; } | Retrieves a required feature from the given type . |
5,393 | public static Boolean getOptionalBooleanParameter ( UimaContext context , String parameter ) throws ResourceInitializationException { Object value = getOptionalParameter ( context , parameter ) ; if ( value instanceof Boolean ) { return ( Boolean ) value ; } else if ( value == null ) { return null ; } else { throw new ResourceInitializationException ( ExceptionMessages . MESSAGE_CATALOG , ExceptionMessages . WRONG_PARAMETER_TYPE , new Object [ ] { parameter , "Boolean" } ) ; } } | Retrieves an optional parameter from the given context . |
5,394 | public static InputStream getResourceAsStream ( UimaContext context , String name ) throws ResourceInitializationException { InputStream inResource = getOptionalResourceAsStream ( context , name ) ; if ( inResource == null ) { throw new ResourceInitializationException ( ExceptionMessages . MESSAGE_CATALOG , ExceptionMessages . IO_ERROR_MODEL_READING , new Object [ ] { name + " could not be found!" } ) ; } return inResource ; } | Retrieves a resource as stream from the given context . |
5,395 | private void process ( Node node , List < String > sentence , List < Span > names ) { if ( node != null ) { for ( TreeElement element : node . getElements ( ) ) { if ( element . isLeaf ( ) ) { processLeaf ( ( Leaf ) element , sentence , names ) ; } else { process ( ( Node ) element , sentence , names ) ; } } } } | Recursive method to process a node in Arvores Deitadas format . |
5,396 | public void process ( CAS tcas ) { String text = tcas . getDocumentText ( ) ; Document document = new DocumentImpl ( text ) ; cogroo . analyze ( document ) ; for ( Sentence sentence : document . getSentences ( ) ) { AnnotationFS sentenceAnn = tcas . createAnnotation ( mSentenceType , sentence . getStart ( ) , sentence . getEnd ( ) ) ; tcas . getIndexRepository ( ) . addFS ( sentenceAnn ) ; int sentenceOffset = sentence . getStart ( ) ; AnnotationFS [ ] tokenAnnotationArr = new AnnotationFS [ sentence . getTokens ( ) . size ( ) ] ; int i = 0 ; for ( Token token : sentence . getTokens ( ) ) { tokenAnnotationArr [ i ] = tcas . createAnnotation ( mTokenType , sentenceOffset + token . getStart ( ) , sentenceOffset + token . getEnd ( ) ) ; tokenAnnotationArr [ i ] . setStringValue ( this . mPosFeature , token . getPOSTag ( ) ) ; tokenAnnotationArr [ i ] . setStringValue ( this . mLexemeFeature , token . getLexeme ( ) ) ; StringArrayFS lemmas = tcas . createStringArrayFS ( token . getLemmas ( ) . length ) ; lemmas . copyFromArray ( token . getLemmas ( ) , 0 , 0 , token . getLemmas ( ) . length ) ; tokenAnnotationArr [ i ] . setFeatureValue ( this . mLemmaFeature , lemmas ) ; tokenAnnotationArr [ i ] . setStringValue ( this . mFeaturesFeature , token . getFeatures ( ) ) ; tcas . getIndexRepository ( ) . addFS ( tokenAnnotationArr [ i ] ) ; i ++ ; } for ( Chunk chunk : sentence . getChunks ( ) ) { int start = sentence . getTokens ( ) . get ( chunk . getStart ( ) ) . getStart ( ) + sentenceOffset ; int end = sentence . getTokens ( ) . get ( chunk . getEnd ( ) - 1 ) . getEnd ( ) + sentenceOffset ; AnnotationFS chunkAnn = tcas . createAnnotation ( mChunkType , start , end ) ; chunkAnn . setStringValue ( mChunkFeature , chunk . getTag ( ) ) ; if ( chunk . getHeadIndex ( ) >= 0 ) { chunkAnn . setFeatureValue ( mChunkHead , tokenAnnotationArr [ chunk . getHeadIndex ( ) ] ) ; } tcas . getIndexRepository ( ) . addFS ( chunkAnn ) ; } for ( SyntacticChunk sc : sentence . getSyntacticChunks ( ) ) { int start = sentence . getTokens ( ) . get ( sc . getStart ( ) ) . getStart ( ) + sentenceOffset ; int end = sentence . getTokens ( ) . get ( sc . getEnd ( ) - 1 ) . getEnd ( ) + sentenceOffset ; AnnotationFS syntChunkAnn = tcas . createAnnotation ( mSyntacticChunkType , start , end ) ; syntChunkAnn . setStringValue ( mSyntacticChunkFeature , sc . getTag ( ) ) ; tcas . getIndexRepository ( ) . addFS ( syntChunkAnn ) ; } } } | Performs chunking on the given tcas object . |
5,397 | public boolean match ( TagMask tagMask , boolean restricted ) { if ( tagMask . getClazz ( ) != null ) { if ( ( this . getClazzE ( ) != null || restricted ) && ! match ( this . getClazzE ( ) , tagMask . getClazz ( ) ) ) return false ; } if ( tagMask . getGender ( ) != null ) { if ( ( this . getGenderE ( ) != null || restricted ) && dontMatch ( tagMask . getGender ( ) ) ) return false ; } if ( tagMask . getNumber ( ) != null ) { if ( ( this . getNumberE ( ) != null || restricted ) && dontMatch ( tagMask . getNumber ( ) ) ) return false ; } if ( tagMask . getCase ( ) != null ) { if ( ( this . getCase ( ) != null || restricted ) && this . getCase ( ) != tagMask . getCase ( ) ) return false ; } if ( tagMask . getPerson ( ) != null ) { if ( ( this . getPersonE ( ) != null || restricted ) && dontMatch ( tagMask . getPerson ( ) ) ) return false ; } if ( tagMask . getTense ( ) != null ) { if ( ( this . getTense ( ) != null || restricted ) && ! match ( this . getTense ( ) , tagMask . getTense ( ) ) ) return false ; } if ( tagMask . getMood ( ) != null ) { if ( ( this . getMood ( ) != null || restricted ) && this . getMood ( ) != tagMask . getMood ( ) ) return false ; } if ( tagMask . getPunctuation ( ) != null ) { if ( ( this . getPunctuation ( ) != null || restricted ) && this . getPunctuation ( ) != tagMask . getPunctuation ( ) ) return false ; } return true ; } | tag doesn t |
5,398 | public short showMessageBox ( XWindowPeer _xParentWindowPeer , String _sTitle , String _sMessage , String _aType , int _aButtons ) { short nResult = - 1 ; XComponent xComponent = null ; try { Object oToolkit = m_xMCF . createInstanceWithContext ( "com.sun.star.awt.Toolkit" , m_xContext ) ; XMessageBoxFactory xMessageBoxFactory = ( XMessageBoxFactory ) UnoRuntime . queryInterface ( XMessageBoxFactory . class , oToolkit ) ; Rectangle aRectangle = new Rectangle ( ) ; XMessageBox xMessageBox = xMessageBoxFactory . createMessageBox ( _xParentWindowPeer , aRectangle , _aType , _aButtons , _sTitle , _sMessage ) ; xComponent = ( XComponent ) UnoRuntime . queryInterface ( XComponent . class , xMessageBox ) ; if ( xMessageBox != null ) { nResult = xMessageBox . execute ( ) ; } } catch ( com . sun . star . uno . Exception ex ) { ex . printStackTrace ( System . out ) ; } finally { if ( xComponent != null ) { xComponent . dispose ( ) ; } } return nResult ; } | Shows an messagebox |
5,399 | public void onReceive ( Context context , Intent intent ) { Bundle bundle = intent . getExtras ( ) ; if ( intent . getAction ( ) . equals ( DDPStateSingleton . MESSAGE_ERROR ) ) { String message = bundle . getString ( DDPStateSingleton . MESSAGE_EXTRA_MSG ) ; onError ( "Login Error" , message ) ; } else if ( intent . getAction ( ) . equals ( DDPStateSingleton . MESSAGE_CONNECTION ) ) { int state = bundle . getInt ( DDPStateSingleton . MESSAGE_EXTRA_STATE ) ; if ( state == DDPStateSingleton . DDPSTATE . Closed . ordinal ( ) ) { onError ( "Disconnected" , "Websocket to server was closed" ) ; } else if ( state == DDPStateSingleton . DDPSTATE . Connected . ordinal ( ) ) { onDDPConnect ( mDDP ) ; } else if ( state == DDPStateSingleton . DDPSTATE . LoggedIn . ordinal ( ) ) { onLogin ( ) ; } else if ( state == DDPStateSingleton . DDPSTATE . NotLoggedIn . ordinal ( ) ) { onLogout ( ) ; } } else if ( intent . getAction ( ) . equals ( DDPStateSingleton . MESSAGE_SUBUPDATED ) ) { String subscriptionName = bundle . getString ( DDPStateSingleton . MESSAGE_EXTRA_SUBNAME ) ; String changeType = bundle . getString ( DDPStateSingleton . MESSAGE_EXTRA_CHANGETYPE ) ; String docId = bundle . getString ( DDPStateSingleton . MESSAGE_EXTRA_CHANGEID ) ; onSubscriptionUpdate ( changeType , subscriptionName , docId ) ; } } | Handles receiving Android broadcast messages |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.