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 ...
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 , GraphDe...
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 IllegalArgumentExceptio...
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_ALR...
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 . get...
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 ) . getAsJs...
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 . encodeSam...
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...
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 ...
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 ) { Bloc...
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 (...
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.change...
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 SelectorUtil...
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 n...
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 ...
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 nu...
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 ...
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 . forQue...
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 ...
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 (...
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 . getC...
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 ...
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 ( ) ) ; la...
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 Tr...
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 Opti...
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 ( ) ) ; } setCo...
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 . loadExtension...
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 . TO...
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 ( expira...
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 ...
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 ( IOExc...
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 > ...
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 ( ) ...
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 . setR...
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 . H...
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 ( remoteU...
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 matc...
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 ( ...
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...
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 ) ; ret...
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 ( newthum...
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...
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 ) ; JWT...
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 = ta...
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 . get...
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 Ht...
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 ) ) ; process...
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 ) ; r...
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 { re...
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...
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 ( ) { pu...
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 ( ) , ...
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 ...
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 , ExceptionMe...
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 ...
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 || res...
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 xMessageBo...
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 . g...
Handles receiving Android broadcast messages