idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
29,000
public String asymmetric ( int leftPos , int rightPos ) { boolean lm = false , rm = false , isSameLAR = isEqual ( this . region . get ( ) [ 0 ] , this . region . get ( ) [ 1 ] ) ; int l = 0 , r = 0 , lr = 0 , lp = 0 , rp = 0 ; for ( Pair < Integer , Integer > kv : indexes . get ( ) ) { if ( isSameLAR ) { ++ lr ; if ( lr == leftPos ) { lp = kv . getR ( ) ; lm = true ; } if ( lr == rightPos ) { rp = kv . getR ( ) ; rm = true ; } } else { switch ( kv . getL ( ) . intValue ( ) ) { case 0 : ++ l ; if ( l == leftPos ) { lp = kv . getR ( ) ; lm = true ; } break ; case 1 : ++ r ; if ( r == rightPos ) { rp = kv . getR ( ) ; rm = true ; } break ; } } if ( lm && rm ) { break ; } } if ( ! ( lm && rm ) ) { return EMPTY ; } return this . doSubstring ( Pair . of ( lp , rp ) ) ; }
Returns the substring in given left position and right position when the left right tag is asymmetric
29,001
public synchronized Filter addKeys ( String ... keys ) { for ( String key : keys ) { this . keys . add ( key ) ; } return this ; }
Adds a list of keys to the filter .
29,002
public synchronized Filter addTags ( String ... tags ) { for ( String tag : tags ) { this . tags . add ( tag ) ; } return this ; }
Adds a list of tags to the filter .
29,003
public synchronized Filter addAttribute ( String key , String value ) { attributes . put ( key , value ) ; return this ; }
Adds an attribute to the filter .
29,004
public synchronized Filter addAttributes ( Map < String , String > attributes ) { for ( Map . Entry < String , String > pair : attributes . entrySet ( ) ) { String key = pair . getKey ( ) ; String value = pair . getValue ( ) ; this . attributes . put ( key , value ) ; } return this ; }
Adds a map of attributes to the filter .
29,005
public void add ( int index , float e ) { if ( index < 0 || index > size ) { throw new IndexOutOfBoundsException ( ) ; } ensureCapacity ( size + 1 ) ; if ( index < size ) { for ( int i = size ; i > index ; i -- ) { elements [ i ] = elements [ i - 1 ] ; } } elements [ index ] = e ; size ++ ; }
Inserts a value into the array at the specified index .
29,006
private void reallocate ( int capacity ) { if ( capacity != elements . length ) { assert ( size <= capacity ) ; float [ ] newArray = new float [ capacity ] ; for ( int i = 0 ; i < size ; i ++ ) { newArray [ i ] = elements [ i ] ; } elements = newArray ; } }
Resizes the underlying array .
29,007
public long count ( ) throws PersistenceException { logger . debug ( "enter - count()" ) ; try { Transaction xaction = Transaction . getInstance ( true ) ; Counter counter = getCounter ( null ) ; try { Map < String , Object > results ; long count ; results = xaction . execute ( counter , new HashMap < String , Object > ( 0 ) , readDataSource ) ; count = ( ( Number ) results . get ( "count" ) ) . longValue ( ) ; xaction . commit ( ) ; return count ; } finally { xaction . rollback ( ) ; } } finally { logger . debug ( "exit - count()" ) ; } }
Counts the total number of objects governed by this factory in the database .
29,008
public BigDecimal toBigDecimal ( int scale , Rounding roundingMode ) { return toBigDecimal ( scale , roundingMode , getProperties ( ) . hasStripTrailingZeros ( ) ) ; }
Return BigDecimal in defined scale with specified rounding mode . Use strip trailing zeros from properties
29,009
public BigDecimal toBigDecimal ( Integer scale , Rounding rounding , boolean stripTrailingZeros ) { out = this . in ; if ( scale != null && rounding != null ) out = out . setScale ( scale , rounding . getBigDecimalRound ( ) ) ; else if ( scale != null && rounding == null ) out = out . setScale ( scale ) ; if ( stripTrailingZeros ) out = out . stripTrailingZeros ( ) ; return out ; }
Return BigDecimal with given parameters .
29,010
public int remainderSize ( ) { BigDecimal fraction = remainder ( ) ; String tmp = fraction . toString ( ) ; int n = tmp . indexOf ( Properties . DEFAULT_DECIMAL_SEPARATOR ) ; if ( n != - 1 ) { return tmp . length ( ) - n - 1 ; } else return 0 ; }
Return count of number in reminder .
29,011
public boolean isEqual ( Object value , boolean autoscale ) { Num numA = this ; Num numB = null ; if ( value instanceof Num ) numB = ( Num ) value ; else numB = new Num ( value ) ; int minScale = numA . remainderSize ( ) ; int bScale = numB . remainderSize ( ) ; if ( bScale < minScale ) minScale = bScale ; return isEqual ( value , minScale ) ; }
Scale both value to scale of number which have minimum scale .
29,012
public Client build ( ) { validate ( ) ; Client client = new Client ( database , credentials , host , scheme ) ; return client ; }
Creates the client object using the specified parameters .
29,013
public static String generateJNISignature ( Class < ? > [ ] params ) { StringBuilder ret = new StringBuilder ( ) ; for ( Class < ? > param : params ) { ret . append ( getJavaSignature ( param ) ) ; } return ret . toString ( ) ; }
Construct a JNI signature string from a series of parameters .
29,014
@ RequestMapping ( value = "/delete" , method = RequestMethod . POST ) public void delete ( @ RequestParam ( value = "username" , required = true ) String username , HttpServletResponse response ) { logger . debug ( "Received request to delete account" ) ; ResponseAccount responseAccount = accountService . getAccountByUsername ( username ) ; if ( responseAccount . getAccount ( ) == null ) { try { response . sendError ( 500 , "No such user exists: " + username ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; return ; } return ; } accountService . delete ( responseAccount . getAccount ( ) ) ; }
Handles request for deleting account
29,015
@ RequestMapping ( value = "/findByUsername" , method = RequestMethod . GET ) public ResponseAccount findByUsername ( @ RequestParam ( value = "username" , required = true ) String username ) { logger . debug ( "Received request to get account by username" ) ; ResponseAccount acconut = accountService . getAccountByUsername ( username ) ; return acconut ; }
Handles request for getting an account by username
29,016
public ArrayList < E > toFlatArrayList ( ) { ArrayList < E > ret = new ArrayList < > ( ) ; this . columns . forEach ( ret :: addAll ) ; return ret ; }
Flattens the matrix column - after - column so that it can be used as a common collection
29,017
public static Object keyValue ( Object entity ) { Class < ? > clazz = entity . getClass ( ) ; Field key = fields . get ( clazz ) ; try { if ( key == null ) { return keyField ( clazz ) . get ( entity ) ; } else { return key . get ( entity ) ; } } catch ( IllegalAccessException e ) { throw new UncheckedException ( e ) ; } }
Returns key value of the specified entity instance .
29,018
public static Field keyField ( Class < ? > clazz ) { for ( Field field : clazz . getDeclaredFields ( ) ) { if ( field . getAnnotation ( Key . class ) != null ) { field . setAccessible ( true ) ; fields . put ( clazz , field ) ; return field ; } } throw new IllegalArgumentException ( "Entity [" + clazz + "] must have one @org.eiichiro.acidhouse.Key field" ) ; }
Returns key field of the specified entity class .
29,019
public static synchronized void setLocale ( String newLocale ) throws UnsupportedLocaleException { Preconditions . checkArgument ( newLocale == null , "newLocale == null" ) ; if ( ! newLocale . equals ( CURRENT_LOCALE ) ) { LogCentral . setLocale ( newLocale ) ; CURRENT_LOCALE = newLocale ; } }
Sets the locale for the complete Logdoc library .
29,020
public static synchronized void setLogFilter ( LogFilter logFilter ) { Preconditions . checkArgument ( logFilter == null , "logFilter == null" ) ; Limb . log ( LogLevel . DEBUG , "Set LogFilter to instance of class " + logFilter . getClass ( ) . getName ( ) + '.' ) ; LOG_FILTER = logFilter ; }
Sets the current log filter .
29,021
private static String convertToHex ( byte [ ] data ) { final StringBuffer buffer = new StringBuffer ( ) ; for ( int i = 0 ; i < data . length ; i ++ ) { int halfByte = ( data [ i ] >>> 4 ) & 0x0F ; int twoHalves = 0 ; do { if ( ( 0 <= halfByte ) && ( halfByte <= 9 ) ) { buffer . append ( ( char ) ( '0' + halfByte ) ) ; } else { buffer . append ( ( char ) ( 'a' + ( halfByte - 10 ) ) ) ; } halfByte = data [ i ] & 0x0F ; } while ( twoHalves ++ < 1 ) ; } return buffer . toString ( ) ; }
Converts an array of bytes to its hexadecimal equivalent
29,022
public static String getSHA1Hash ( final String input ) throws HibiscusException { String hashValue = null ; try { final MessageDigest messageDigest = MessageDigest . getInstance ( MESSAGE_DIGEST_ALGORITHM_SHA1 ) ; byte [ ] sha1Hash = new byte [ BYTE_LENGTH_SHA1 ] ; messageDigest . update ( input . getBytes ( ENCODING_CHARSET_NAME ) , MESSAGE_DIGEST_UPDATE_OFFSET , input . length ( ) ) ; sha1Hash = messageDigest . digest ( ) ; hashValue = convertToHex ( sha1Hash ) ; } catch ( NoSuchAlgorithmException e ) { throw new HibiscusException ( "Unsupported Message Digest Algorithm " + MESSAGE_DIGEST_ALGORITHM_SHA1 , e ) ; } catch ( UnsupportedEncodingException e ) { throw new HibiscusException ( "Unsupported Encoding " + ENCODING_CHARSET_NAME , e ) ; } return hashValue ; }
Returns the SHA1 hash of the input string
29,023
public static String getMD5Hash ( final String input ) throws HibiscusException { String hashValue = null ; try { final MessageDigest messageDigest = MessageDigest . getInstance ( MESSAGE_DIGEST_ALGORITHM_MD5 ) ; byte [ ] md5Hash = new byte [ BYTE_LENGTH_MD5 ] ; messageDigest . update ( input . getBytes ( ENCODING_CHARSET_NAME ) , MESSAGE_DIGEST_UPDATE_OFFSET , input . length ( ) ) ; md5Hash = messageDigest . digest ( ) ; hashValue = convertToHex ( md5Hash ) ; } catch ( NoSuchAlgorithmException e ) { throw new HibiscusException ( "Unsupported Message Digest Algorithm " + MESSAGE_DIGEST_ALGORITHM_MD5 , e ) ; } catch ( UnsupportedEncodingException e ) { throw new HibiscusException ( "Unsupported Encoding " + ENCODING_CHARSET_NAME , e ) ; } return hashValue ; }
Returns the MD5 hash of the input string
29,024
public List < String > createCommandList ( final List < String > filterOptions ) { List < String > list = new ArrayList < String > ( ) ; list . add ( getExecutable ( ) ) ; for ( String opt : filterOptions ) { if ( isOptionSet ( opt ) ) { list . add ( opt ) ; final String value = getOption ( opt ) ; if ( value != NO_OPTION_VALUE ) { list . add ( value ) ; } } } return list ; }
Creates a command line from the current configuration . The command line is represented as a string list . The options are filtered by the specified list .
29,025
public Process execute ( ) throws IOException { List < String > list = createCommandList ( ) ; if ( _LOG_ . isDebugEnabled ( ) ) { _LOG_ . debug ( "executing command: " + list ) ; } Process proc = Runtime . getRuntime ( ) . exec ( list . toArray ( new String [ 0 ] ) ) ; return proc ; }
Executes this command .
29,026
public boolean addFlowElement ( MapElement fe ) { if ( fe instanceof ExceptionHandler ) { exceptionHandler = ( ExceptionHandler ) fe ; return true ; } else if ( fe instanceof InvocationResultExpression ) { if ( results == null ) { results = new ArrayList ( ) ; } results . add ( fe ) ; return true ; } return false ; }
Adds invocation results and exception handlers .
29,027
public static Payload createPayload ( TestRun testRun ) { if ( testRun == null ) { throw new IllegalArgumentException ( "The test run must be present." ) ; } Payload payload = new Payload ( ) ; payload . setTestRun ( testRun ) ; return payload ; }
Create a payload from a test run
29,028
public void registerAddOn ( AddOnModel addOn ) { PluginDescriptor descriptor = addOn . getPlugin ( ) . getDescriptor ( ) ; String name = descriptor . getTitle ( ) ; String version = descriptor . getVersion ( ) . toString ( ) ; String provider = descriptor . getProvider ( ) ; String id = descriptor . getPluginId ( ) ; String sdkVersion = descriptor . getSdkVersion ( ) . toString ( ) ; String artifactID = descriptor . getArtifactID ( ) ; Optional < Integer > serverID = descriptor . getServerID ( ) ; try { AddOnInformation addOnInformation = new AddOnInformationImpl ( name , provider , version , id , sdkVersion , serverID , artifactID ) ; addOnInformations . add ( addOnInformation ) ; addOns . add ( addOn ) ; } catch ( MissingArgumentException e ) { error ( "Unable to register addOn: " + addOn . getID ( ) + " with the AddOnInformationManager" , e ) ; } }
Registers an addOn with the AddOnInformationManager by extracting all relevant information from the addOn and adding it the the sets .
29,029
private boolean unregisterHelper ( Supplier < Optional < AddOnModel > > suppAdd , Supplier < Optional < AddOnInformation > > suppAddInf ) { boolean success1 = false ; Optional < AddOnModel > addOnModel = suppAdd . get ( ) ; if ( addOnModel . isPresent ( ) ) { success1 = addOns . remove ( addOnModel . get ( ) ) ; } boolean success2 = false ; Optional < AddOnInformation > addOnInformation = suppAddInf . get ( ) ; if ( addOnInformation . isPresent ( ) ) { success2 = addOnInformations . remove ( addOnInformation . get ( ) ) ; } return success1 && success2 ; }
Helper to unregister an addOn .
29,030
public AddOnModel getAddonModel ( Identification identification ) { IdentificationImpl impl = ( IdentificationImpl ) identification ; return getAddonModel ( impl . getIdentifiable ( ) ) ; }
gets the AddonModel for the Identification or null if none found
29,031
public AddOnModel getAddonModel ( Identifiable identifiable ) { if ( identifiable . getClass ( ) . getClassLoader ( ) instanceof IzouPluginClassLoader && ! identifiable . getClass ( ) . getName ( ) . toLowerCase ( ) . contains ( IzouPluginClassLoader . PLUGIN_PACKAGE_PREFIX_IZOU_SDK ) ) { return getMain ( ) . getAddOnInformationManager ( ) . getAddOnForClassLoader ( identifiable . getClass ( ) . getClassLoader ( ) ) . orElse ( null ) ; } return null ; }
gets the AddonModel for the Identifiable or null if none found
29,032
public Optional < AddOnModel > getAddOnForClassLoader ( ClassLoader classLoader ) { return addOns . stream ( ) . filter ( addOnModel -> addOnModel . getClass ( ) . getClassLoader ( ) . equals ( classLoader ) ) . findFirst ( ) ; }
Returns the addOn loaded from the given classLoader .
29,033
public int length ( Object o ) { if ( o instanceof List ) { return ( ( List ) o ) . size ( ) ; } else if ( o instanceof Map ) { return ( ( Map ) o ) . size ( ) ; } else if ( o instanceof String ) { return ( ( String ) o ) . length ( ) ; } return 0 ; }
Get string|list|map length
29,034
public static EmailMessage addToRecipientToEmailMessage ( final String recipientEmail , final String recipientPersonal , final String recipientCharset , final EmailMessage emailMessage ) throws UnsupportedEncodingException , MessagingException { Address recipientAddress = EmailExtensions . newAddress ( recipientEmail , recipientPersonal , recipientCharset ) ; if ( null != recipientAddress ) { emailMessage . addTo ( recipientAddress ) ; } else { emailMessage . setRecipients ( Message . RecipientType . TO , recipientEmail ) ; } return emailMessage ; }
Adds a to recipient to the email message .
29,035
public static String getCharsetFromContentType ( final String type ) throws MessagingException { if ( ! type . isNullOrEmpty ( ) ) { int start = type . indexOf ( EmailConstants . CHARSET_PREFIX ) ; if ( start > 0 ) { start += EmailConstants . CHARSET_PREFIX . length ( ) ; final int offset = type . indexOf ( " " , start ) ; if ( offset > 0 ) { return type . substring ( start , offset ) ; } else { return type . substring ( start ) ; } } } return null ; }
Gets the encoding from the header .
29,036
public static Address newAddress ( final String address ) throws AddressException , UnsupportedEncodingException { return newAddress ( address , null , null ) ; }
Creates an Address from the given the email address as String object .
29,037
public static Address newAddress ( final String emailAddress , final String personal ) throws AddressException , UnsupportedEncodingException { return newAddress ( emailAddress , personal , null ) ; }
Creates from the given the address and personal name an Adress - object .
29,038
public static Address newAddress ( final String address , String personal , final String charset ) throws AddressException , UnsupportedEncodingException { if ( personal . isNullOrEmpty ( ) ) { personal = address ; } final InternetAddress internetAdress = new InternetAddress ( address ) ; if ( charset . isNullOrEmpty ( ) ) { internetAdress . setPersonal ( personal ) ; } else { internetAdress . setPersonal ( personal , charset ) ; } return internetAdress ; }
Creates an Address from the given the address and personal name .
29,039
public static EmailMessage setFromToEmailMessage ( final String senderEmail , final String senderPersonal , final String senderCharset , final EmailMessage emailMessage ) throws UnsupportedEncodingException , MessagingException { Address senderAddress = null ; senderAddress = EmailExtensions . newAddress ( senderEmail , senderPersonal , senderCharset ) ; if ( null != senderAddress ) { emailMessage . setFrom ( senderAddress ) ; } else { emailMessage . setFrom ( senderEmail ) ; } return emailMessage ; }
Sets the from to the email message .
29,040
public static boolean validateEmailAdress ( final String emailAddress ) { boolean isValid = true ; try { final InternetAddress internetAddress = new InternetAddress ( emailAddress ) ; internetAddress . validate ( ) ; } catch ( final AddressException e ) { isValid = false ; } return isValid ; }
Validate the given email address .
29,041
public void close ( ) { if ( transactionalBranch != null ) { XATransactionalBranch < C > branch = this . transactionalBranch ; this . release ( ) ; branch . getManagedConnection ( ) . close ( ) ; } }
releases and closes the associated TransactionalBranch and releases the associated resources
29,042
static SecureAccess createSecureAccess ( Main main , SystemMail systemMail ) throws IllegalAccessException { if ( ! exists ) { SecureAccess secureAccess = new SecureAccess ( main , systemMail ) ; exists = true ; return secureAccess ; } throw new IllegalAccessException ( "Cannot create more than one instance of IzouSecurityManager" ) ; }
Creates an SecureAccess . There can only be one single SecureAccess so calling this method twice will cause an illegal access exception .
29,043
public static < T > T readLines ( URL url , Charset charset , LineProcessor < T > callback ) throws IOException { return asCharSource ( url , charset ) . readLines ( callback ) ; }
Streams lines from a URL stopping when our callback returns false or we have read all of the lines .
29,044
private boolean _create ( String path , byte [ ] data , CreateMode createMode ) throws ZooKeeperException { if ( data == null ) { data = ArrayUtils . EMPTY_BYTE_ARRAY ; } try { curatorFramework . create ( ) . creatingParentsIfNeeded ( ) . withMode ( createMode ) . forPath ( path , data ) ; _invalidateCache ( path ) ; return true ; } catch ( InterruptedException e ) { return false ; } catch ( KeeperException . NodeExistsException e ) { return false ; } catch ( KeeperException . ConnectionLossException e ) { throw new ZooKeeperException . ClientDisconnectedException ( ) ; } catch ( Exception e ) { if ( e instanceof ZooKeeperException ) { throw ( ZooKeeperException ) e ; } else { throw new ZooKeeperException ( e ) ; } } }
Creates a new node with initial data .
29,045
private void _watchNode ( String path ) throws ZooKeeperException { try { cacheNodeWatcher . get ( path ) ; } catch ( Exception e ) { if ( e instanceof ZooKeeperException ) { throw ( ZooKeeperException ) e ; } else { throw new ZooKeeperException ( e ) ; } } }
Watches a node for changes .
29,046
private Object _readJson ( String path ) throws ZooKeeperException { String jsonString = getData ( path ) ; try { return jsonString != null ? SerializationUtils . fromJsonString ( jsonString ) : null ; } catch ( Exception e ) { if ( e instanceof ZooKeeperException ) { throw ( ZooKeeperException ) e ; } else { throw new ZooKeeperException ( e ) ; } } }
Reads Json data from a node .
29,047
public boolean nodeExists ( String path ) throws ZooKeeperException { try { Stat stat = curatorFramework . checkExists ( ) . forPath ( path ) ; return stat != null ; } catch ( Exception e ) { if ( e instanceof ZooKeeperException ) { throw ( ZooKeeperException ) e ; } else { throw new ZooKeeperException ( e ) ; } } }
Checks if a path exists .
29,048
public String [ ] getChildren ( String path ) throws ZooKeeperException { try { List < String > result = curatorFramework . getChildren ( ) . forPath ( path ) ; return result != null ? result . toArray ( ArrayUtils . EMPTY_STRING_ARRAY ) : null ; } catch ( KeeperException . NoNodeException e ) { return null ; } catch ( Exception e ) { if ( e instanceof ZooKeeperException ) { throw ( ZooKeeperException ) e ; } else { throw new ZooKeeperException ( e ) ; } } }
Gets children of a node .
29,049
public Object getDataJson ( String path ) throws ZooKeeperException { try { Object data = getFromCache ( cacheNameJson , path ) ; if ( data == null ) { data = _readJson ( path ) ; putToCache ( cacheNameJson , path , data ) ; } return data ; } catch ( ZooKeeperException . NodeNotFoundException e ) { return null ; } catch ( Exception e ) { if ( e instanceof ZooKeeperException ) { throw ( ZooKeeperException ) e ; } else { throw new ZooKeeperException ( e ) ; } } }
Reads data from a node as a JSON object .
29,050
public String getData ( String path ) throws ZooKeeperException { byte [ ] data = getDataRaw ( path ) ; return data != null ? new String ( data , UTF8 ) : null ; }
Reads data from a node .
29,051
public boolean removeNode ( String path , boolean removeChildren ) throws ZooKeeperException { try { if ( removeChildren ) { curatorFramework . delete ( ) . deletingChildrenIfNeeded ( ) . forPath ( path ) ; } else { curatorFramework . delete ( ) . forPath ( path ) ; } } catch ( KeeperException . NotEmptyException e ) { return false ; } catch ( KeeperException . NoNodeException e ) { return true ; } catch ( Exception e ) { if ( e instanceof ZooKeeperException ) { throw ( ZooKeeperException ) e ; } else { throw new ZooKeeperException ( e ) ; } } _invalidateCache ( path ) ; return true ; }
Removes an existing node .
29,052
public boolean setData ( String path , byte [ ] value , boolean createNodes ) throws ZooKeeperException { return _write ( path , value , createNodes ) ; }
Writes raw data to a node .
29,053
private void _connect ( ) throws IOException { curatorFramework = CuratorFrameworkFactory . newClient ( connectString , sessionTimeout , 5000 , new RetryNTimes ( 3 , 2000 ) ) ; curatorFramework . start ( ) ; }
Connects to ZooKeeper server .
29,054
public ImmutableCollection < V > values ( ) { ImmutableCollection < V > result = values ; return ( result == null ) ? values = new ImmutableMapValues < K , V > ( this ) : result ; }
Returns an immutable collection of the values in this map . The values are in the same order as the parameters used to build this map .
29,055
public ImmutableSetMultimap < K , V > asMultimap ( ) { ImmutableSetMultimap < K , V > result = multimapView ; return ( result == null ) ? ( multimapView = new ImmutableSetMultimap < K , V > ( new MapViewOfValuesAsSingletonSets ( ) , size ( ) , null ) ) : result ; }
Returns a multimap view of the map .
29,056
private static String performHttpRequest ( org . dasein . cloud . digitalocean . DigitalOcean provider , RESTMethod method , String token , String endpoint ) throws CloudException , InternalException { return performHttpRequest ( provider , method , token , endpoint , null ) ; }
for get method
29,057
public final boolean encloses ( HString other ) { if ( other == null ) { return false ; } return ( document ( ) != null && other . document ( ) != null ) && ( document ( ) == other . document ( ) ) && super . encloses ( other ) ; }
Checks if this HString encloses the given other .
29,058
public String getLemma ( ) { if ( isInstance ( Types . TOKEN ) ) { if ( contains ( Types . SPELLING_CORRECTION ) ) { return get ( Types . SPELLING_CORRECTION ) . asString ( ) ; } if ( contains ( Types . LEMMA ) ) { return get ( Types . LEMMA ) . asString ( ) ; } return toLowerCase ( ) ; } return tokens ( ) . stream ( ) . map ( HString :: getLemma ) . collect ( Collectors . joining ( getLanguage ( ) . usesWhitespace ( ) ? " " : "" ) ) ; }
Gets the lemmatized version of the HString . Lemmas of longer phrases are constructed from token lemmas .
29,059
public HString head ( ) { return tokens ( ) . stream ( ) . filter ( t -> t . parent ( ) . isEmpty ( ) ) . map ( Cast :: < HString > as ) . findFirst ( ) . orElseGet ( ( ) -> tokens ( ) . stream ( ) . filter ( t -> ! this . overlaps ( t . parent ( ) ) ) . map ( Cast :: < HString > as ) . findFirst ( ) . orElse ( this ) ) ; }
Gets head .
29,060
public final boolean overlaps ( HString other ) { if ( other == null ) { return false ; } return ( document ( ) != null && other . document ( ) != null ) && ( document ( ) == other . document ( ) ) && super . overlaps ( other ) ; }
Checks if this HString overlaps with the given other .
29,061
public HString substring ( int relativeStart , int relativeEnd ) { Preconditions . checkPositionIndexes ( relativeStart , relativeEnd , length ( ) ) ; return new Fragment ( document ( ) , start ( ) + relativeStart , start ( ) + relativeEnd ) ; }
Returns a new HString that is a substring of this one . The substring begins at the specified relativeStart and extends to the character at index relativeEnd - 1 . Thus the length of the substring is relativeEnd - relativeStart .
29,062
public String toPOSString ( char delimiter ) { return tokens ( ) . stream ( ) . map ( t -> t . toString ( ) + delimiter + t . get ( Types . PART_OF_SPEECH ) . as ( POS . class , POS . ANY ) . asString ( ) ) . collect ( Collectors . joining ( " " ) ) ; }
Converts the HString to a string with part - of - speech information attached using the given delimiter
29,063
public static ContextInfo fromConfig ( ConfigParams config ) { ContextInfo result = new ContextInfo ( ) ; result . configure ( config ) ; return result ; }
Creates a new ContextInfo and sets its configuration parameters .
29,064
public < T extends RoxPayload > T load ( String name , Class < T > clazz ) throws IOException { InputStreamReader isr = new InputStreamReader ( new FileInputStream ( new File ( getTmpDir ( clazz ) , name ) ) , Charset . forName ( Constants . ENCODING ) . newDecoder ( ) ) ; return serializer . deserializePayload ( isr , clazz ) ; }
Load a payload
29,065
public < T extends RoxPayload > List < T > load ( Class < T > clazz ) throws IOException { List < T > payloads = new ArrayList < > ( ) ; for ( File f : getTmpDir ( clazz ) . listFiles ( ) ) { if ( f . isFile ( ) ) { InputStreamReader isr = new InputStreamReader ( new FileInputStream ( f ) , Charset . forName ( Constants . ENCODING ) . newDecoder ( ) ) ; payloads . add ( serializer . deserializePayload ( isr , clazz ) ) ; } } return payloads ; }
Load a list of payload
29,066
public SequencalJobExecuteResults runAll ( ) { SequencalJobExecuteResults results = new SequencalJobExecuteResults ( ) ; for ( Job job : jobs ) { job . setJarByClass ( SequencalJobChain . class ) ; try { boolean isSuccessful = job . waitForCompletion ( true ) ; results . add ( new SequencalJobExecuteResult ( isSuccessful , job . getJobName ( ) ) ) ; if ( ! isSuccessful ) { break ; } } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } return results ; }
Run all of the job has been added .
29,067
public FieldCounter < Double > extract ( String jsonString , String recordId ) { return extract ( jsonString , recordId , false ) ; }
Extracts sums and average of TF - IDF value for the schema s Solr field array without collecting the terms .
29,068
private void flushQueue ( ) { while ( true ) { final Action act = firstNonNull ( actionQueue . poll ( ) , new Action ( Actions . END , null ) ) ; switch ( act . action ) { case POST : post ( act . object ) ; break ; case REGISTER : register ( act . object ) ; break ; case UNREGISTER : unregister ( act . object ) ; break ; case END : default : return ; } } }
Flushes the queue
29,069
public static URL getDeepResource ( ClassLoader startLoader , String resourceName ) { ClassLoader currentLoader = checkNotNull ( startLoader ) ; URL url = currentLoader . getResource ( checkNotEmpty ( resourceName ) ) ; int attempts = 0 ; while ( url == null && attempts < 10 ) { currentLoader = currentLoader . getParent ( ) ; attempts += 1 ; if ( currentLoader == null ) { break ; } url = currentLoader . getResource ( resourceName ) ; } checkArgument ( url != null , "resource %s not found for the context class loader %s" , resourceName , startLoader ) ; return url ; }
Search class loader tree for resource current implementation attempts up to 10 levels of nested class loaders .
29,070
public static TokenRegex compile ( String pattern ) throws ParseException { ExpressionIterator p = QueryToPredicate . PARSER . parse ( pattern ) ; Expression exp ; TransitionFunction top = null ; while ( ( exp = p . next ( ) ) != null ) { if ( top == null ) { top = consumerize ( exp ) ; } else { top = new TransitionFunction . Sequence ( top , consumerize ( exp ) ) ; } } return new TokenRegex ( top ) ; }
Compiles the regular expression
29,071
public Optional < HString > matchFirst ( HString text ) { TokenMatcher matcher = new TokenMatcher ( nfa , text ) ; if ( matcher . find ( ) ) { return Optional . of ( matcher . group ( ) ) ; } return Optional . empty ( ) ; }
Match first optional .
29,072
public Set < String > getVariableNames ( ) { final ImmutableSet . Builder < String > sb = ImmutableSet . builder ( ) ; for ( final Expression expr : expressions ) for ( final Variable var : expr . getVariables ( ) ) sb . add ( var . getName ( ) ) ; return sb . build ( ) ; }
Returns an immutable set of variable names contained in the expressions of this URI Template .
29,073
public Settings parse ( String [ ] arguments ) throws CommandLineException { Settings out = new Settings ( ) ; if ( arguments != null ) { CommandOption option = null ; for ( String argument : arguments ) { if ( isOption ( argument ) ) { option = findOption ( argument ) ; if ( option != null && ! option . hasArguments ( ) ) { out . put ( option . getSetting ( ) , option . parse ( argument ) ) ; } continue ; } if ( option == null ) { throw new CommandLineException ( "Unknown command line option: " + argument ) ; } Object value = option . parse ( argument ) ; out . put ( option . getSetting ( ) , value ) ; } } CommandOption config = builder . getConfigFileOption ( ) ; CommandBuilder defaults = new CommandBuilder ( builder . get ( ) ) ; if ( config != null ) { String file = ( String ) out . get ( config . getSetting ( ) ) ; if ( file != null ) { ConfigFileReader reader = new ConfigFileReader ( ) ; Settings configSettings = reader . load ( file , builder ) ; defaults . setDefaults ( configSettings ) ; out . remove ( config . getSetting ( ) ) ; } } for ( CommandOption option : defaults . get ( ) ) { if ( ! ( option instanceof ConfigFileOption ) && ! out . containsKey ( option . getSetting ( ) ) ) { out . put ( option . getSetting ( ) , option . getDefault ( ) ) ; } } return out ; }
Returns HashMap of read out settings
29,074
private CommandOption findOption ( String argument ) { if ( "--" . equals ( argument ) || argument == null ) { return null ; } if ( argument . startsWith ( "--" ) ) { return builder . findLong ( argument ) ; } if ( argument . startsWith ( "-" ) ) { return builder . findShort ( argument ) ; } CommandOption found = builder . findShort ( argument ) ; if ( found == null ) { found = builder . findLong ( argument ) ; } return found ; }
Extracts argument and returns setting
29,075
private String escape ( final String string , final State inState ) { if ( string == null ) { return null ; } State state = inState ; final int length = string . length ( ) ; for ( int index = 0 ; index < length ; index ++ ) { if ( state == State . HOST && string . indexOf ( PROTOCOL_SEPARATOR ) == index ) { index += PROTOCOL_SEPARATOR . length ( ) ; continue ; } final char c = string . charAt ( index ) ; if ( HOST_SEPARATOR . matches ( c ) && state == State . HOST ) { state = State . PATH ; } if ( FRAG_SEPARATOR . matches ( c ) && state != State . FRAGMENT && state != State . QUERY_PARAM ) { state = State . FRAGMENT ; } else if ( QUERY_SEPARATOR . matches ( c ) && ( state == State . PATH || state == State . HOST ) ) { state = State . QUERY ; } else { final String encodeString = encodeCharAtIndex ( string , index , state ) ; if ( encodeString != null ) { return string . substring ( 0 , index ) + encodeString + escape ( string . substring ( index + 1 ) , state ) ; } } } return string ; }
Returns the escaped string beginning in the given state . This function can be called recursively .
29,076
private boolean isIllegal ( final char c , final State state ) { switch ( state ) { case FRAGMENT : return ( strict ? STRICT_ILLEGAL_IN_FRAGMENT : ILLEGAL_IN_FRAGMENT ) . matches ( c ) ; case QUERY : return ( strict ? STRICT_ILLEGAL_IN_QUERY : ILLEGAL_IN_QUERY ) . matches ( c ) ; case QUERY_PARAM : return ( strict ? STRICT_ILLEGAL_IN_QUERY_PARAM : ILLEGAL_IN_QUERY_PARAM ) . matches ( c ) ; case PATH : return ( strict ? STRICT_ILLEGAL_IN_PATH : ILLEGAL_IN_PATH ) . matches ( c ) ; case HOST : return ILLEGAL_IN_HOST . matches ( c ) ; default : throw new AssertionError ( state ) ; } }
Returns whether or not this character is illegal in the given state
29,077
private String encodeCharAtIndex ( final String string , final int index , final State state ) { final char c = string . charAt ( index ) ; if ( ( SPACE . matches ( c ) && ( ( state != State . QUERY && state != State . QUERY_PARAM ) || strict ) ) || ( strict && PLUS . matches ( c ) && state == State . QUERY ) ) { return "%20" ; } if ( ESCAPED . matches ( c ) && string . length ( ) > index + 2 && HEX . matches ( string . charAt ( index + 1 ) ) && HEX . matches ( string . charAt ( index + 2 ) ) ) { return null ; } if ( isIllegal ( c , state ) ) { try { if ( c == '*' ) { return "%2A" ; } else { return URLEncoder . encode ( Character . toString ( c ) , "UTF-8" ) ; } } catch ( UnsupportedEncodingException e ) { throw new AssertionError ( "UTF-8 always exists, " + e . getMessage ( ) ) ; } } return null ; }
Encodes the character at the given index and returns the resulting string . If the character does not need to be encoded this function returns null
29,078
public static String escape ( final String url , final boolean strict ) { return ( strict ? STRICT_ESCAPER : ESCAPER ) . escape ( url ) ; }
Escapes a string as a URI
29,079
public static String escapePath ( final String path , final boolean strict ) { return ( strict ? STRICT_ESCAPER : ESCAPER ) . escapePath ( path ) ; }
Escapes a string as a URI path
29,080
public static SelectedRule rule ( String rule , ArgumentBuilder arguments ) throws Exception { if ( AunitRuntime . getParserFactory ( ) == null ) throw new IllegalStateException ( "Parser factory not set by configuration" ) ; for ( Method method : collectMethods ( AunitRuntime . getParserFactory ( ) . getParserClass ( ) ) ) { if ( method . getName ( ) . equals ( rule ) ) { return new SelectedRule ( method , arguments . get ( ) ) ; } } throw new Exception ( "Rule " + rule + " not found" ) ; }
Select a rule to be used as a starting point in
29,081
public static SelectedRule withRule ( String rule , ArgumentBuilder arguments ) throws Exception { if ( AunitRuntime . getTreeParserFactory ( ) == null ) throw new IllegalStateException ( "TreeParser factory not set by configuration" ) ; for ( Method method : collectMethods ( AunitRuntime . getTreeParserFactory ( ) . getTreeParserClass ( ) ) ) { if ( method . getName ( ) . equals ( rule ) ) { return new SelectedRule ( method , arguments . get ( ) ) ; } } throw new Exception ( "Rule " + rule + " not found" ) ; }
Select a tree rule be used as a starting point in tree walking
29,082
public static < T > T generateParser ( String src ) throws Exception { ANTLRInputStream input = new ANTLRInputStream ( new ByteArrayInputStream ( src . getBytes ( ) ) ) ; Lexer lexer = AunitRuntime . getLexerFactory ( ) . generate ( input ) ; CommonTokenStream tokens = new CommonTokenStream ( lexer ) ; return ( T ) AunitRuntime . getParserFactory ( ) . generate ( tokens ) ; }
Generate an instance of the configured parser using a string as a source for input .
29,083
public static < T > T generateParser ( File src ) throws Exception { ANTLRInputStream input = new ANTLRInputStream ( new FileInputStream ( src ) ) ; Lexer lexer = AunitRuntime . getLexerFactory ( ) . generate ( input ) ; CommonTokenStream tokens = new CommonTokenStream ( lexer ) ; return ( T ) AunitRuntime . getParserFactory ( ) . generate ( tokens ) ; }
Generate an instance of the configured parser using a file as a source for input .
29,084
private static Set < Method > collectMethods ( Class clazz ) { if ( clazz == null ) return Collections . emptySet ( ) ; Set < Method > s = new HashSet < Method > ( ) ; s . addAll ( Arrays . asList ( clazz . getDeclaredMethods ( ) ) ) ; s . addAll ( collectMethods ( clazz . getSuperclass ( ) ) ) ; return s ; }
Recursively collect the set of declared methods of a class and its super class .
29,085
@ SuppressWarnings ( { "ThrowableInstanceNeverThrown" } ) public static void validatePublicNoArg ( Method method , List < Throwable > errors ) { if ( ! Modifier . isPublic ( method . getModifiers ( ) ) ) { errors . add ( new Exception ( "Method " + method . getName ( ) + "() should be public" ) ) ; } if ( method . getParameterTypes ( ) . length != 0 ) { errors . add ( new Exception ( "Method " + method . getName ( ) + " should have no parameters" ) ) ; } }
Validate that a method is public has no arguments .
29,086
@ SuppressWarnings ( { "ThrowableInstanceNeverThrown" } ) public static void validateVoid ( Method method , List < Throwable > errors ) { if ( method . getReturnType ( ) != Void . TYPE ) { errors . add ( new Exception ( "Method " + method . getName ( ) + "() should be void" ) ) ; } }
Validate that a method returns no value .
29,087
@ SuppressWarnings ( { "ThrowableInstanceNeverThrown" } ) public static void validatePrimitiveArray ( Method method , Class type , List < Throwable > errors ) { Class returnType = method . getReturnType ( ) ; if ( ! returnType . isArray ( ) || ! returnType . getComponentType ( ) . equals ( type ) ) { errors . add ( new Exception ( "Method " + method . getName ( ) + "() should return " + type . getName ( ) + "[]" ) ) ; } }
Validate that a method returns primitive array of specific type .
29,088
@ SuppressWarnings ( { "ThrowableInstanceNeverThrown" } ) public static void validateIsStatic ( Method method , List < Throwable > errors ) { if ( ! Modifier . isStatic ( method . getModifiers ( ) ) ) { errors . add ( new Exception ( "Method " + method . getName ( ) + "() should be static" ) ) ; } if ( ! Modifier . isPublic ( method . getDeclaringClass ( ) . getModifiers ( ) ) ) { errors . add ( new Exception ( "Class " + method . getDeclaringClass ( ) . getName ( ) + " should be public" ) ) ; } }
Validate that a method is static .
29,089
private LinkedList < Device > getDevices ( SSLSocket socket ) throws CommunicationException { LinkedList < Device > listDev = null ; try { InputStream socketStream = socket . getInputStream ( ) ; byte [ ] b = new byte [ 1024 ] ; ByteArrayOutputStream message = new ByteArrayOutputStream ( ) ; int nbBytes = 0 ; while ( ( nbBytes = socketStream . read ( b , 0 , 1024 ) ) != - 1 ) { message . write ( b , 0 , nbBytes ) ; } listDev = new LinkedList < Device > ( ) ; byte [ ] listOfDevices = message . toByteArray ( ) ; int nbTuples = listOfDevices . length / FEEDBACK_TUPLE_SIZE ; logger . debug ( "Found: [" + nbTuples + "]" ) ; for ( int i = 0 ; i < nbTuples ; i ++ ) { int offset = i * FEEDBACK_TUPLE_SIZE ; int index = 0 ; int firstByte = 0 ; int secondByte = 0 ; int thirdByte = 0 ; int fourthByte = 0 ; long anUnsignedInt = 0 ; firstByte = ( 0x000000FF & ( ( int ) listOfDevices [ offset ] ) ) ; secondByte = ( 0x000000FF & ( ( int ) listOfDevices [ offset + 1 ] ) ) ; thirdByte = ( 0x000000FF & ( ( int ) listOfDevices [ offset + 2 ] ) ) ; fourthByte = ( 0x000000FF & ( ( int ) listOfDevices [ offset + 3 ] ) ) ; index = index + 4 ; anUnsignedInt = ( ( long ) ( firstByte << 24 | secondByte << 16 | thirdByte << 8 | fourthByte ) ) & 0xFFFFFFFFL ; Timestamp timestamp = new Timestamp ( anUnsignedInt * 1000 ) ; int deviceTokenLength = listOfDevices [ offset + 4 ] << 8 | listOfDevices [ offset + 5 ] ; String deviceToken = "" ; int octet = 0 ; for ( int j = 0 ; j < 32 ; j ++ ) { octet = ( 0x000000FF & ( ( int ) listOfDevices [ offset + 6 + j ] ) ) ; deviceToken = deviceToken . concat ( String . format ( "%02x" , octet ) ) ; } Device device = new BasicDevice ( ) ; device . setToken ( deviceToken ) ; device . setLastRegister ( timestamp ) ; listDev . add ( device ) ; logger . info ( "FeedbackManager retrieves one device : " + timestamp + ";" + deviceTokenLength + ";" + deviceToken + "." ) ; } } catch ( Exception e ) { logger . debug ( "Caught exception fetching devices from Feedback Service" ) ; throw new CommunicationException ( "Problem communicating with Feedback service" , e ) ; } finally { try { socket . close ( ) ; } catch ( Exception e ) { } } return listDev ; }
Retrieves the list of devices from an established SSLSocket .
29,090
protected Object doExec ( Element element , Object scope , String formatterName , Object ... arguments ) { Format format = getFormat ( formatterName ) ; if ( format == null ) { throw new TemplateException ( "Formatting class |%s| not found." , formatterName ) ; } return format ; }
Execute FORMAT operator . Returns requested formatter instance throwing templates exception if not found .
29,091
public static Format getFormat ( String className ) { assert className != null ; if ( className . isEmpty ( ) ) { return null ; } ThreadLocal < Format > tlsFormatter = classFormatters . get ( className ) ; if ( tlsFormatter == null ) { try { Classes . forName ( className ) ; tlsFormatter = new ThreadLocal < Format > ( ) ; classFormatters . put ( className , tlsFormatter ) ; } catch ( NoSuchBeingException e ) { log . error ( "Formatter class |%s| not found." , className ) ; return null ; } catch ( ClassCastException e ) { log . error ( "Invalid formatter class |%s|. It should inherit from |%s|." , className , Format . class ) ; return null ; } } Format formatter = tlsFormatter . get ( ) ; if ( formatter == null ) { formatter = createFormatter ( className ) ; if ( formatter == null ) { throw new BugError ( "Invalid formatter class |%s|. Proper constructor not found." , className ) ; } tlsFormatter . set ( formatter ) ; } return formatter ; }
Return format instance usable to requested class .
29,092
public void execute ( ) throws MojoExecutionException { getLog ( ) . debug ( "- outputDirectory : " + outputDirectory ) ; try { CheckService . isValidOutputDirectory ( outputDirectory ) ; } catch ( InvalidOutputDirectoryException e ) { throw new MojoExecutionException ( "CheckService return error(s)" , e ) ; } getLog ( ) . debug ( "- resources : " + resources ) ; for ( Resource resource : resources ) { try { ResourceService . execute ( this , resource , outputDirectory ) ; } catch ( ResourceExecutionException e ) { throw new MojoExecutionException ( "ResourceService return error(s)" , e ) ; } } }
entry point for goal copy
29,093
public void setProperties ( Properties properties ) { baseDir = properties . getProperty ( "base_dir" , baseDir ) ; inputFileLocation = baseDir + '/' + properties . getProperty ( "input_file_location" , inputFileLocation ) ; outputFileLocation = baseDir + '/' + properties . getProperty ( "output_file_location" , outputFileLocation ) ; tempOutputFileLocation = baseDir + '/' + properties . getProperty ( "temp_output_file_location" , tempOutputFileLocation ) ; }
Determines file locations .
29,094
public void start ( ) { System . out . println ( new LogEntry ( "starting root console" ) ) ; try { openFileReader ( ) ; } catch ( IOException ioe ) { throw new ResourceException ( "can not open file reader" , ioe ) ; } thread = new Thread ( this ) ; isRunning = true ; thread . start ( ) ; }
Starts monitoring the input file .
29,095
public void stop ( ) { isRunning = false ; thread . interrupt ( ) ; try { closeFileReader ( ) ; } catch ( IOException ioe ) { System . out . println ( new LogEntry ( Level . CRITICAL , "I/O exception while closing file reader: " + ioe . getMessage ( ) , ioe ) ) ; } }
Stops monitoring the input file .
29,096
private void writeResult ( Object result ) throws IOException { File outputFile = new File ( outputFileLocation ) ; File tempfile = FileSupport . createFile ( tempOutputFileLocation ) ; FileOutputStream fos = null ; try { fos = new FileOutputStream ( tempfile ) ; PrintStream ps = new PrintStream ( new FileOutputStream ( tempfile ) ) ; if ( result != null ) { if ( result instanceof Throwable ) { ( ( Throwable ) result ) . printStackTrace ( ps ) ; } ps . println ( result . toString ( ) ) ; } ps . close ( ) ; } finally { fos . close ( ) ; } if ( outputFile . exists ( ) ) { boolean success = outputFile . delete ( ) ; } boolean success = tempfile . renameTo ( new File ( outputFileLocation ) ) ; }
Writes result to the output file .
29,097
public void writeToFile ( File f ) { try ( FileOutputStream fos = new FileOutputStream ( f ) ) { fos . write ( write ( ) ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } }
Writes the BDS to the given file .
29,098
public static < T > Invoker of ( final Provider < T > provider ) { if ( provider == null ) throw new NullPointerException ( "provider" ) ; return new Invoker ( ) { public Object invoke ( final Invocation invocation ) throws Exception { T service = provider . get ( ) ; return invocation . invoke ( service ) ; } } ; }
Creates an invoker which uses a service provider to execute invocations .
29,099
public byte set ( int index , byte e ) { rangeCheck ( index ) ; byte value = elements [ index ] ; elements [ index ] = e ; return value ; }
Sets an element of this array .