idx
int64
0
165k
question
stringlengths
73
5.81k
target
stringlengths
5
918
8,000
public static Observable < BackendUser > signUpInBackground ( String username , String email , String password ) { return getAM ( ) . signUpASync ( new SignUpCredentials ( username , email , password ) ) ; }
Perform asyncronously sign up attempt .
8,001
public boolean signUp ( ) { SignUpCredentials creds = new SignUpCredentials ( getUsername ( ) , getEmailAddress ( ) , getPassword ( ) ) ; SignUpResponse response = getAM ( ) . signUp ( creds ) ; if ( response . getStatus ( ) . isSuccess ( ) ) { this . initFrom ( response . get ( ) ) ; return true ; } else return false ...
Synchronously sign up using credentials provided via constructor or setters .
8,002
public static KeyPair generateKeyPair ( final int keyLen ) throws NoSuchAlgorithmException { final String name = ASYM_CIPHER_CHAIN_PADDING ; final int offset = name . indexOf ( '/' ) ; final String alg = ( ( offset < 0 ) ? name : name . substring ( 0 , offset ) ) ; final KeyPairGenerator generator = KeyPairGenerator . ...
Generate RSA KeyPair
8,003
public ByteBuffer getByteBuffer ( ) { final ByteBuffer bb = ByteBuffer . wrap ( buf ) ; bb . limit ( bufLimit ) ; bb . position ( bufPosition ) ; return bb ; }
Return internal buffer as ByteBuffer
8,004
public byte [ ] outputBytes ( ) { byte [ ] tmpBuf = buf ; int len = bufLimit ; int flags = 0 ; if ( useCompress ) { flags |= FLAG_COMPRESS ; tmpBuf = deflate ( tmpBuf , len ) ; len = tmpBuf . length ; } if ( aesKey != null ) { flags |= FLAG_AES ; try { tmpBuf = crypto ( tmpBuf , 0 , len , false ) ; } catch ( Exception ...
Output bytes in raw format
8,005
public Packer loadStringHex ( final String in ) throws InvalidInputDataException { try { return loadBytes ( fromHex ( in ) ) ; } catch ( ParseException e ) { throw new IllegalArgumentException ( "Invalid input string" , e ) ; } }
Load string in hex format
8,006
final byte [ ] crypto ( final byte [ ] input , final int offset , final int len , final boolean decrypt ) throws InvalidKeyException , InvalidAlgorithmParameterException , IllegalBlockSizeException , BadPaddingException { aesCipher . init ( decrypt ? Cipher . DECRYPT_MODE : Cipher . ENCRYPT_MODE , aesKey , aesIV ) ; re...
Encrypt or Decrypt with AES
8,007
final byte [ ] cryptoAsym ( final byte [ ] input , final int offset , final int len , final boolean decrypt ) throws InvalidKeyException , InvalidAlgorithmParameterException , IllegalBlockSizeException , BadPaddingException { rsaCipher . init ( decrypt ? Cipher . DECRYPT_MODE : Cipher . ENCRYPT_MODE , decrypt ? rsaKeyF...
Encrypt or Decrypt with RSA
8,008
static final byte [ ] resizeBuffer ( final byte [ ] buf , final int newsize ) { if ( buf . length == newsize ) return buf ; final byte [ ] newbuf = new byte [ newsize ] ; System . arraycopy ( buf , 0 , newbuf , 0 , Math . min ( buf . length , newbuf . length ) ) ; return newbuf ; }
Resize input buffer to newsize
8,009
static final boolean compareBuffer ( final byte [ ] buf1 , final int offset1 , final byte [ ] buf2 , final int offset2 , final int len ) { for ( int i = 0 ; i < len ; i ++ ) { final byte b1 = buf1 [ offset1 + i ] ; final byte b2 = buf2 [ offset2 + i ] ; if ( b1 != b2 ) { return false ; } } return true ; }
Compare buffer1 and buffer2
8,010
static final String toHex ( final byte [ ] input , final int len , final boolean upper ) { final char [ ] hex = new char [ len << 1 ] ; for ( int i = 0 , j = 0 ; i < len ; i ++ ) { final int bx = input [ i ] ; final int bh = ( ( bx >> 4 ) & 0xF ) ; final int bl = ( bx & 0xF ) ; if ( ( bh >= 0 ) && ( bh <= 9 ) ) { hex [...
Transform byte array to Hex String
8,011
static final byte [ ] fromHex ( final String hex ) throws ParseException { final int len = hex . length ( ) ; final byte [ ] out = new byte [ len / 2 ] ; for ( int i = 0 , j = 0 ; i < len ; i ++ ) { char c = hex . charAt ( i ) ; int v = 0 ; if ( ( c >= '0' ) && ( c <= '9' ) ) { v = ( c - '0' ) ; } else if ( ( c >= 'A' ...
Transform Hex String to byte array
8,012
static final byte [ ] deflate ( final byte [ ] in , final int len ) { byte [ ] defBuf = new byte [ len << 1 ] ; int payloadLength ; synchronized ( deflater ) { deflater . reset ( ) ; deflater . setInput ( in , 0 , len ) ; deflater . finish ( ) ; payloadLength = deflater . deflate ( defBuf ) ; } return resizeBuffer ( de...
Deflate input buffer
8,013
static final byte [ ] inflate ( final byte [ ] in , final int offset , final int length ) throws DataFormatException { byte [ ] infBuf = new byte [ length << 1 ] ; int payloadLength ; synchronized ( inflater ) { inflater . reset ( ) ; inflater . setInput ( in , offset , length ) ; payloadLength = inflater . inflate ( i...
Inflate input buffer
8,014
public static boolean copyFile ( File srcFile , File destFile ) { boolean result = false ; try { InputStream in = new FileInputStream ( srcFile ) ; try { result = copyToFile ( in , destFile ) ; } finally { in . close ( ) ; } } catch ( IOException e ) { result = false ; } return result ; }
false if fail
8,015
public static boolean copyToFile ( InputStream inputStream , File destFile ) { try { OutputStream out = new FileOutputStream ( destFile ) ; try { byte [ ] buffer = new byte [ 4096 ] ; int bytesRead ; while ( ( bytesRead = inputStream . read ( buffer ) ) >= 0 ) { out . write ( buffer , 0 , bytesRead ) ; } } finally { ou...
Copy data from a source stream to destFile . Return true if succeed return false if failed .
8,016
public static String readTextFile ( File file , int max , String ellipsis ) throws IOException { InputStream input = new FileInputStream ( file ) ; try { if ( max > 0 ) { byte [ ] data = new byte [ max + 1 ] ; int length = input . read ( data ) ; if ( length <= 0 ) return "" ; if ( length <= max ) return new String ( d...
Read a text file into a String optionally limiting the length .
8,017
public void setFilePermissions ( FilePermissions filePermissions ) { if ( isWritable ( ) ) { meta_data . put ( PERMISSIONS_KEY . KEY , gson . toJson ( filePermissions , FilePermissions . class ) ) ; } }
Sets new file permissions for this object .
8,018
protected void setOwnerId ( Integer id ) { if ( getOwnerId ( ) != null ) { logger . warn ( "Attempting to set owner id for an object where it as previously been set. Ignoring new id" ) ; return ; } meta_put ( OWNER_ID_KEY , id ) ; }
accessable to subclasses and this class stupid java .
8,019
public DAOArray fromDao ( DAO [ ] daoList ) throws DAOArrayException { for ( DAO dao : daoList ) { add ( dao ) ; } return this ; }
convert a list of dao into this format
8,020
public DAO [ ] convert ( ) { int size = data . size ( ) ; DAO [ ] daoList = new DAO [ size ] ; for ( int i = 0 ; i < size ; i ++ ) { Object [ ] dat = data . get ( i ) ; DAO dao = new DAO ( modelName ) ; for ( int j = 0 ; j < attributes . length ; j ++ ) { dao . set_Value ( attributes [ j ] , dat [ j ] ) ; } daoList [ i...
From this format convert back to DAO
8,021
public List < T > getSortedKeys ( ) { List < T > l = Lists . newArrayList ( counts . keySet ( ) ) ; Collections . sort ( l , Ordering . natural ( ) . reverse ( ) . onResultOf ( Functions . forMap ( counts . getBaseMap ( ) ) ) ) ; return l ; }
Gets the keys in this sorted order from the highest count to the lowest count .
8,022
public static ListSupertaggedSentence createWithUnobservedSupertags ( List < String > words , List < String > pos ) { return new ListSupertaggedSentence ( WordAndPos . createExample ( words , pos ) , Collections . nCopies ( words . size ( ) , Collections . < HeadedSyntacticCategory > emptyList ( ) ) , Collections . nCo...
Creates a supertagged sentence where the supertags for each word are unobserved . Using this sentence during CCG parsing allows any syntactic category to be assigned to each word .
8,023
public Object next ( ) { assertGeneratorStarted ( ) ; if ( ! hasNext ( ) ) { throw new NoSuchElementException ( "No more object to generate" ) ; } Object object = currentFixtureGenerator . next ( ) ; logger . debug ( "Generated {}" , object ) ; extractorDelegate . extractEntity ( object ) ; return object ; }
Returns the next entity to load .
8,024
public static MapReduceExecutor getMapReduceExecutor ( ) { if ( executor == null ) { executor = new LocalMapReduceExecutor ( Runtime . getRuntime ( ) . availableProcessors ( ) , 20 ) ; } return executor ; }
Gets the global map - reduce executor .
8,025
public List < Assignment > getNonzeroAssignments ( ) { Iterator < Outcome > outcomeIter = outcomeIterator ( ) ; List < Assignment > assignments = Lists . newArrayList ( ) ; while ( outcomeIter . hasNext ( ) ) { Outcome outcome = outcomeIter . next ( ) ; if ( outcome . getProbability ( ) != 0.0 ) { assignments . add ( o...
Gets all assignments to this factor which have non - zero weight .
8,026
private double getPartitionFunction ( ) { if ( partitionFunction != - 1.0 ) { return partitionFunction ; } partitionFunction = 0.0 ; Iterator < Outcome > outcomeIterator = outcomeIterator ( ) ; while ( outcomeIterator . hasNext ( ) ) { partitionFunction += outcomeIterator . next ( ) . getProbability ( ) ; } return part...
Get the partition function = denominator = total sum probability of all assignments .
8,027
public static < A , B > Map < A , B > fromLists ( List < A > keys , List < B > values ) { Preconditions . checkArgument ( keys . size ( ) == values . size ( ) ) ; Map < A , B > map = Maps . newHashMap ( ) ; for ( int i = 0 ; i < keys . size ( ) ; i ++ ) { map . put ( keys . get ( i ) , values . get ( i ) ) ; } return m...
Returns a map where the ith element of keys maps to the ith element of values .
8,028
public static Type inferType ( Expression2 expression , Type rootType , TypeDeclaration typeDeclaration ) { Map < Integer , Type > subexpressionTypeMap = inferTypeMap ( expression , rootType , typeDeclaration ) ; return subexpressionTypeMap . get ( 0 ) ; }
Implementation of type inference that infers types for expressions using the basic type information in typeDeclaration .
8,029
public static boolean eventDateValid ( String eventDate ) { boolean result = false ; if ( extractDate ( eventDate ) != null ) { result = true ; } else { Interval interval = extractInterval ( eventDate ) ; if ( interval != null ) { if ( interval . getStart ( ) . isBefore ( interval . getEnd ( ) ) ) { result = true ; } }...
Test to see whether an eventDate contains a string in an expected ISO format .
8,030
public static Map < String , String > extractDateFromVerbatim ( String verbatimEventDate ) { return extractDateFromVerbatim ( verbatimEventDate , DateUtils . YEAR_BEFORE_SUSPECT ) ; }
Attempt to extract a date or date range in standard format from a provided verbatim date string .
8,031
public static boolean isRange ( String eventDate ) { boolean isRange = false ; if ( eventDate != null ) { String [ ] dateBits = eventDate . split ( "/" ) ; if ( dateBits != null && dateBits . length == 2 ) { DateTimeParser [ ] parsers = { DateTimeFormat . forPattern ( "yyyy-MM" ) . getParser ( ) , DateTimeFormat . forP...
Test to see if a string appears to represent a date range of more than one day .
8,032
public static Interval extractInterval ( String eventDate ) { Interval result = null ; DateTimeParser [ ] parsers = { DateTimeFormat . forPattern ( "yyyy-MM" ) . getParser ( ) , DateTimeFormat . forPattern ( "yyyy" ) . getParser ( ) , ISODateTimeFormat . dateOptionalTimeParser ( ) . getParser ( ) } ; DateTimeFormatter ...
Given a string that may be a date or a date range extract a interval of dates from that date range up to the end milisecond of the last day .
8,033
public static DateMidnight extractDate ( String eventDate ) { DateMidnight result = null ; DateTimeParser [ ] parsers = { DateTimeFormat . forPattern ( "yyyy-MM" ) . getParser ( ) , DateTimeFormat . forPattern ( "yyyy" ) . getParser ( ) , DateTimeFormat . forPattern ( "yyyy-MM-dd/yyyy-MM-dd" ) . getParser ( ) , ISODate...
Extract a single joda date from an event date .
8,034
public static boolean isConsistent ( String eventDate , String startDayOfYear , String endDayOfYear , String year , String month , String day ) { if ( isEmpty ( eventDate ) || ( isEmpty ( startDayOfYear ) && isEmpty ( endDayOfYear ) && isEmpty ( year ) && isEmpty ( month ) && isEmpty ( day ) ) ) { return true ; } boole...
Identify whether an event date is consistent with its atomic parts .
8,035
public static boolean isEmpty ( String aString ) { boolean result = true ; if ( aString != null && aString . trim ( ) . length ( ) > 0 ) { if ( ! aString . trim ( ) . toUpperCase ( ) . equals ( "NULL" ) ) { result = false ; } } return result ; }
Does a string contain a non - blank value .
8,036
public static boolean specificToDay ( String eventDate ) { boolean result = false ; if ( ! isEmpty ( eventDate ) ) { Interval eventDateInterval = extractInterval ( eventDate ) ; logger . debug ( eventDateInterval ) ; logger . debug ( eventDateInterval . toDuration ( ) ) ; if ( eventDateInterval . toDuration ( ) . getSt...
Test if an event date specifies a duration of one day or less .
8,037
public static boolean specificToDecadeScale ( String eventDate ) { boolean result = false ; if ( ! isEmpty ( eventDate ) ) { Interval eventDateInterval = extractDateInterval ( eventDate ) ; if ( eventDateInterval . toDuration ( ) . getStandardDays ( ) <= 3650l ) { result = true ; } } return result ; }
Test if an event date specifies a duration of 10 years or less .
8,038
protected static String instantToStringTime ( Instant instant ) { String result = "" ; if ( instant != null ) { StringBuffer time = new StringBuffer ( ) ; time . append ( String . format ( "%02d" , instant . get ( DateTimeFieldType . hourOfDay ( ) ) ) ) ; time . append ( ":" ) . append ( String . format ( "%02d" , inst...
Given an instant return the time within one day that it represents as a string .
8,039
public static int countLeapDays ( String eventDate ) { int result = 0 ; if ( ! DateUtils . isEmpty ( eventDate ) && DateUtils . eventDateValid ( eventDate ) ) { Interval interval = extractInterval ( eventDate ) ; Integer sYear = interval . getStart ( ) . getYear ( ) ; Integer eYear = interval . getEnd ( ) . getYear ( )...
Count the number of leap days present in an event date
8,040
public void store ( final RandomRoutingTable . Snapshot snapshot ) throws IOException { try { saveString ( serialize ( snapshot ) ) ; } catch ( final JsonGenerationException e ) { throw new IOException ( "Error serializing routing snapshot" , e ) ; } catch ( final JsonMappingException e ) { throw new IOException ( "Err...
Store routing table information via this mechanism .
8,041
private < T > String buildClassListTag ( final T t ) { return ( exportClassFullName != null ) ? exportClassFullName : t . getClass ( ) . getSimpleName ( ) + exportClassEnding ; }
Build XML list tag determined by fullname status and ending class phrase
8,042
private HashMap < Class , String > buildDefaultDataTypeMap ( ) { return new HashMap < Class , String > ( ) { { put ( boolean . class , "BOOLEAN" ) ; put ( Boolean . class , "BOOLEAN" ) ; put ( byte . class , "BYTE" ) ; put ( Byte . class , "BYTE" ) ; put ( short . class , "INT" ) ; put ( Short . class , "INT" ) ; put (...
Build default data types
8,043
private String buildCreateTableQuery ( final IClassContainer container , final String primaryKeyField ) { final StringBuilder builder = new StringBuilder ( "CREATE TABLE IF NOT EXISTS " ) . append ( container . getExportClassName ( ) . toLowerCase ( ) ) . append ( "(\n" ) ; final String resultValues = container . getFo...
Create String of Create Table Query
8,044
private String buildInsertNameTypeQuery ( final String finalFieldName , final IClassContainer container ) { final Class < ? > exportFieldType = container . getField ( finalFieldName ) . getType ( ) ; switch ( container . getContainer ( finalFieldName ) . getType ( ) ) { case ARRAY : case COLLECTION : final Class < ? > ...
Creates String of Create Table Insert Quert
8,045
private < T > String buildInsertQuery ( final T t , final IClassContainer container ) { final List < ExportContainer > exportContainers = extractExportContainers ( t , container ) ; final StringBuilder builder = new StringBuilder ( "INSERT INTO " ) . append ( container . getExportClassName ( ) . toLowerCase ( ) ) . app...
Build insert query part with values
8,046
private < T > String format ( final T t , final IClassContainer container ) { final List < ExportContainer > exportContainers = extractExportContainers ( t , container ) ; final String resultValues = exportContainers . stream ( ) . map ( c -> convertFieldValue ( container . getField ( c . getExportName ( ) ) , c ) ) . ...
Creates insert query field name
8,047
private boolean isTypeTimestampConvertible ( final Field field ) { return dataTypes . entrySet ( ) . stream ( ) . anyMatch ( e -> e . getValue ( ) . equals ( "TIMESTAMP" ) && e . getKey ( ) . equals ( field . getType ( ) ) ) ; }
Check data types for field class compatibility with Timestamp class
8,048
private String convertFieldValue ( final Field field , final ExportContainer container ) { final boolean isArray2D = ( container . getType ( ) == FieldContainer . Type . ARRAY_2D ) ; if ( field . getType ( ) . equals ( String . class ) ) { return wrapWithComma ( container . getExportValue ( ) ) ; } else if ( isTypeTime...
Convert container value to Sql specific value type
8,049
private Timestamp convertFieldValueToTimestamp ( final Field field , final ExportContainer exportContainer ) { if ( field . getType ( ) . equals ( LocalDateTime . class ) ) { return convertToTimestamp ( parseDateTime ( exportContainer . getExportValue ( ) ) ) ; } else if ( field . getType ( ) . equals ( LocalDate . cla...
Convert container export value to timestamp value type
8,050
public final List < DiscreteVariable > getDiscreteVariables ( ) { List < DiscreteVariable > discreteVars = new ArrayList < DiscreteVariable > ( ) ; for ( int i = 0 ; i < vars . length ; i ++ ) { if ( vars [ i ] instanceof DiscreteVariable ) { discreteVars . add ( ( DiscreteVariable ) vars [ i ] ) ; } } return discreteV...
Get the discrete variables in this map ordered by variable index .
8,051
private final void checkCompatibility ( VariableNumMap other ) { int i = 0 , j = 0 ; int [ ] otherNums = other . nums ; String [ ] otherNames = other . names ; Variable [ ] otherVars = other . vars ; while ( i < nums . length && j < otherNums . length ) { if ( nums [ i ] < otherNums [ j ] ) { i ++ ; } else if ( nums [ ...
Ensures that all variable numbers which are shared between other and this are mapped to the same variables .
8,052
public Assignment outcomeToAssignment ( Object [ ] outcome ) { Preconditions . checkArgument ( outcome . length == nums . length , "outcome %s cannot be assigned to %s (wrong number of values)" , outcome , this ) ; return Assignment . fromSortedArrays ( nums , outcome ) ; }
Get the assignment corresponding to a particular setting of the variables in this factor .
8,053
public static VariableNumMap unionAll ( Collection < VariableNumMap > varNumMaps ) { VariableNumMap curMap = EMPTY ; for ( VariableNumMap varNumMap : varNumMaps ) { curMap = curMap . union ( varNumMap ) ; } return curMap ; }
Returns the union of all of the passed - in maps which may not contain conflicting mappings for any variable number .
8,054
public static Credentials getUserByEmail ( DAO serverDao , String email ) throws DAO . DAOException { Query query = new QueryBuilder ( ) . select ( ) . from ( Credentials . class ) . where ( Credentials . EMAIL_KEY , OPERAND . EQ , email ) . build ( ) ; TransientObject to = ( TransientObject ) ObjectUtils . get1stOrNul...
Convience method to do a Credentials query against an email address
8,055
public static Credentials getUserById ( DAO serverDao , String userId ) throws DAO . DAOException { Query query = new QueryBuilder ( ) . select ( ) . from ( Credentials . class ) . where ( Credentials . OWNER_ID_KEY , OPERAND . EQ , userId ) . build ( ) ; TransientObject to = ( TransientObject ) ObjectUtils . get1stOrN...
Convience method to do a Credentials query against an user id .
8,056
private static String getSalt ( byte [ ] value ) { byte [ ] salt = new byte [ Generate . SALT_BYTES ] ; System . arraycopy ( value , 0 , salt , 0 , salt . length ) ; return ByteArray . toBase64 ( salt ) ; }
Retrieves the salt from the given value .
8,057
private static byte [ ] getHash ( byte [ ] value ) { byte [ ] hash = new byte [ value . length - Generate . SALT_BYTES ] ; System . arraycopy ( value , Generate . SALT_BYTES , hash , 0 , hash . length ) ; return hash ; }
Retrieves the hash from the given value .
8,058
public SufficientStatistics getNewSufficientStatistics ( ) { List < SufficientStatistics > lexiconParameterList = Lists . newArrayList ( ) ; List < String > lexiconParameterNames = Lists . newArrayList ( ) ; for ( int i = 0 ; i < lexiconFamilies . size ( ) ; i ++ ) { ParametricCcgLexicon lexiconFamily = lexiconFamilies...
Gets a new all - zero parameter vector .
8,059
public static synchronized < BackendType extends Backend > BackendType init ( Config < BackendType > config ) { logger . debug ( "Initializing... " + config ) ; Guice . createInjector ( config . getModule ( ) ) ; return injector . getInstance ( config . getModuleType ( ) ) ; }
Initialization point for divide . Returns an instance of the Divide object . Only one instance may exist at a time .
8,060
public static Type getGenericType ( final Type type , final int paramNumber ) { try { final ParameterizedType parameterizedType = ( ( ParameterizedType ) type ) ; return ( parameterizedType . getActualTypeArguments ( ) . length < paramNumber ) ? Object . class : parameterizedType . getActualTypeArguments ( ) [ paramNum...
Extracts generic type
8,061
public static boolean areEquals ( final Class < ? > firstClass , final Class < ? > secondClass ) { final boolean isFirstShort = firstClass . isAssignableFrom ( Short . class ) ; final boolean isSecondShort = secondClass . isAssignableFrom ( Short . class ) ; if ( isFirstShort && isSecondShort || isFirstShort && secondC...
Check if objects have equals types even if they are primitive
8,062
public < T extends DAO > T insert ( DAO dao , boolean excludePrimaryKeys ) throws DatabaseException { ModelDef model = db . getModelMetaDataDefinition ( ) . getDefinition ( dao . getModelName ( ) ) ; if ( excludePrimaryKeys ) { dao . add_IgnoreColumn ( model . getPrimaryAttributes ( ) ) ; } return insertRecord ( dao , ...
The primary keys should have defaults on the database to make this work
8,063
public < T extends DAO > T insertNoChangeLog ( DAO dao , ModelDef model ) throws DatabaseException { DAO ret = db . insert ( dao , null , model , null ) ; Class < ? extends DAO > clazz = getDaoClass ( dao . getModelName ( ) ) ; return cast ( clazz , ret ) ; }
Insert the record without bothering changelog to avoid infinite method recursive calls when inserting changelogs into record_changelog table
8,064
public Fixture addObjects ( Object ... objectsToAdd ) { if ( 0 < objectsToAdd . length ) { Collections . addAll ( objects , objectsToAdd ) ; } return this ; }
Add entities to the current list of entities to load .
8,065
public String digest ( String message ) { try { Mac mac = Mac . getInstance ( algorithm ) ; SecretKeySpec macKey = new SecretKeySpec ( key , algorithm ) ; mac . init ( macKey ) ; byte [ ] digest = mac . doFinal ( ByteArray . fromString ( message ) ) ; return ByteArray . toHex ( digest ) ; } catch ( NoSuchAlgorithmExcep...
Computes an HMAC for the given message using the key passed to the constructor .
8,066
public void reweightRootEntries ( CcgChart chart ) { int spanStart = 0 ; int spanEnd = chart . size ( ) - 1 ; int numChartEntries = chart . getNumChartEntriesForSpan ( spanStart , spanEnd ) ; ChartEntry [ ] entries = CcgBeamSearchChart . copyChartEntryArray ( chart . getChartEntriesForSpan ( spanStart , spanEnd ) , num...
Updates entries in the beam for the root node with a factor for the root syntactic category and any unary rules .
8,067
public < B extends BackendObject > Observable < Void > send ( final Collection < B > objects ) { return getWebService ( ) . save ( isLoggedIn ( ) , objects ) . subscribeOn ( config . subscribeOn ( ) ) . observeOn ( config . observeOn ( ) ) ; }
Function used to save objects on remote server .
8,068
public < B extends BackendObject > Observable < Collection < B > > get ( final Class < B > type , final Collection < String > objects ) { return Observable . create ( new Observable . OnSubscribe < Collection < B > > ( ) { public void call ( Subscriber < ? super Collection < B > > observer ) { try { observer . onNext (...
Function used to return specific objects corrosponding to the object keys provided .
8,069
public < B extends BackendObject > Observable < Integer > count ( final Class < B > type ) { return getWebService ( ) . count ( isLoggedIn ( ) , Query . safeTable ( type ) ) . subscribeOn ( config . subscribeOn ( ) ) . observeOn ( config . observeOn ( ) ) ; }
Functin used to perform a count query against remote sever for specifed type .
8,070
public static Set < HeadedSyntacticCategory > getSyntacticCategoryClosure ( Collection < HeadedSyntacticCategory > syntacticCategories ) { Set < String > featureValues = Sets . newHashSet ( ) ; for ( HeadedSyntacticCategory cat : syntacticCategories ) { getAllFeatureValues ( cat . getSyntax ( ) , featureValues ) ; } Qu...
Gets the closure of a set of syntactic categories under function application and feature assignment .
8,071
public static DiscreteFactor buildUnrestrictedBinaryDistribution ( DiscreteVariable syntaxType , Iterable < CcgBinaryRule > rules , boolean allowComposition ) { List < HeadedSyntacticCategory > allCategories = syntaxType . getValuesWithCast ( HeadedSyntacticCategory . class ) ; Set < List < Object > > validOutcomes = S...
Constructs a distribution over binary combination rules for CCG given a set of syntactic categories . This method compiles out all of the possible ways to combine two adjacent CCG categories using function application composition and any other binary rules .
8,072
private LinkedList < Class > getClassesToDelete ( ) { LinkedHashSet < Class > classesToDelete = new LinkedHashSet < Class > ( ) ; for ( Object object : getObjects ( ) ) { classesToDelete . add ( object . getClass ( ) ) ; } return new LinkedList < Class > ( classesToDelete ) ; }
Returns the list of mapping classes representing the tables to truncate .
8,073
public static SparseTensor diagonal ( int [ ] dimensionNumbers , int [ ] dimensionSizes , double value ) { int minDimensionSize = Ints . min ( dimensionSizes ) ; double [ ] values = new double [ minDimensionSize ] ; Arrays . fill ( values , value ) ; return diagonal ( dimensionNumbers , dimensionSizes , values ) ; }
Creates a tensor whose only non - zero entries are on its main diagonal .
8,074
public static CcgCategory fromSyntaxLf ( HeadedSyntacticCategory cat , Expression2 lf ) { String head = lf . toString ( ) ; head = head . replaceAll ( " " , "_" ) ; List < String > subjects = Lists . newArrayList ( ) ; List < Integer > argumentNums = Lists . newArrayList ( ) ; List < Integer > objects = Lists . newArra...
Generates a CCG category with head and dependency information automatically populated from the syntactic category and logical form . The logical form itself is used as the semantic head of the returned category .
8,075
public List < String > getSemanticHeads ( ) { int headSemanticVariable = syntax . getHeadVariable ( ) ; int [ ] allSemanticVariables = getSemanticVariables ( ) ; for ( int i = 0 ; i < allSemanticVariables . length ; i ++ ) { if ( allSemanticVariables [ i ] == headSemanticVariable ) { return Lists . newArrayList ( varia...
The semantic head of this category i . e . the assignment to the semantic variable at the root of the syntactic tree .
8,076
public Combinator . Type getDerivingCombinatorType ( ) { if ( combinator == null ) { return Combinator . Type . OTHER ; } else { return combinator . getType ( ) ; } }
Gets the type of the combinator used to produce this chart entry .
8,077
public SparseTensor getOldKeyIndicatorTensor ( ) { double [ ] values = new double [ oldKeyNums . length ] ; Arrays . fill ( values , 1.0 ) ; return SparseTensor . fromUnorderedKeyValues ( oldTensor . getDimensionNumbers ( ) , oldTensor . getDimensionSizes ( ) , oldKeyNums , values ) ; }
Gets a tensor of indicator variables for the old key values in this . The returned tensor has value 1 for all keys in this and 0 for all other keys .
8,078
public static SExpression readProgram ( List < String > filenames , IndexedList < String > symbolTable ) { StringBuilder programBuilder = new StringBuilder ( ) ; programBuilder . append ( "(begin " ) ; for ( String filename : filenames ) { for ( String line : IoUtils . readLines ( filename ) ) { line = line . replaceAl...
Reads a program from a list of files . Lines starting with any amount of whitespace followed by ; are ignored as comments .
8,079
public static boolean hasRecords ( String hostName , String dnsType ) throws DNSLookupException { return DNSLookup . doLookup ( hostName , dnsType ) > 0 ; }
Checks if a host name has a valid record .
8,080
public static int doLookup ( String hostName , String dnsType ) throws DNSLookupException { hostName = UniPunyCode . toPunycodeIfPossible ( hostName ) ; Hashtable < String , String > env = new Hashtable < String , String > ( ) ; env . put ( "java.naming.factory.initial" , "com.sun.jndi.dns.DnsContextFactory" ) ; DirCon...
Counts the number of records found for hostname and the specific type . Outputs 0 if no record is found or - 1 if the hostname is unknown invalid!
8,081
public static void shutdown ( ) { if ( MetricsManager . executorService != null ) { MetricsManager . executorService . shutdown ( ) ; MetricsManager . executorService = null ; } if ( MetricsManager . instance != null ) { MetricsManager . instance = null ; MetricsManager . poolManager . shutdown ( ) ; MetricsManager . p...
Shutdown MetricsManager clean up resources This method is not thread - safe only use it to clean up resources when your application is shutting down .
8,082
public static MetricsLogger getMetricsLogger ( final String dimensions ) { if ( MetricsManager . instance != null ) { final Map < String , String > dimensionsMap = DimensionsUtils . parseDimensions ( dimensions ) ; if ( ! dimensionsMap . isEmpty ( ) ) { dimensionsMap . put ( "service" , MetricsManager . instance . serv...
Get MetricsLogger to start collecting metrics . MetricsLogger can be used to collect Counter Timer or Recorder
8,083
public static void flushAll ( long now ) { if ( MetricsManager . instance != null ) { MetricsManager . instance . metricsLoggers . values ( ) . forEach ( MetricsManager :: flushMetricsLogger ) ; flushToServer ( now ) ; } }
Flush all metrics which have been collected so far by all MetricsLoggers . Metrics can also be flushed by each MetricsLogger individually .
8,084
static void flushToServer ( long now ) { LOG . debug ( "Flush to BeeInstant Server" ) ; Collection < String > readyToSubmit = new ArrayList < > ( ) ; metricsQueue . drainTo ( readyToSubmit ) ; StringBuilder builder = new StringBuilder ( ) ; readyToSubmit . forEach ( string -> { builder . append ( string ) ; builder . a...
Flush metrics to BeeInstant Server
8,085
static void reportError ( final String errorMessage ) { if ( MetricsManager . instance != null ) { MetricsManager . rootMetricsLogger . incCounter ( METRIC_ERRORS , 1 ) ; } LOG . error ( errorMessage ) ; }
Report errors during metric data collecting process . Report in two forms a host level metric which counts number of errors and a log line with message for each error . Will be used by MetricsLogger to report errors .
8,086
static void flushMetricsLogger ( final MetricsLogger metricsLogger ) { metricsLogger . flushToString ( MetricsManager :: queue ) ; MetricsManager . rootMetricsLogger . flushToString ( MetricsManager :: queue ) ; }
Flush metrics collected by MetricsLogger to log files . Will be used by MetricsLogger to flush itself .
8,087
public static < A > Mapper < A , A > identity ( ) { return new Mapper < A , A > ( ) { public A map ( A item ) { return item ; } } ; }
Gets the identity mapper .
8,088
public KeyPair unwrapKeyPair ( String wrappedPrivateKey , String encodedPublicKey ) { PrivateKey privateKey = unwrapPrivateKey ( wrappedPrivateKey ) ; PublicKey publicKey = decodePublicKey ( encodedPublicKey ) ; return new KeyPair ( publicKey , privateKey ) ; }
Convenience method to unwrap a public - private key pain in a single call .
8,089
public static final DimensionSpec mergeDimensions ( int [ ] firstDimensionNums , int [ ] firstDimensionSizes , int [ ] secondDimensionNums , int [ ] secondDimensionSizes ) { SortedSet < Integer > first = Sets . newTreeSet ( Ints . asList ( firstDimensionNums ) ) ; SortedSet < Integer > second = Sets . newTreeSet ( Ints...
Merges the given sets of dimensions verifying that any dimensions in both sets have the same size .
8,090
public T next ( ) { if ( ! hasNext ( ) ) { throw new NoSuchElementException ( toString ( ) + " ended" ) ; } current = iterator . next ( ) ; return current ( ) ; }
Returns the next value in list .
8,091
< T > IClassContainer buildClassContainer ( final List < T > list ) { return ( BasicCollectionUtils . isNotEmpty ( list ) ) ? buildClassContainer ( list . get ( 0 ) ) : null ; }
Build class container with export entity parameters
8,092
IWriter buildWriter ( final IClassContainer classContainer ) { try { return new BufferedFileWriter ( classContainer . getExportClassName ( ) , path , format . getExtension ( ) ) ; } catch ( IOException e ) { logger . warning ( e . getMessage ( ) ) ; return null ; } }
Build buffered writer for export
8,093
< T > List < ExportContainer > extractExportContainers ( final T t , final IClassContainer classContainer ) { final List < ExportContainer > exports = new ArrayList < > ( ) ; classContainer . getFormatSupported ( format ) . forEach ( ( k , v ) -> { try { k . setAccessible ( true ) ; final String exportFieldName = v . g...
Generates class export field - value map
8,094
< T > boolean isExportEntityInvalid ( final List < T > t ) { return ( BasicCollectionUtils . isEmpty ( t ) || isExportEntityInvalid ( t . get ( 0 ) ) ) ; }
Validate export arguments
8,095
public static ExpressionSimplifier lambdaCalculus ( ) { List < ExpressionReplacementRule > rules = Lists . newArrayList ( ) ; rules . add ( new LambdaApplicationReplacementRule ( ) ) ; rules . add ( new VariableCanonicalizationReplacementRule ( ) ) ; return new ExpressionSimplifier ( rules ) ; }
Default simplifier for lambda calculus expressions . This simplifier performs beta reduction of lambda expressions and canonicalizes variable names .
8,096
public static boolean is_email ( String email , boolean checkDNS ) throws DNSLookupException { return ( is_email_verbose ( email , checkDNS ) . getState ( ) == GeneralState . OK ) ; }
Checks the syntax of an email address .
8,097
private static String replaceCharAt ( String s , int pos , char c ) { return s . substring ( 0 , pos ) + c + s . substring ( pos + 1 ) ; }
Replaces a char in a String
8,098
public void updateOutsideEntry ( int spanStart , int spanEnd , double [ ] values , Factor factor , VariableNumMap var ) { if ( sumProduct ) { updateEntrySumProduct ( outsideChart [ spanStart ] [ spanEnd ] , values , factor . coerceToDiscrete ( ) . getWeights ( ) , var . getOnlyVariableNum ( ) ) ; } else { updateEntryMa...
Update an entry of the outside chart with a new production . Depending on the type of the chart this performs either a sum or max over productions of the same type in the same entry .
8,099
public Factor getInsideEntries ( int spanStart , int spanEnd ) { Tensor entries = new DenseTensor ( parentVar . getVariableNumsArray ( ) , parentVar . getVariableSizes ( ) , insideChart [ spanStart ] [ spanEnd ] ) ; return new TableFactor ( parentVar , entries ) ; }
Get the inside unnormalized probabilities over productions at a particular span in the tree .