idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
7,500
public void registerClass ( Class < ? > clazz ) { registeredClasses . add ( clazz ) ; for ( Field field : clazz . getFields ( ) ) { if ( field . isAnnotationPresent ( Opt . class ) ) { int mod = field . getModifiers ( ) ; if ( ! Modifier . isPublic ( mod ) ) { throw new IllegalStateException ( "@" + Opt . class . getName ( ) + " on non-public field: " + field ) ; } if ( Modifier . isFinal ( mod ) ) { throw new IllegalStateException ( "@" + Opt . class . getName ( ) + " on final field: " + field ) ; } if ( Modifier . isAbstract ( mod ) ) { throw new IllegalStateException ( "@" + Opt . class . getName ( ) + " on abstract field: " + field ) ; } Opt opt = field . getAnnotation ( Opt . class ) ; String name = getName ( opt , field ) ; if ( ! names . add ( name ) ) { throw new RuntimeException ( "Multiple options have the same name: --" + name ) ; } String shortName = null ; if ( createShortNames ) { shortName = getAndAddUniqueShortName ( name ) ; } Option apacheOpt = new Option ( shortName , name , opt . hasArg ( ) , opt . description ( ) ) ; apacheOpt . setRequired ( opt . required ( ) ) ; options . addOption ( apacheOpt ) ; optionFieldMap . put ( apacheOpt , field ) ; if ( ! field . getType ( ) . equals ( Boolean . TYPE ) && ! opt . hasArg ( ) ) { throw new RuntimeException ( "Only booleans can not have arguments." ) ; } } } }
Registers all the
7,501
private static String getName ( Opt option , Field field ) { if ( option . name ( ) . equals ( Opt . DEFAULT_STRING ) ) { return field . getName ( ) ; } else { return option . name ( ) ; } }
Gets the name specified in
7,502
public void printUsage ( ) { String name = mainClass == null ? "<MainClass>" : mainClass . getName ( ) ; String usage = "java " + name + " [OPTIONS]" ; final HelpFormatter formatter = new HelpFormatter ( ) ; formatter . setWidth ( 120 ) ; formatter . printHelp ( usage , options , true ) ; }
Prints the usage of the main class for this ArgParser .
7,503
public static int safeStrToInt ( String str ) { if ( sciInt . matcher ( str ) . find ( ) ) { return SafeCast . safeDoubleToInt ( Double . parseDouble ( str . toUpperCase ( ) ) ) ; } else { return Integer . parseInt ( str ) ; } }
Correctly casts 1e + 06 to 1000000 .
7,504
@ SuppressWarnings ( { "unchecked" , "rawtypes" } ) public List serialize ( ClassUnwrapper unwrapper , Object agent ) { List variables = new ArrayList < > ( ) ; List < GetterMethodCover > methods = unwrapper . getMethods ( ) ; for ( GetterMethodCover method : methods ) { Object value = method . invoke ( agent ) ; if ( value == null ) continue ; variables . add ( newVariable ( method . getKey ( ) , getValue ( method , value ) , method . isHidden ( ) ) ) ; } return variables ; }
Serialize java object
7,505
@ SuppressWarnings ( "rawtypes" ) protected Object getValue ( GetterMethodCover method , Object value ) { if ( method . isByte ( ) ) { value = ( ( Byte ) value ) . intValue ( ) ; } else if ( method . isChar ( ) ) { value = ( int ) ( ( Character ) value ) . charValue ( ) ; } else if ( method . isFloat ( ) ) { value = ( ( Float ) value ) . doubleValue ( ) ; } else if ( method . isLong ( ) ) { value = ( ( Long ) value ) . doubleValue ( ) ; } else if ( method . isShort ( ) ) { value = ( ( Short ) value ) . intValue ( ) ; } else if ( method . isObject ( ) ) { value = parseObject ( method , value ) ; } else if ( method . isObjectArray ( ) ) { value = parseArray ( method , value ) ; } else if ( method . isArrayObjectCollection ( ) ) { return parseArrayObjectCollection ( method , ( Collection ) value ) ; } else if ( method . isObjectCollection ( ) ) { return parseObjectCollection ( method , ( Collection ) value ) ; } else if ( method . isArrayCollection ( ) ) { return parseArrayCollection ( method , ( Collection ) value ) ; } else if ( method . isArray ( ) || method . isColection ( ) ) { return transformSimpleValue ( value ) ; } return value ; }
Call getter method and get value
7,506
private void updateBuddyProperties ( BuddyProperties buddyProperties , ApiBuddyProperties apiBuddyProperties ) { apiBuddyProperties . setInited ( buddyProperties . isInited ( ) ) ; apiBuddyProperties . setNickName ( buddyProperties . getNickName ( ) ) ; apiBuddyProperties . setOnline ( buddyProperties . isOnline ( ) ) ; apiBuddyProperties . setState ( buddyProperties . getState ( ) ) ; }
Update buddy properties of user
7,507
void apply ( final LambdaUnaryOpDouble lambda ) { params . apply ( new FnIntDoubleToDouble ( ) { public double call ( int idx , double val ) { return lambda . call ( val ) ; } } ) ; }
ONLY FOR TESTING .
7,508
ImmutableCell < V > validateCounts ( int rowCount , int columnCount ) { if ( row >= rowCount || column >= columnCount ) { throw new IndexOutOfBoundsException ( "Invalid row-column: " + row + "," + column + " for grid " + rowCount + "x" + columnCount ) ; } return this ; }
Validates this cell against the specified counts .
7,509
public static double approxSumPaths ( WeightedIntDiGraph g , RealVector startWeights , RealVector endWeights , Iterator < DiEdge > seq , DoubleConsumer c ) { DefaultDict < DiEdge , Double > prefixWeightsEndingAt = new DefaultDict < DiEdge , Double > ( Void -> 0.0 ) ; RealVector currentSums = startWeights . copy ( ) ; double currentTotal = currentSums . dotProduct ( endWeights ) ; if ( c != null ) { c . accept ( currentTotal ) ; } for ( DiEdge e : ScheduleUtils . iterable ( seq ) ) { int s = e . get1 ( ) ; int t = e . get2 ( ) ; double oldTargetSum = currentSums . getEntry ( t ) ; double oldEdgeSum = prefixWeightsEndingAt . get ( e ) ; double newEdgeSum = currentSums . getEntry ( s ) * g . getWeight ( e ) ; double newTargetSum = oldTargetSum + ( newEdgeSum - oldEdgeSum ) ; double newTotal = currentTotal + ( newTargetSum - oldTargetSum ) * endWeights . getEntry ( t ) ; prefixWeightsEndingAt . put ( e , newEdgeSum ) ; currentSums . setEntry ( t , newTargetSum ) ; currentTotal = newTotal ; if ( c != null ) { c . accept ( currentTotal ) ; } } return currentTotal ; }
Computes the approximate sum of paths through the graph where the weight of each path is the product of edge weights along the path ;
7,510
public static int hash32 ( final long data , int seed ) { final int m = 0x5bd1e995 ; final int r = 24 ; final int length = 8 ; int h = seed ^ length ; for ( int i = 0 ; i < 2 ; i ++ ) { int k = ( i == 0 ) ? ( int ) ( data & 0xffffffffL ) : ( int ) ( ( data >>> 32 ) & 0xffffffffL ) ; k *= m ; k ^= k >>> r ; k *= m ; h *= m ; h ^= k ; } h ^= h >>> 13 ; h *= m ; h ^= h >>> 15 ; return h ; }
My conversion of MurmurHash to take a long as input .
7,511
private void ensureVarTensor ( ) { if ( vt == null ) { log . warn ( "Generating VarTensor for a GlobalFactor. This should only ever be done during testing." ) ; vt = BruteForceInferencer . safeNewVarTensor ( s , f ) ; if ( fillVal != null ) { vt . fill ( fillVal ) ; } } }
Ensures that the VarTensor is loaded .
7,512
protected Object checkUserAgent ( ServerUserHandlerClass handler , ApiUser userAgent ) { if ( handler . getUserClass ( ) . isAssignableFrom ( userAgent . getClass ( ) ) ) return userAgent ; return UserAgentUtil . getGameUser ( userAgent , handler . getUserClass ( ) ) ; }
Check whether context of user agent is application or game
7,513
public String getLabel ( ) { if ( label == null ) { StringBuilder label = new StringBuilder ( ) ; label . append ( headNode . getLabel ( ) ) ; label . append ( "<--" ) ; for ( Hypernode tailNode : tailNodes ) { label . append ( tailNode . getLabel ( ) ) ; label . append ( "," ) ; } if ( tailNodes . length > 0 ) { label . deleteCharAt ( label . length ( ) - 1 ) ; } return label . toString ( ) ; } return label ; }
Gets a name for this edge .
7,514
public static ApiUser getUserAgent ( User sfsUser ) { Object userAgent = sfsUser . getProperty ( APIKey . USER ) ; if ( userAgent == null ) throw new RuntimeException ( "Can not get user agent" ) ; return ( ApiUser ) userAgent ; }
Get user agent object mapped to smartfox user object
7,515
public static ApiRoom getRoomAgent ( Room sfsRoom ) { Object roomAgent = sfsRoom . getProperty ( APIKey . ROOM ) ; if ( roomAgent == null ) throw new RuntimeException ( "Can not get user agent" ) ; return ( ApiRoom ) roomAgent ; }
Get room agent object mapped to smartfox room object
7,516
public static < X , Y > Map < X , Y > zip ( List < X > keys , List < Y > values ) { if ( keys . size ( ) != values . size ( ) ) { throw new IllegalArgumentException ( "Lengths are not equal" ) ; } Map < X , Y > map = new HashMap < > ( keys . size ( ) ) ; for ( int i = 0 ; i < keys . size ( ) ; i ++ ) { map . put ( keys . get ( i ) , values . get ( i ) ) ; } return map ; }
Like Python s zip this creates a map by zipping together the key and values lists .
7,517
private void extractAllFeats ( FgExampleList data , FactorTemplateList templates ) { IFgModel counts = new IFgModel ( ) { public void addAfterScaling ( FeatureVector fv , double multiplier ) { } public void add ( int feat , double addend ) { } } ; for ( int i = 0 ; i < data . size ( ) ; i ++ ) { if ( i % 1000 == 0 ) { log . debug ( "Processing example: " + i ) ; } LFgExample ex = data . get ( i ) ; FactorGraph fgLat = MarginalLogLikelihood . getFgLat ( ex . getFactorGraph ( ) , ex . getGoldConfig ( ) ) ; NoOpInferencer inferencer = new NoOpInferencer ( ex . getFactorGraph ( ) ) ; for ( int a = 0 ; a < ex . getFactorGraph ( ) . getNumFactors ( ) ; a ++ ) { Factor f = fgLat . getFactor ( a ) ; if ( f instanceof ObsFeatureCarrier && f instanceof TemplateFactor ) { int t = templates . getTemplateId ( ( TemplateFactor ) f ) ; if ( t != - 1 ) { ( ( ObsFeatureCarrier ) f ) . getObsFeatures ( ) ; } } else { f = ex . getFactorGraph ( ) . getFactor ( a ) ; if ( f instanceof GlobalFactor ) { ( ( GlobalFactor ) f ) . addExpectedPartials ( counts , 0 , inferencer , a ) ; } else { VarTensor marg = inferencer . getMarginalsForFactorId ( a ) ; f . addExpectedPartials ( counts , marg , 0 ) ; } } } } }
Loops through all examples to create the features thereby ensuring that the FTS are initialized .
7,518
private IntIntDenseVector [ ] [ ] countFeatures ( FgExampleList data , FactorTemplateList templates ) { IntIntDenseVector [ ] [ ] counts = new IntIntDenseVector [ numTemplates ] [ ] ; for ( int t = 0 ; t < numTemplates ; t ++ ) { FactorTemplate template = templates . get ( t ) ; int numConfigs = template . getNumConfigs ( ) ; int numFeats = template . getAlphabet ( ) . size ( ) ; counts [ t ] = new IntIntDenseVector [ numConfigs ] ; for ( int c = 0 ; c < numConfigs ; c ++ ) { counts [ t ] [ c ] = new IntIntDenseVector ( numFeats ) ; } } for ( int i = 0 ; i < data . size ( ) ; i ++ ) { LFgExample ex = data . get ( i ) ; FactorGraph fg = ex . getFactorGraph ( ) ; for ( int a = 0 ; a < ex . getFactorGraph ( ) . getNumFactors ( ) ; a ++ ) { Factor f = fg . getFactor ( a ) ; if ( f instanceof ObsFeatureCarrier && f instanceof TemplateFactor ) { int t = templates . getTemplateId ( ( TemplateFactor ) f ) ; if ( t != - 1 ) { FeatureVector fv = ( ( ObsFeatureCarrier ) f ) . getObsFeatures ( ) ; VarConfig predVc = ex . getGoldConfigPred ( a ) ; IntIter iter = IndexForVc . getConfigIter ( ex . getFactorGraph ( ) . getFactor ( a ) . getVars ( ) , predVc ) ; while ( iter . hasNext ( ) ) { int config = iter . next ( ) ; for ( IntDoubleEntry entry : fv ) { counts [ t ] [ config ] . add ( entry . index ( ) , 1 ) ; } } } } } } return counts ; }
Counts the number of times each feature appears in the gold training data .
7,519
protected void notifyToHandler ( ServerHandlerClass handler , ApiZone zone , ApiBuddyImpl buddy ) { ReflectMethodUtil . invokeHandleMethod ( handler . getHandleMethod ( ) , handler . newInstance ( ) , context , zone , buddy ) ; }
Notify event to handler
7,520
private void checkIndices ( int ... indices ) { if ( indices . length != dims . length ) { throw new IllegalArgumentException ( String . format ( "Indices array is not the correct length. expected=%d actual=%d" , indices . length , dims . length ) ) ; } for ( int i = 0 ; i < indices . length ; i ++ ) { if ( indices [ i ] < 0 || dims [ i ] <= indices [ i ] ) { throw new IllegalArgumentException ( String . format ( "Indices array contains an index that is out of bounds: i=%d index=%d" , i , indices [ i ] ) ) ; } } }
Checks that the indices are valid .
7,521
public double [ ] getValuesAsNativeArray ( ) { double [ ] vs = new double [ this . size ( ) ] ; for ( int c = 0 ; c < vs . length ; c ++ ) { vs [ c ] = getValue ( c ) ; } return vs ; }
Gets a copy of the internal values as a native array .
7,522
public static VTensor combine ( VTensor t1 , VTensor t2 ) { checkSameDims ( t1 , t2 ) ; checkSameAlgebra ( t1 , t2 ) ; int [ ] dims3 = IntArrays . insertEntry ( t1 . getDims ( ) , 0 , 2 ) ; VTensor y = new VTensor ( t1 . s , dims3 ) ; y . addTensor ( t1 , 0 , 0 ) ; y . addTensor ( t2 , 0 , 1 ) ; return y ; }
Combines two identically sized tensors by adding an initial dimension of size 2 .
7,523
static int guessNumWords ( Beliefs b ) { int n = - 1 ; for ( int v = 0 ; v < b . varBeliefs . length ; v ++ ) { Var var = b . varBeliefs [ v ] . getVars ( ) . get ( 0 ) ; if ( var instanceof LinkVar ) { LinkVar link = ( LinkVar ) var ; int p = link . getParent ( ) ; int c = link . getChild ( ) ; n = Math . max ( n , Math . max ( p , c ) ) ; } } return n + 1 ; }
Gets the maximum index of a parent or child in a LinkVar plus one .
7,524
public Map getSingleInfoServiceByRep ( String sql , Map requestParamMap ) throws Exception { List placeList = new ArrayList ( ) ; sqlTemplateService ( sql , requestParamMap , placeList ) ; String realSql = sqlTemplateService ( sql , requestParamMap , placeList ) ; ; Map retMap = getInnerDao ( ) . querySingleObjJoinByCondition ( realSql , placeList . toArray ( ) ) ; CheckModelTypeUtil . addMetaCols ( retMap ) ; CheckModelTypeUtil . changeNoStrCols ( retMap ) ; return retMap ; }
add 20190430 by ning
7,525
private void setOutMsgs ( VarTensor outMsg , SpanVar span , double outMsgTrue , double outMsgFalse ) { Algebra s = outMsg . getAlgebra ( ) ; outMsg . setValue ( SpanVar . FALSE , s . fromLogProb ( outMsgFalse ) ) ; outMsg . setValue ( SpanVar . TRUE , s . fromLogProb ( outMsgTrue ) ) ; if ( log . isTraceEnabled ( ) ) { log . trace ( String . format ( "outMsgTrue: %s = %.2f" , span . getName ( ) , outMsg . getValue ( LinkVar . TRUE ) ) ) ; log . trace ( String . format ( "outMsgFalse: %s = %.2f" , span . getName ( ) , outMsg . getValue ( LinkVar . FALSE ) ) ) ; } assert ! outMsg . containsBadValues ( ) : "message = " + outMsg ; }
Sets the outgoing messages .
7,526
private static boolean [ ] [ ] getChart ( int n , VarConfig vc ) { boolean [ ] [ ] chart = new boolean [ n ] [ n + 1 ] ; int count = 0 ; for ( Var v : vc . getVars ( ) ) { SpanVar span = ( SpanVar ) v ; chart [ span . getStart ( ) ] [ span . getEnd ( ) ] = ( vc . getState ( span ) == SpanVar . TRUE ) ; count ++ ; } if ( count != ( n * ( n + 1 ) / 2 ) ) { return null ; } return chart ; }
Creates a boolean chart representing the set of spans which are on or null if the number of span variables in the assignment is invalid .
7,527
private static boolean isTree ( int n , boolean [ ] [ ] chart ) { if ( ! chart [ 0 ] [ n ] ) { return false ; } for ( int width = 1 ; width <= n ; width ++ ) { for ( int start = 0 ; start <= n - width ; start ++ ) { int end = start + width ; if ( width == 1 ) { if ( ! chart [ start ] [ end ] ) { return false ; } } else { if ( chart [ start ] [ end ] ) { int childPairCount = 0 ; for ( int mid = start + 1 ; mid <= end - 1 ; mid ++ ) { if ( chart [ start ] [ mid ] && chart [ mid ] [ end ] ) { childPairCount ++ ; } } if ( childPairCount != 1 ) { return false ; } } } } } return true ; }
Returns true if the boolean chart represents a set of spans that form a valid constituency tree false otherwise .
7,528
public static IndexForVc getConfigIter ( VarSet indexVars , VarConfig config ) { int fixedConfigContrib = getConfigIndex ( indexVars , config ) ; VarSet forVars = new VarSet ( indexVars ) ; forVars . removeAll ( config . getVars ( ) ) ; return new IndexForVc ( indexVars , forVars , fixedConfigContrib ) ; }
Iterates over all the configurations of indexVars where the subset of variables in config have been clamped to their given values . The iterator returns the configuration index of variables in indexVars .
7,529
public static int [ ] getConfigArr ( VarSet vars , VarConfig config ) { IntArrayList a = new IntArrayList ( config . getVars ( ) . calcNumConfigs ( ) ) ; IntIter iter = getConfigIter ( vars , config ) ; while ( iter . hasNext ( ) ) { a . add ( iter . next ( ) ) ; } return a . toNativeArray ( ) ; }
Gets an array version of the configuration iterator .
7,530
public static int getConfigIndex ( VarSet vars , VarConfig config ) { int configIndex = 0 ; int numStatesProd = 1 ; for ( int v = vars . size ( ) - 1 ; v >= 0 ; v -- ) { Var var = vars . get ( v ) ; int state = config . getState ( var , 0 ) ; configIndex += state * numStatesProd ; numStatesProd *= var . getNumStates ( ) ; } return configIndex ; }
Gets the index of the configuration of the variables where all those in config have the specified value and all other variables in vars have the zero state .
7,531
public static int configIdToLibDaiIx ( int configId , VarSet vs ) { int [ ] indices = vs . getVarConfigAsArray ( configId ) ; int [ ] dims = vs . getDims ( ) ; return Tensor . ravelIndexMatlab ( indices , dims ) ; }
converts the internal pacaya index of a config on the varset into the libdai index corresponding to the same configuration
7,532
public PrivateKey get ( KeyStoreChooser keyStoreChooser , PrivateKeyChooserByAlias privateKeyChooserByAlias ) { CacheKey cacheKey = new CacheKey ( keyStoreChooser . getKeyStoreName ( ) , privateKeyChooserByAlias . getAlias ( ) ) ; PrivateKey retrievedPrivateKey = cache . get ( cacheKey ) ; if ( retrievedPrivateKey != null ) { return retrievedPrivateKey ; } KeyStore keyStore = keyStoreRegistry . get ( keyStoreChooser ) ; if ( keyStore != null ) { PrivateKeyFactoryBean factory = new PrivateKeyFactoryBean ( ) ; factory . setKeystore ( keyStore ) ; factory . setAlias ( privateKeyChooserByAlias . getAlias ( ) ) ; factory . setPassword ( privateKeyChooserByAlias . getPassword ( ) ) ; try { factory . afterPropertiesSet ( ) ; PrivateKey privateKey = ( PrivateKey ) factory . getObject ( ) ; if ( privateKey != null ) { cache . put ( cacheKey , privateKey ) ; } return privateKey ; } catch ( Exception e ) { throw new PrivateKeyException ( "error initializing private key factory bean" , e ) ; } } return null ; }
Returns the selected private key or null if not found .
7,533
public static int [ ] unravelIndex ( int configIx , int ... dims ) { int numConfigs = IntArrays . prod ( dims ) ; assert configIx < numConfigs ; int [ ] strides = getStrides ( dims ) ; return unravelIndexFromStrides ( configIx , strides ) ; }
Returns an integer array of the same length as dims that matches the configIx th configuration if enumerated configurations in order such that the leftmost dimension changes slowest
7,534
public static int [ ] unravelIndexMatlab ( int configIx , int ... dims ) { dims = dims . clone ( ) ; ArrayUtils . reverse ( dims ) ; int [ ] config = unravelIndex ( configIx , dims ) ; ArrayUtils . reverse ( config ) ; return config ; }
Returns an integer array of the same length as dims that matches the configIx th configuration if enumerated configurations in order such that the rightmost dimension is fastest
7,535
public static int [ ] unravelIndexFromStrides ( int configIx , int ... strides ) { int offset = 0 ; int [ ] config = new int [ strides . length ] ; for ( int i = 0 ; i < strides . length ; i ++ ) { int ix = ( configIx - offset ) / strides [ i ] ; config [ i ] = ix ; offset += ix * strides [ i ] ; } return config ; }
strides are given in order from left to right slowest to fastest
7,536
public double setValue ( int idx , double val ) { double prev = values [ idx ] ; values [ idx ] = val ; return prev ; }
Sets the value of the idx th entry .
7,537
public void add ( double addend ) { for ( int c = 0 ; c < this . values . length ; c ++ ) { addValue ( c , addend ) ; } }
Add the addend to each value .
7,538
public void multiply ( double val ) { for ( int c = 0 ; c < this . values . length ; c ++ ) { multiplyValue ( c , val ) ; } }
Scale each value by lambda .
7,539
public void divide ( double val ) { for ( int c = 0 ; c < this . values . length ; c ++ ) { divideValue ( c , val ) ; } }
Divide each value by lambda .
7,540
public Tensor select ( int dim , int idx ) { int [ ] yDims = IntArrays . removeEntry ( this . getDims ( ) , dim ) ; Tensor y = new Tensor ( s , yDims ) ; DimIter yIter = new DimIter ( y . getDims ( ) ) ; while ( yIter . hasNext ( ) ) { int [ ] yIdx = yIter . next ( ) ; int [ ] xIdx = IntArrays . insertEntry ( yIdx , dim , idx ) ; y . set ( yIdx , this . get ( xIdx ) ) ; } return y ; }
Selects a sub - tensor from this one . This can be though of as fixing a particular dimension to a given index .
7,541
public void addTensor ( Tensor addend , int dim , int idx ) { checkSameAlgebra ( this , addend ) ; DimIter yIter = new DimIter ( addend . getDims ( ) ) ; while ( yIter . hasNext ( ) ) { int [ ] yIdx = yIter . next ( ) ; int [ ] xIdx = IntArrays . insertEntry ( yIdx , dim , idx ) ; this . add ( xIdx , addend . get ( yIdx ) ) ; } }
Adds a smaller tensor to this one inserting it at a specified dimension and index . This can be thought of as selecting the sub - tensor of this tensor adding the smaller tensor to it .
7,542
public VarConfig getVarConfig ( int configIndex ) { int i ; int [ ] states = getVarConfigAsArray ( configIndex ) ; VarConfig config = new VarConfig ( ) ; i = 0 ; for ( Var var : this ) { config . put ( var , states [ i ++ ] ) ; } return config ; }
Gets the variable configuration corresponding to the given configuration index .
7,543
public void getVarConfigAsArray ( int configIndex , int [ ] putInto ) { if ( putInto . length != this . size ( ) ) throw new IllegalArgumentException ( ) ; int i = putInto . length - 1 ; for ( int v = this . size ( ) - 1 ; v >= 0 ; v -- ) { Var var = this . get ( v ) ; putInto [ i -- ] = configIndex % var . getNumStates ( ) ; configIndex /= var . getNumStates ( ) ; } }
this is the no - allocation version of the non - void method of the same name .
7,544
public int [ ] getDims ( ) { int [ ] dims = new int [ size ( ) ] ; for ( int i = 0 ; i < size ( ) ; i ++ ) { dims [ i ] = get ( i ) . getNumStates ( ) ; } return dims ; }
Returns an array holding the number of values the corresponding variables can take on
7,545
public static void runCommand ( String [ ] cmdArray , File logFile , File dir ) { Process proc = System . runProcess ( cmdArray , logFile , dir ) ; if ( proc . exitValue ( ) != 0 ) { throw new RuntimeException ( "Command failed with exit code " + proc . exitValue ( ) + ": " + System . cmdToString ( cmdArray ) + "\n" + QFiles . tail ( logFile ) ) ; } }
Checks the exit code and throws an Exception if the process failed .
7,546
public static Process runProcess ( String [ ] cmdArray , File logFile , File dir ) { try { ProcessBuilder pb = new ProcessBuilder ( cmdArray ) ; pb . redirectErrorStream ( true ) ; pb . directory ( dir ) ; Process proc = pb . start ( ) ; if ( logFile != null ) { InputStream inputStream = new BufferedInputStream ( proc . getInputStream ( ) ) ; BufferedOutputStream out = new BufferedOutputStream ( new FileOutputStream ( logFile ) ) ; int read = 0 ; byte [ ] bytes = new byte [ 1024 ] ; while ( ( read = inputStream . read ( bytes ) ) != - 1 ) { out . write ( bytes , 0 , read ) ; } inputStream . close ( ) ; out . flush ( ) ; out . close ( ) ; } proc . waitFor ( ) ; return proc ; } catch ( Exception e ) { String tail = "" ; try { tail = QFiles . tail ( logFile ) ; } catch ( Throwable t ) { } throw new RuntimeException ( "Exception thrown while trying to exec command " + System . cmdToString ( cmdArray ) + "\n" + tail , e ) ; } }
Returns the Process which contains the exit code .
7,547
private void forwardSendMessage ( int edge , int iter ) { double oldResidual = residuals [ edge ] ; residuals [ edge ] = smartResidual ( msgs [ edge ] , newMsgs [ edge ] , edge ) ; if ( oldResidual > prm . convergenceThreshold && residuals [ edge ] <= prm . convergenceThreshold ) { numConverged ++ ; } if ( oldResidual <= prm . convergenceThreshold && residuals [ edge ] > prm . convergenceThreshold ) { numConverged -- ; } if ( log . isTraceEnabled ( ) && iter > 0 ) { if ( msgs [ edge ] . getArgmaxConfigId ( ) != newMsgs [ edge ] . getArgmaxConfigId ( ) ) { oscillationCount . incrementAndGet ( ) ; } sendCount . incrementAndGet ( ) ; log . trace ( "Residual: {} {}" , fg . edgeToString ( edge ) , residuals [ edge ] ) ; } int child = bg . childE ( edge ) ; if ( ! bg . isT1T2 ( edge ) && bg . numNbsT1 ( child ) >= prm . minVarNbsForCache ) { varBeliefs [ child ] . elemDivBP ( msgs [ edge ] ) ; varBeliefs [ child ] . elemMultiply ( newMsgs [ edge ] ) ; assert ! varBeliefs [ child ] . containsBadValues ( ) : "varBeliefs[child] = " + varBeliefs [ child ] ; } else if ( bg . isT1T2 ( edge ) && bg . numNbsT2 ( child ) >= prm . minFacNbsForCache ) { Factor f = bg . t2E ( edge ) ; if ( ! ( f instanceof GlobalFactor ) ) { facBeliefs [ child ] . divBP ( msgs [ edge ] ) ; facBeliefs [ child ] . prod ( newMsgs [ edge ] ) ; assert ! facBeliefs [ child ] . containsBadValues ( ) : "facBeliefs[child] = " + facBeliefs [ child ] ; } } VarTensor oldMessage = msgs [ edge ] ; msgs [ edge ] = newMsgs [ edge ] ; newMsgs [ edge ] = oldMessage ; assert ! msgs [ edge ] . containsBadValues ( ) : "msgs[edge] = " + msgs [ edge ] ; if ( log . isTraceEnabled ( ) ) { log . trace ( "Message sent: {} {}" , fg . edgeToString ( edge ) , msgs [ edge ] ) ; } }
Sends the message that is currently pending for this edge . This just copies the message in the pending slot to the message slot for this edge .
7,548
private double smartResidual ( VarTensor message , VarTensor newMessage , int edge ) { return CachingBpSchedule . isConstantMsg ( edge , fg ) ? 0.0 : getResidual ( message , newMessage ) ; }
Returns the converged residual for constant messages and the actual residual otherwise .
7,549
private double getResidual ( VarTensor t1 , VarTensor t2 ) { assert s == t1 . getAlgebra ( ) && s == t2 . getAlgebra ( ) ; Tensor . checkEqualSize ( t1 , t2 ) ; Tensor . checkSameAlgebra ( t1 , t2 ) ; double residual = Double . NEGATIVE_INFINITY ; for ( int c = 0 ; c < t1 . size ( ) ; c ++ ) { double abs = Math . abs ( s . toLogProb ( t1 . get ( c ) ) - s . toLogProb ( t2 . get ( c ) ) ) ; if ( abs > residual ) { residual = abs ; } } return residual ; }
Gets the residual for a new message as the maximum error over all assignments .
7,550
private void calcProductAtVar ( int v , VarTensor prod , int excl1 , int excl2 ) { for ( int nb = 0 ; nb < bg . numNbsT1 ( v ) ; nb ++ ) { if ( nb == excl1 || nb == excl2 ) { continue ; } VarTensor nbMsg = msgs [ bg . opposingT1 ( v , nb ) ] ; prod . elemMultiply ( nbMsg ) ; } }
Computes the product of all messages being sent to a node optionally excluding messages sent from another node or two .
7,551
private VarTensor calcVarBeliefs ( Var var ) { VarTensor prod = new VarTensor ( s , new VarSet ( var ) , s . one ( ) ) ; calcProductAtVar ( var . getId ( ) , prod , - 1 , - 1 ) ; return prod ; }
Gets the unnormalized variable beleifs .
7,552
private VarTensor calcFactorBeliefs ( Factor factor ) { if ( factor instanceof GlobalFactor ) { log . warn ( "Getting marginals of a global factor is not supported." + " This will require exponential space to store the resulting factor." + " This should only be used for testing." ) ; } VarTensor prod = safeNewVarTensor ( factor ) ; calcProductAtFactor ( factor . getId ( ) , prod , - 1 , - 1 ) ; return prod ; }
Gets the unnormalized factor beleifs .
7,553
private static File getTempPath ( String prefix , File parentDir ) throws IOException { final int maxI = ( int ) Math . pow ( 10 , NUM_DIGITS ) ; String formatStr = "%s_%0" + NUM_DIGITS + "d" ; File path ; int i ; for ( i = 0 ; i < maxI ; i ++ ) { path = new File ( parentDir , String . format ( formatStr , prefix , i ) ) ; if ( ! path . exists ( ) ) { return path ; } } path = File . createTempFile ( prefix , "" , parentDir ) ; if ( ! path . delete ( ) ) { throw new RuntimeException ( "Could not delete temp file as expected: " + path ) ; } return path ; }
Creates a file object of a currently available path but does not create the file . This method is not thread safe .
7,554
public static void readUntil ( BufferedReader reader , String breakpoint ) throws IOException { String line ; while ( ( line = reader . readLine ( ) ) != null ) { if ( line . equals ( breakpoint ) ) { return ; } } }
Read until the current line equals the breakpoint string .
7,555
public static void runOutsideAlgorithm ( final int [ ] sent , final CnfGrammar grammar , final LoopOrder loopOrder , final Chart inChart , final Chart outChart , final Scorer scorer ) { ChartCell outRootCell = outChart . getCell ( 0 , sent . length ) ; outRootCell . updateCell ( grammar . getRootSymbol ( ) , 0 , - 1 , null ) ; for ( int width = sent . length ; width >= 1 ; width -- ) { for ( int start = 0 ; start <= sent . length - width ; start ++ ) { int end = start + width ; ChartCell outCell = outChart . getCell ( start , end ) ; ScoresSnapshot scoresSnapshot = outCell . getScoresSnapshot ( ) ; int [ ] nts = outCell . getNts ( ) ; for ( final int parentNt : nts ) { for ( final Rule r : grammar . getUnaryRulesWithParent ( parentNt ) ) { double score = scorer . score ( r , start , end , end ) + scoresSnapshot . getScore ( parentNt ) ; outCell . updateCell ( r . getLeftChild ( ) , score , end , r ) ; } } if ( loopOrder == LoopOrder . CARTESIAN_PRODUCT ) { processCellCartesianProduct ( grammar , inChart , outChart , start , end , outCell , scorer ) ; } else if ( loopOrder == LoopOrder . LEFT_CHILD ) { processCellLeftChild ( grammar , inChart , outChart , start , end , outCell , scorer ) ; } else if ( loopOrder == LoopOrder . RIGHT_CHILD ) { processCellRightChild ( grammar , inChart , outChart , start , end , outCell , scorer ) ; } else { throw new RuntimeException ( "Not implemented: " + loopOrder ) ; } } } for ( int i = 0 ; i <= sent . length - 1 ; i ++ ) { ChartCell outCell = outChart . getCell ( i , i + 1 ) ; ScoresSnapshot scoresSnapshot = outCell . getScoresSnapshot ( ) ; for ( final Rule r : grammar . getLexicalRulesWithChild ( sent [ i ] ) ) { double score = scorer . score ( r , i , i + 1 , i + 1 ) + scoresSnapshot . getScore ( r . getParent ( ) ) ; outCell . updateCell ( r . getLeftChild ( ) , score , i + 1 , r ) ; } } }
Runs the outside algorithm given an inside chart .
7,556
public static IntDoubleVector estimateGradientFd ( Function fn , IntDoubleVector x , double epsilon ) { int numParams = fn . getNumDimensions ( ) ; IntDoubleVector gradFd = new IntDoubleDenseVector ( numParams ) ; for ( int j = 0 ; j < numParams ; j ++ ) { IntDoubleVector d = new IntDoubleDenseVector ( numParams ) ; d . set ( j , 1 ) ; double dotFd = getGradDotDirApprox ( fn , x , d , epsilon ) ; if ( Double . isNaN ( dotFd ) ) { log . warn ( "Hit NaN" ) ; } gradFd . set ( j , dotFd ) ; } return gradFd ; }
Estimates a gradient of a function by an independent finite - difference computation along each dimension of the domain of the function .
7,557
public void reset ( Sentence sentence ) { this . sentence = sentence ; if ( sentence . size ( ) > chart . length ) { chart = getNewChart ( sentence , grammar , cellType , parseType , constraint ) ; } else { for ( int i = 0 ; i < sentence . size ( ) ; i ++ ) { for ( int j = i + 1 ; j < sentence . size ( ) + 1 ; j ++ ) { chart [ i ] [ j ] . reset ( sentence ) ; } } } }
Resets the chart for the input sentence .
7,558
private static ChartCell [ ] [ ] getNewChart ( Sentence sentence , CnfGrammar grammar , ChartCellType cellType , ParseType parseType , ChartCellConstraint constraint ) { ChartCell [ ] [ ] chart = new ChartCell [ sentence . size ( ) ] [ sentence . size ( ) + 1 ] ; for ( int i = 0 ; i < chart . length ; i ++ ) { for ( int j = i + 1 ; j < chart [ i ] . length ; j ++ ) { if ( parseType == ParseType . INSIDE && cellType != ChartCellType . FULL ) { throw new RuntimeException ( "Inside algorithm not implemented for cell type: " + cellType ) ; } ChartCell cell ; switch ( cellType ) { case SINGLE_HASH : chart [ i ] [ j ] = new SingleHashChartCell ( grammar , false ) ; break ; case SINGLE_HASH_BREAK_TIES : chart [ i ] [ j ] = new SingleHashChartCell ( grammar , true ) ; break ; case CONSTRAINED_SINGLE : cell = new SingleHashChartCell ( grammar , true ) ; chart [ i ] [ j ] = new ConstrainedChartCell ( i , j , cell , constraint , sentence ) ; break ; case DOUBLE_HASH : chart [ i ] [ j ] = new DoubleHashChartCell ( grammar ) ; break ; case FULL : chart [ i ] [ j ] = new FullChartCell ( i , j , grammar , parseType ) ; break ; case FULL_BREAK_TIES : chart [ i ] [ j ] = new FullTieBreakerChartCell ( grammar , true ) ; break ; case CONSTRAINED_FULL : cell = new FullTieBreakerChartCell ( grammar , true ) ; chart [ i ] [ j ] = new ConstrainedChartCell ( i , j , cell , constraint , sentence ) ; break ; default : throw new RuntimeException ( "not implemented for " + cellType ) ; } } } return chart ; }
Gets a new chart of the appropriate size for the sentence specific to this grammar and with cells of the specified type .
7,559
public void setInitializationVector ( String initializationVector ) { try { this . initializationVectorSpec = new IvParameterSpec ( Base64 . decodeBase64 ( initializationVector . getBytes ( "UTF-8" ) ) ) ; } catch ( UnsupportedEncodingException e ) { throw new SymmetricEncryptionException ( "UTF-8 is an unsupported encoding on this platform" , e ) ; } }
A base64 encoded representation of the raw byte array containing the initialization vector .
7,560
public double getValue ( int idx ) { int vSize = MVecArray . count ( varBeliefs ) ; if ( idx < vSize ) { return MVecArray . getValue ( idx , varBeliefs ) ; } else { return MVecArray . getValue ( idx - vSize , facBeliefs ) ; } }
Gets a particular value by treating this object as a vector .
7,561
public double setValue ( int idx , double val ) { int vSize = MVecArray . count ( varBeliefs ) ; if ( idx < vSize ) { return MVecArray . setValue ( idx , val , varBeliefs ) ; } else { return MVecArray . setValue ( idx - vSize , val , facBeliefs ) ; } }
Sets a particular value by treating this object as a vector .
7,562
public FactorGraph readBnAsFg ( File networkFile , File cpdFile ) throws IOException { return readBnAsFg ( new FileInputStream ( networkFile ) , new FileInputStream ( cpdFile ) ) ; }
Reads a Bayesian Network from a network file and a CPD file and returns a factor graph representation of it .
7,563
public FactorGraph readBnAsFg ( InputStream networkIs , InputStream cpdIs ) throws IOException { BufferedReader networkReader = new BufferedReader ( new InputStreamReader ( networkIs ) ) ; int numVars = Integer . parseInt ( networkReader . readLine ( ) . trim ( ) ) ; varMap = new HashMap < String , Var > ( ) ; VarSet allVars = new VarSet ( ) ; for ( int i = 0 ; i < numVars ; i ++ ) { Var var = parseVar ( networkReader . readLine ( ) ) ; allVars . add ( var ) ; varMap . put ( var . getName ( ) , var ) ; } assert ( allVars . size ( ) == numVars ) ; networkReader . close ( ) ; BufferedReader cpdReader = new BufferedReader ( new InputStreamReader ( cpdIs ) ) ; factorMap = new LinkedHashMap < VarSet , ExplicitFactor > ( ) ; String line ; while ( ( line = cpdReader . readLine ( ) ) != null ) { VarConfig config = new VarConfig ( ) ; String [ ] assns = whitespaceOrComma . split ( line ) ; for ( int i = 0 ; i < assns . length - 1 ; i ++ ) { String assn = assns [ i ] ; String [ ] va = equals . split ( assn ) ; assert ( va . length == 2 ) ; String varName = va [ 0 ] ; String stateName = va [ 1 ] ; config . put ( varMap . get ( varName ) , stateName ) ; } double value = Double . parseDouble ( assns [ assns . length - 1 ] ) ; value = FastMath . log ( value ) ; VarSet vars = config . getVars ( ) ; ExplicitFactor f = factorMap . get ( vars ) ; if ( f == null ) { f = new ExplicitFactor ( vars ) ; } f . setValue ( config . getConfigIndex ( ) , value ) ; factorMap . put ( vars , f ) ; } cpdReader . close ( ) ; FactorGraph fg = new FactorGraph ( ) ; for ( ExplicitFactor f : factorMap . values ( ) ) { fg . addFactor ( f ) ; } return fg ; }
Reads a Bayesian Network from a network InputStream and a CPD InputStream and returns a factor graph representation of it .
7,564
private static Var parseVar ( String varLine ) { String [ ] ws = whitespace . split ( varLine ) ; String name = ws [ 0 ] ; List < String > stateNames = Arrays . asList ( comma . split ( ws [ 1 ] ) ) ; int numStates = stateNames . size ( ) ; return new Var ( VarType . PREDICTED , numStates , name , stateNames ) ; }
Reads a variable from a line containing the variable name a space then a comma - separated list of the values it can take .
7,565
public boolean add ( T e ) { if ( elements . add ( e ) ) { ordered . add ( e ) ; return true ; } else { return false ; } }
maintain the set so that it is easy to test membership the list so that there is a fixed order
7,566
public boolean remove ( Object o ) { if ( elements . remove ( o ) ) { ordered . remove ( o ) ; return true ; } else { return false ; } }
remove will be slow
7,567
public String digest ( String message ) { final byte [ ] messageAsByteArray ; try { messageAsByteArray = message . getBytes ( charsetName ) ; } catch ( UnsupportedEncodingException e ) { throw new DigestException ( "error converting message to byte array: charsetName=" + charsetName , e ) ; } final byte [ ] digest = digest ( messageAsByteArray ) ; switch ( outputMode ) { case BASE64 : return Base64 . encodeBase64String ( digest ) ; case HEX : return Hex . encodeHexString ( digest ) ; default : return null ; } }
Returns the message digest . The representation of the message digest depends on the outputMode property .
7,568
public void addEdge ( DiEdge e ) { if ( ! getEdges ( ) . contains ( e ) ) { super . addEdge ( e ) ; weights . put ( e , makeDefaultWeight . apply ( e ) ) ; } }
Attempts to adds the edge to the graph with default weight if not already present ; If the edge is already present does nothing .
7,569
public void addEdge ( DiEdge e , double w ) { if ( ! getEdges ( ) . contains ( e ) ) { super . addEdge ( e ) ; weights . put ( e , w ) ; } }
Adds the edge with the given weight
7,570
public void setWeight ( int s , int t , double w ) { DiEdge e = edge ( s , t ) ; assertEdge ( e ) ; weights . put ( e , w ) ; }
Sets the weight of the edge s - > t to be w if the edge is present otherwise an IndexOutOfBoundsException is thrown
7,571
public static < X > ArrayList < X > sublist ( List < X > list , int start , int end ) { ArrayList < X > sublist = new ArrayList < X > ( ) ; for ( int i = start ; i < end ; i ++ ) { sublist . add ( list . get ( i ) ) ; } return sublist ; }
Creates a new list containing a slice of the original list .
7,572
public static ArrayList < String > getInternedList ( List < String > oldList ) { ArrayList < String > newList = new ArrayList < String > ( oldList . size ( ) ) ; for ( String elem : oldList ) { newList . add ( elem . intern ( ) ) ; } return newList ; }
Gets a new list of Strings that have been interned .
7,573
public static void intern ( List < String > list ) { if ( list == null ) { return ; } for ( int i = 0 ; i < list . size ( ) ; i ++ ) { String interned = list . get ( i ) ; if ( interned != null ) { interned = interned . intern ( ) ; } list . set ( i , interned ) ; } }
Interns a list of strings in place .
7,574
public static < T > Collection < T > collect ( Iterable < T > stream ) { LinkedList < T > collection = new LinkedList < > ( ) ; for ( T e : stream ) { collection . add ( e ) ; } return collection ; }
Returns a Collections that contains all of the objects from the underlying stream in order
7,575
public static < T > Iterable < Indexed < T > > enumerate ( Iterable < T > stream ) { return new Iterable < Indexed < T > > ( ) { public Iterator < Indexed < T > > iterator ( ) { Iterator < T > itr = stream . iterator ( ) ; return new Iterator < Indexed < T > > ( ) { private int i = 0 ; public boolean hasNext ( ) { return itr . hasNext ( ) ; } public Indexed < T > next ( ) { Indexed < T > nextPair = new Indexed < T > ( itr . next ( ) , i ) ; i ++ ; return nextPair ; } } ; } } ; }
Returns an iterable over Index objects that each hold one of the original objects of the stream as well its index in the stream
7,576
public int find ( int element ) { if ( trees [ element ] != element ) trees [ element ] = find ( trees [ element ] ) ; return trees [ element ] ; }
Return the set where the given element is . This implementation compresses the followed path .
7,577
public Certificate get ( KeyStoreChooser keyStoreChooser , CertificateChooserByAlias certificateChooserByAlias ) { CacheCert cacheCert = new CacheCert ( keyStoreChooser . getKeyStoreName ( ) , certificateChooserByAlias . getAlias ( ) ) ; Certificate retrievedCertificate = cache . get ( cacheCert ) ; if ( retrievedCertificate != null ) { return retrievedCertificate ; } KeyStore keyStore = keyStoreRegistry . get ( keyStoreChooser ) ; if ( keyStore != null ) { CertificateFactoryBean factory = new CertificateFactoryBean ( ) ; factory . setKeystore ( keyStore ) ; factory . setAlias ( certificateChooserByAlias . getAlias ( ) ) ; try { factory . afterPropertiesSet ( ) ; Certificate certificate = ( Certificate ) factory . getObject ( ) ; if ( certificate != null ) { cache . put ( cacheCert , certificate ) ; } return certificate ; } catch ( Exception e ) { throw new CertificateException ( "error initializing the certificate factory bean" , e ) ; } } return null ; }
Returns the selected certificate or null if not found .
7,578
protected boolean checkHandler ( RoomHandlerClass handler , ApiRoom roomAgent , Object user ) { return ( handler . getRoomClass ( ) . isAssignableFrom ( roomAgent . getClass ( ) ) ) && ( roomAgent . getName ( ) . startsWith ( handler . getRoomName ( ) ) ) ; }
Validate the handler
7,579
private void callHandleMethod ( Method method , Object instance , Object roomAgent , Object userAgent ) { ReflectMethodUtil . invokeHandleMethod ( method , instance , context , roomAgent , userAgent ) ; }
Invoke handle method
7,580
@ SuppressWarnings ( "unchecked" ) public ApiRoom execute ( ) { Room sfsRoom = CommandUtil . getSfsRoom ( agent , extension ) ; User sfsUser = CommandUtil . getSfsUser ( user , api ) ; if ( sfsRoom == null ) return null ; AgentClassUnwrapper unwrapper = context . getRoomAgentClass ( agent . getClass ( ) ) . getUnwrapper ( ) ; List < RoomVariable > variables = new RoomAgentSerializer ( ) . serialize ( unwrapper , agent ) ; List < RoomVariable > answer = variables ; if ( includedVars . size ( ) > 0 ) answer = getVariables ( variables , includedVars ) ; answer . removeAll ( getVariables ( answer , excludedVars ) ) ; if ( toClient ) api . setRoomVariables ( sfsUser , sfsRoom , answer ) ; else sfsRoom . setVariables ( answer ) ; return agent ; }
Execute update room variables
7,581
public static EdgeScores getEdgeMarginalsRealSemiring ( O2AllGraDpHypergraph graph , Scores sc ) { Algebra s = graph . getAlgebra ( ) ; int nplus = graph . getNumTokens ( ) + 1 ; Hypernode [ ] [ ] [ ] [ ] c = graph . getChart ( ) ; EdgeScores marg = new EdgeScores ( graph . getNumTokens ( ) , 0.0 ) ; for ( int width = 1 ; width < nplus ; width ++ ) { for ( int i = 0 ; i < nplus - width ; i ++ ) { int j = i + width ; for ( int g = 0 ; g < nplus ; g ++ ) { if ( i <= g && g <= j && ! ( i == 0 && g == O2AllGraDpHypergraph . NIL ) ) { continue ; } if ( j > 0 ) { marg . incrScore ( i - 1 , j - 1 , s . toReal ( sc . marginal [ c [ i ] [ j ] [ g ] [ O2AllGraDpHypergraph . INCOMPLETE ] . getId ( ) ] ) ) ; } if ( i > 0 ) { marg . incrScore ( j - 1 , i - 1 , s . toReal ( sc . marginal [ c [ j ] [ i ] [ g ] [ O2AllGraDpHypergraph . INCOMPLETE ] . getId ( ) ] ) ) ; } } } } return marg ; }
Gets the edge marginals in the real semiring from an all - grandparents hypergraph and its marginals in scores .
7,582
public static boolean hasOneParentPerToken ( int n , VarConfig vc ) { int [ ] parents = new int [ n ] ; Arrays . fill ( parents , - 2 ) ; for ( Var v : vc . getVars ( ) ) { if ( v instanceof LinkVar ) { LinkVar link = ( LinkVar ) v ; if ( vc . getState ( v ) == LinkVar . TRUE ) { if ( parents [ link . getChild ( ) ] != - 2 ) { return false ; } parents [ link . getChild ( ) ] = link . getParent ( ) ; } } } return ! ArrayUtils . contains ( parents , - 2 ) ; }
Returns whether this variable assignment specifies one parent per token .
7,583
public static int [ ] getParents ( int n , VarConfig vc ) { int [ ] parents = new int [ n ] ; Arrays . fill ( parents , - 2 ) ; for ( Var v : vc . getVars ( ) ) { if ( v instanceof LinkVar ) { LinkVar link = ( LinkVar ) v ; if ( vc . getState ( v ) == LinkVar . TRUE ) { if ( parents [ link . getChild ( ) ] != - 2 ) { throw new IllegalStateException ( "Multiple parents defined for the same child. Is this VarConfig for only one example?" ) ; } parents [ link . getChild ( ) ] = link . getParent ( ) ; } } } return parents ; }
Extracts the parents as defined by a variable assignment for a single sentence .
7,584
private static VarTensor getProductOfAllFactors ( FactorGraph fg , Algebra s ) { VarTensor joint = new VarTensor ( s , new VarSet ( ) , s . one ( ) ) ; for ( int a = 0 ; a < fg . getNumFactors ( ) ; a ++ ) { Factor f = fg . getFactor ( a ) ; VarTensor factor = safeNewVarTensor ( s , f ) ; assert ! factor . containsBadValues ( ) : factor ; joint . prod ( factor ) ; } return joint ; }
Gets the product of all the factors in the factor graph . If working in the log - domain this will do factor addition .
7,585
protected boolean checkHandler ( ZoneHandlerClass handler , ApiZone apiZone ) { return apiZone . getName ( ) . startsWith ( handler . getZoneName ( ) ) ; }
Check zone name
7,586
private void callHandleMethod ( Method method , Object instance , ApiZone apiZone , Object userAgent ) { ReflectMethodUtil . invokeHandleMethod ( method , instance , context , apiZone , userAgent ) ; }
Call handle method
7,587
public static double probabilityTruncZero ( double a , double b , double mu , double sigma ) { a = Math . max ( a , 0.0 ) ; b = Math . max ( b , 0.0 ) ; final double denom = sigma * SQRT2 ; final double scaledSDA = ( a - mu ) / denom ; final double scaledSDB = ( b - mu ) / denom ; final double probNormTimes2 = Erf . erf ( scaledSDA , scaledSDB ) ; final double scaledSD0 = - mu / denom ; final double reZTimes2 = Erf . erfc ( scaledSD0 ) ; return probNormTimes2 / reZTimes2 ; }
returns the probability of x falling within the range of a to b under a normal distribution with mean mu and standard deviation sigma if the distribution is truncated below 0 and renormalized
7,588
public static double meanTruncLower ( double mu , double sigma , double lowerBound ) { double alpha = ( lowerBound - mu ) / sigma ; double phiAlpha = densityNonTrunc ( alpha , 0 , 1.0 ) ; double cPhiAlpha = cumulativeNonTrunc ( alpha , 0 , 1.0 ) ; return mu + sigma * phiAlpha / ( 1.0 - cPhiAlpha ) ; }
Returns the mean of the normal distribution truncated to 0 for values of x < lowerBound
7,589
void set ( int row , int column , V value ) { this . row = row ; this . column = column ; this . value = value ; }
Sets the content of the cell .
7,590
public DeviceEnvelope getDevice ( String deviceId ) throws ApiException { ApiResponse < DeviceEnvelope > resp = getDeviceWithHttpInfo ( deviceId ) ; return resp . getData ( ) ; }
Get Device Retrieves a device
7,591
public SubscriptionEnvelope deleteSubscription ( String subId ) throws ApiException { ApiResponse < SubscriptionEnvelope > resp = deleteSubscriptionWithHttpInfo ( subId ) ; return resp . getData ( ) ; }
Delete Subscription Delete Subscription
7,592
private void init ( DelaunayTriangulation delaunay , int xCellCount , int yCellCount , BoundingBox region ) { indexDelaunay = delaunay ; indexRegion = region ; x_size = region . getWidth ( ) / yCellCount ; y_size = region . getHeight ( ) / xCellCount ; grid = new Triangle [ xCellCount ] [ yCellCount ] ; Triangle colStartTriangle = indexDelaunay . find ( middleOfCell ( 0 , 0 ) ) ; updateCellValues ( 0 , 0 , xCellCount - 1 , yCellCount - 1 , colStartTriangle ) ; }
Initialize the grid index
7,593
public Triangle findCellTriangleOf ( Point3D point ) { int x_index = ( int ) ( ( point . x - indexRegion . minX ( ) ) / x_size ) ; int y_index = ( int ) ( ( point . y - indexRegion . minY ( ) ) / y_size ) ; return grid [ x_index ] [ y_index ] ; }
Finds a triangle near the given point
7,594
public void updateIndex ( Iterator < Triangle > updatedTriangles ) { BoundingBox updatedRegion = new BoundingBox ( ) ; while ( updatedTriangles . hasNext ( ) ) { updatedRegion = updatedRegion . unionWith ( updatedTriangles . next ( ) . getBoundingBox ( ) ) ; } if ( updatedRegion . isNull ( ) ) return ; if ( ! indexRegion . contains ( updatedRegion ) ) { init ( indexDelaunay , ( int ) ( indexRegion . getWidth ( ) / x_size ) , ( int ) ( indexRegion . getHeight ( ) / y_size ) , indexRegion . unionWith ( updatedRegion ) ) ; } else { Vector2i minInvalidCell = getCellOf ( updatedRegion . getMinPoint ( ) ) ; Vector2i maxInvalidCell = getCellOf ( updatedRegion . getMaxPoint ( ) ) ; Triangle adjacentValidTriangle = findValidTriangle ( minInvalidCell ) ; updateCellValues ( minInvalidCell . getX ( ) , minInvalidCell . getY ( ) , maxInvalidCell . getX ( ) , maxInvalidCell . getY ( ) , adjacentValidTriangle ) ; } }
Updates the grid index to reflect changes to the triangulation . Note that added triangles outside the indexed region will force to recompute the whole index with the enlarged region .
7,595
private Vector2i getCellOf ( Point3D coordinate ) { int xCell = ( int ) ( ( coordinate . x - indexRegion . minX ( ) ) / x_size ) ; int yCell = ( int ) ( ( coordinate . y - indexRegion . minY ( ) ) / y_size ) ; return new Vector2i ( xCell , yCell ) ; }
Locates the grid cell point covering the given coordinate
7,596
private Vector3 middleOfCell ( int x_index , int y_index ) { float middleXCell = ( float ) ( indexRegion . minX ( ) + x_index * x_size + x_size / 2 ) ; float middleYCell = ( float ) ( indexRegion . minY ( ) + y_index * y_size + y_size / 2 ) ; return new Vector3 ( middleXCell , middleYCell , 0 ) ; }
Create a point at the center of a cell
7,597
public static double Function ( double x ) { double [ ] P = { 1.60119522476751861407E-4 , 1.19135147006586384913E-3 , 1.04213797561761569935E-2 , 4.76367800457137231464E-2 , 2.07448227648435975150E-1 , 4.94214826801497100753E-1 , 9.99999999999999996796E-1 } ; double [ ] Q = { - 2.31581873324120129819E-5 , 5.39605580493303397842E-4 , - 4.45641913851797240494E-3 , 1.18139785222060435552E-2 , 3.58236398605498653373E-2 , - 2.34591795718243348568E-1 , 7.14304917030273074085E-2 , 1.00000000000000000320E0 } ; double p , z ; double q = Math . abs ( x ) ; if ( q > 33.0 ) { if ( x < 0.0 ) { p = Math . floor ( q ) ; if ( p == q ) { try { throw new ArithmeticException ( "Overflow" ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } z = q - p ; if ( z > 0.5 ) { p += 1.0 ; z = q - p ; } z = q * Math . sin ( Math . PI * z ) ; if ( z == 0.0 ) { try { throw new ArithmeticException ( "Overflow" ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } z = Math . abs ( z ) ; z = Math . PI / ( z * Stirling ( q ) ) ; return - z ; } else { return Stirling ( x ) ; } } z = 1.0 ; while ( x >= 3.0 ) { x -= 1.0 ; z *= x ; } while ( x < 0.0 ) { if ( x == 0.0 ) { throw new ArithmeticException ( ) ; } else if ( x > - 1.0E-9 ) { return ( z / ( ( 1.0 + 0.5772156649015329 * x ) * x ) ) ; } z /= x ; x += 1.0 ; } while ( x < 2.0 ) { if ( x == 0.0 ) { throw new ArithmeticException ( ) ; } else if ( x < 1.0E-9 ) { return ( z / ( ( 1.0 + 0.5772156649015329 * x ) * x ) ) ; } z /= x ; x += 1.0 ; } if ( ( x == 2.0 ) || ( x == 3.0 ) ) return z ; x -= 2.0 ; p = Special . Polevl ( x , P , 6 ) ; q = Special . Polevl ( x , Q , 7 ) ; return z * p / q ; }
Gamma function of the specified value .
7,598
public static double Stirling ( double x ) { double [ ] STIR = { 7.87311395793093628397E-4 , - 2.29549961613378126380E-4 , - 2.68132617805781232825E-3 , 3.47222221605458667310E-3 , 8.33333333333482257126E-2 , } ; double MAXSTIR = 143.01608 ; double w = 1.0 / x ; double y = Math . exp ( x ) ; w = 1.0 + w * Special . Polevl ( w , STIR , 4 ) ; if ( x > MAXSTIR ) { double v = Math . pow ( x , 0.5 * x - 0.25 ) ; y = v * ( v / y ) ; } else { y = Math . pow ( x , x - 0.5 ) / y ; } y = 2.50662827463100050242E0 * y * w ; return y ; }
Gamma function as computed by Stirling s formula .
7,599
public static double Digamma ( double x ) { double s = 0 ; double w = 0 ; double y = 0 ; double z = 0 ; double nz = 0 ; boolean negative = false ; if ( x <= 0.0 ) { negative = true ; double q = x ; double p = ( int ) Math . floor ( q ) ; if ( p == q ) { try { throw new ArithmeticException ( "Function computation resulted in arithmetic overflow." ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } nz = q - p ; if ( nz != 0.5 ) { if ( nz > 0.5 ) { p = p + 1.0 ; nz = q - p ; } nz = Math . PI / Math . tan ( Math . PI * nz ) ; } else { nz = 0.0 ; } x = 1.0 - x ; } if ( x <= 10.0 && x == Math . floor ( x ) ) { y = 0.0 ; int n = ( int ) Math . floor ( x ) ; for ( int i = 1 ; i <= n - 1 ; i ++ ) { w = i ; y = y + 1.0 / w ; } y = y - 0.57721566490153286061 ; } else { s = x ; w = 0.0 ; while ( s < 10.0 ) { w = w + 1.0 / s ; s = s + 1.0 ; } if ( s < 1.0E17 ) { z = 1.0 / ( s * s ) ; double polv = 8.33333333333333333333E-2 ; polv = polv * z - 2.10927960927960927961E-2 ; polv = polv * z + 7.57575757575757575758E-3 ; polv = polv * z - 4.16666666666666666667E-3 ; polv = polv * z + 3.96825396825396825397E-3 ; polv = polv * z - 8.33333333333333333333E-3 ; polv = polv * z + 8.33333333333333333333E-2 ; y = z * polv ; } else { y = 0.0 ; } y = Math . log ( s ) - 0.5 / s - y - w ; } if ( negative == true ) { y = y - nz ; } return y ; }
Digamma function .