code
stringlengths 67
466k
| docstring
stringlengths 1
13.2k
|
---|---|
public int delMetaBeanById(String tableName, String id) {
//JdbcTemplate jdbcTemplate = (JdbcTemplate) MicroDbHolder.getDbSource(dbName);
JdbcTemplate jdbcTemplate =getMicroJdbcTemplate();
String sql = "delete from " + tableName + " where id=?";
String[] paramArray=new String[1];
paramArray[0]=id;
logger.debug(sql);
logger.debug(paramArray);
Integer retStatus=jdbcTemplate.update(sql,paramArray);
return retStatus;
} | /*
锟斤拷荼锟斤拷锟斤拷id删锟斤拷锟阶硷拷锟斤拷bean |
public int updateMetaBeanById(String tableName, String id,MicroMetaBean microMetaBean) {
//JdbcTemplate jdbcTemplate = (JdbcTemplate) MicroDbHolder.getDbSource(dbName);
JdbcTemplate jdbcTemplate =getMicroJdbcTemplate();
String setMetaContent="";
String setMetaKey="";
String setMetaName="";
String setMetaType="";
String setRemark="";
String setCreate_time="";
String setUpdate_time="";
String setStr="";
List paramList=new ArrayList();
if(microMetaBean.getMeta_content()!=null){
setMetaContent="meta_content=?";
setStr=setStr+","+setMetaContent;
paramList.add(microMetaBean.getMeta_content());
}
if(microMetaBean.getMeta_key()!=null){
setMetaKey="meta_key=?";
setStr=setStr+","+setMetaKey;
paramList.add(microMetaBean.getMeta_key());
}
if(microMetaBean.getMeta_name()!=null){
setMetaName="meta_name=?";
setStr=setStr+","+setMetaName;
paramList.add(microMetaBean.getMeta_name());
}
if(microMetaBean.getMeta_type()!=null){
setMetaType="meta_type=?";
setStr=setStr+","+setMetaType;
paramList.add(microMetaBean.getMeta_type());
}
if(microMetaBean.getRemark()!=null){
setRemark="remark=?";
setStr=setStr+","+setRemark;
paramList.add(microMetaBean.getRemark());
}
final MicroMetaBean insertBean=microMetaBean;
String timeName=getTimeName();
String sql = "update " + tableName +" set update_time="+timeName+" "+setStr+ " where id=?";
paramList.add(id);
logger.debug(sql);
logger.debug(paramList.toArray());
Integer retStatus=jdbcTemplate.update(sql,paramList.toArray());
return retStatus;
} | /*
锟斤拷荼锟斤拷锟斤拷id锟斤拷锟铰憋拷准锟斤拷锟絙ean |
public int insertMetaBeanById(String tableName, MicroMetaBean microMetaBean) {
//JdbcTemplate jdbcTemplate = (JdbcTemplate) MicroDbHolder.getDbSource(dbName);
JdbcTemplate jdbcTemplate =getMicroJdbcTemplate();
final MicroMetaBean insertBean=microMetaBean;
String timeName=getTimeName();
String sql = "insert into " + tableName +"(id,meta_content,meta_key,meta_name,meta_type,remark,create_time,update_time) values(?,?,?,?,?,?,"+timeName+","+timeName+") ";
List paramList=new ArrayList();
paramList.add(insertBean.getId());
paramList.add(insertBean.getMeta_content());
paramList.add(insertBean.getMeta_key());
paramList.add(insertBean.getMeta_name());
paramList.add(insertBean.getMeta_type());
paramList.add(insertBean.getRemark());
logger.debug(sql);
logger.debug(paramList.toArray());
Integer retStatus=jdbcTemplate.update(sql,paramList.toArray());
return retStatus;
} | /*
锟斤拷荼锟斤拷锟斤拷id锟斤拷锟斤拷锟阶硷拷锟斤拷bean |
public List<MicroMetaBean> queryMetaBeanByCondition(String tableName, String condition) {
List<MicroMetaBean> retBeanList=new ArrayList();
/* JdbcTemplate jdbcTemplate = (JdbcTemplate) MicroDbHolder
.getDbSource(dbName);*/
JdbcTemplate jdbcTemplate = getMicroJdbcTemplate();
String sql = "select * from " + tableName + " where "+condition;
logger.debug(sql);
List<Map<String, Object>> retList = jdbcTemplate.queryForList(sql);
if(retList==null){
return retBeanList;
}
for(Map<String,Object> rowMap:retList){
MicroMetaBean metaBean = new MicroMetaBean();
metaBean.setId((String) rowMap.get("id"));
metaBean.setMeta_content((String) rowMap.get("meta_content"));
metaBean.setMeta_key((String) rowMap.get("meta_key"));
metaBean.setMeta_name((String) rowMap.get("meta_name"));
metaBean.setMeta_type((String) rowMap.get("meta_type"));
metaBean.setRemark((String) rowMap.get("remark"));
metaBean.setCreate_time((Date) rowMap.get("create_time"));
metaBean.setUpdate_time((Date) rowMap.get("update_time"));
retBeanList.add(metaBean);
}
return retBeanList;
} | /*
锟斤拷荼锟斤拷锟斤拷锟斤拷锟斤拷锟窖拷锟阶硷拷锟斤拷bean |
public List<Map<String, Object>> queryObjJoinByCondition(String sql) {
/* JdbcTemplate jdbcTemplate = (JdbcTemplate) MicroDbHolder
.getDbSource(dbName);*/
JdbcTemplate jdbcTemplate = getMicroJdbcTemplate();
logger.debug(sql);
List<Map<String, Object>> retList0 = jdbcTemplate.queryForList(sql);
//add 201807 ning
//List<Map<String, Object>> retList=changeOutKeyCase4List(retList0);
//add 201902 ning
List<Map<String, Object>> retList=ignoreKeyCase((List)retList0);
return retList;
} | /*
锟斤拷锟絪ql锟斤拷询 |
public Map<String, Object> queryObjJoinById(String tableName,Object id) {
//String tableName=changeTableNameCase(otableName);
//String tempIdKey=changeInIdKeyCase(calcuIdKey());
String tempIdKey=calcuIdKey();
String where="where "+tempIdKey+"=?";
String limitStr="";
String tempType=calcuDbType();
if(tempType!=null && tempType.equals("mysql")){
//if(dbType!=null && dbType.equals("mysql")){
limitStr="limit 1";
}else{
limitStr="and rownum=1";
}
String select="select * from "+tableName+" "+where+" "+limitStr;
String sql=select+" ";
Object[] paramArray=new Object[1];
logger.debug(sql);
logger.debug(paramArray);
paramArray[0]=id;
List infoList=queryObjJoinByCondition(sql,paramArray);
// init by null
Map retMap0=null;
if(infoList!=null && infoList.size()>0){
retMap0=(Map) infoList.get(0);
}
//add 201807 ning
//Map retMap=changeOutKeyCase(retMap0);
//add 201902 ning
Map retMap=ignoreKeyCase(retMap0);
return retMap;
} | /*
锟斤拷锟絠d锟斤拷询 |
public Map<String, Object> queryObjJoinByBizId(String tableName,Object bizId,String condition) {
//String tableName=changeTableNameCase(otableName);
String where="where "+condition+"=?";
String limitStr="";
String tempType=calcuDbType();
if(tempType!=null && tempType.equals("mysql")){
//if(dbType!=null && dbType.equals("mysql")){
limitStr="limit 1";
}else{
limitStr="and rownum=1";
}
String select="select * from "+tableName+" "+where+" "+limitStr;
String sql=select+" ";
logger.debug(sql);
Object[] paramArray=new Object[1];
paramArray[0]=bizId;
List infoList=queryObjJoinByCondition(sql,paramArray);
//init by null
Map retMap0=null;
if(infoList!=null && infoList.size()>0){
retMap0=(Map) infoList.get(0);
}
//add 201807 ning
//Map retMap=changeOutKeyCase(retMap0);
//add 201902 ning
Map retMap=ignoreKeyCase(retMap0);
return retMap;
} | /*
锟斤拷锟揭碉拷锟絠d锟斤拷询 |
public List<Map<String, Object>> queryObjJoinDataByPageCondition(String innerSql, int start,int end) {
/* JdbcTemplate jdbcTemplate = (JdbcTemplate) MicroDbHolder
.getDbSource(dbName);*/
JdbcTemplate jdbcTemplate = getMicroJdbcTemplate();
String sql = "";
String tempType=calcuDbType();
if(tempType!=null && tempType.equals("mysql")){
//if(dbType!=null && dbType.equals("mysql")){
int pageRows=end-start;
String limit=start+","+pageRows;
sql=innerSql+ " limit "+limit;
}else{
String startLimit=" WHERE NHPAGE_RN >= "+start;
String endLimit=" WHERE ROWNUM < "+end;
/* if(orclEndFlag==false){
endLimit=" WHERE ROWNUM < "+end;
}*/
sql="SELECT * FROM ( SELECT NHPAGE_TEMP.*, ROWNUM NHPAGE_RN FROM ("+ innerSql +" ) NHPAGE_TEMP "+endLimit+" ) "+ startLimit;
}
logger.debug(sql);
List<Map<String, Object>> retList0 = jdbcTemplate.queryForList(sql);
//add 201807 ning
//List<Map<String, Object>> retList=changeOutKeyCase4List(retList0);
//add 201902 ning
List<Map<String, Object>> retList=ignoreKeyCase((List)retList0);
return retList;
} | /*
锟斤拷锟絪ql锟斤拷页锟斤拷询 |
public int queryObjJoinCountByCondition(String sql){
/* JdbcTemplate jdbcTemplate = (JdbcTemplate) MicroDbHolder
.getDbSource(dbName);*/
JdbcTemplate jdbcTemplate = getMicroJdbcTemplate();
logger.debug(sql);
Integer total=jdbcTemplate.queryForObject(sql,Integer.class);
return total;
} | /*
锟斤拷锟絪ql锟斤拷询锟斤拷录锟斤拷 |
public int queryObjJoinCountByCondition(String sql,Object[] paramArray){
/* JdbcTemplate jdbcTemplate = (JdbcTemplate) MicroDbHolder
.getDbSource(dbName);*/
JdbcTemplate jdbcTemplate = getMicroJdbcTemplate();
logger.debug(sql);
logger.debug(Arrays.toString(paramArray));
Integer total=jdbcTemplate.queryForObject(sql,Integer.class,paramArray);
return total;
} | /*
锟斤拷锟絪ql锟斤拷询锟斤拷录锟斤拷 |
public List<Map<String, Object>> queryObjByCondition(String tableName, String condition,String cols, String orders,Object[] paramArray,int[] typeArray) {
//String tableName=changeTableNameCase(otableName);
/* JdbcTemplate jdbcTemplate = (JdbcTemplate) MicroDbHolder
.getDbSource(dbName);*/
JdbcTemplate jdbcTemplate = getMicroJdbcTemplate();
String sql = "select "+cols+" from " + tableName + " where "+condition+" order by "+orders;
logger.debug(sql);
logger.debug(Arrays.toString(paramArray));
List<Map<String, Object>> retList0 = jdbcTemplate.queryForList(sql,paramArray,typeArray);
//add 201807 ning
//List<Map<String, Object>> retList=changeOutKeyCase4List(retList0);
//add 201902 ning
List<Map<String, Object>> retList=ignoreKeyCase((List)retList0);
return retList;
} | /*
锟斤拷荼锟斤拷锟斤拷询 |
public int queryObjCountByCondition(String tableName, String condition){
/* JdbcTemplate jdbcTemplate = (JdbcTemplate) MicroDbHolder
.getDbSource(dbName);*/
//String tableName=changeTableNameCase(otableName);
JdbcTemplate jdbcTemplate = getMicroJdbcTemplate();
String sql="";
sql="select count(1) from " + tableName + " where "+condition;
logger.debug(sql);
Integer total=jdbcTemplate.queryForObject(sql,Integer.class);
return total;
} | /*
锟斤拷荼锟斤拷锟斤拷询锟斤拷录锟斤拷 |
public int queryObjCountByCondition(String tableName, String condition,Object[] paramArray){
/* JdbcTemplate jdbcTemplate = (JdbcTemplate) MicroDbHolder
.getDbSource(dbName);*/
//String tableName=changeTableNameCase(otableName);
JdbcTemplate jdbcTemplate = getMicroJdbcTemplate();
String sql="";
sql="select count(1) from " + tableName + " where "+condition;
logger.debug(sql);
logger.debug(Arrays.toString(paramArray));
Integer total=jdbcTemplate.queryForObject(sql,Integer.class,paramArray);
return total;
} | /*
锟斤拷荼锟斤拷锟斤拷询锟斤拷录锟斤拷 |
public int calcuStartIndex(int pageNum,int onePageCount){
int startIndex=0;
String tempType=calcuDbType();
if(tempType!=null && tempType.equals("mysql")){
//if(dbType!=null && dbType.equals("mysql")){
startIndex=pageNum*onePageCount;
}else{
startIndex=pageNum*onePageCount+1;
}
return startIndex;
} | /*
锟斤拷锟斤拷锟揭筹拷锟绞硷拷锟铰嘉伙拷锟� |
public int updateObjByCondition(String tableName, String condition,String setStr) {
//JdbcTemplate jdbcTemplate = (JdbcTemplate) MicroDbHolder.getDbSource(dbName);
//String tableName=changeTableNameCase(otableName);
JdbcTemplate jdbcTemplate =getMicroJdbcTemplate();
String timeName=getTimeName();
if(autoOperTime){
setStr="update_time="+timeName+","+setStr;
}
String sql = "update " + tableName +" set "+setStr+ " where "+condition;
logger.debug(sql);
Integer retStatus=jdbcTemplate.update(sql);
return retStatus;
} | /*
锟斤拷荼锟斤拷锟斤拷锟斤拷 |
public int updateObjByCondition(String sql) {
//JdbcTemplate jdbcTemplate = (JdbcTemplate) MicroDbHolder.getDbSource(dbName);
JdbcTemplate jdbcTemplate =getMicroJdbcTemplate();
logger.debug(sql);
Integer retStatus=jdbcTemplate.update(sql);
return retStatus;
} | /*
锟斤拷锟絪ql锟斤拷锟斤拷 |
public int delObjByCondition(String tableName, String condition) {
//String tableName=changeTableNameCase(otableName);
//JdbcTemplate jdbcTemplate = (JdbcTemplate) MicroDbHolder.getDbSource(dbName);
JdbcTemplate jdbcTemplate =getMicroJdbcTemplate();
String sql = "delete from " + tableName + " where "+condition;
logger.debug(sql);
Integer retStatus=jdbcTemplate.update(sql);
return retStatus;
} | /*
锟斤拷荼锟斤拷锟缴撅拷锟� |
public int delObjByCondition(String tableName, String condition,Object[] paramArray,int[] typeArray) {
//JdbcTemplate jdbcTemplate = (JdbcTemplate) MicroDbHolder.getDbSource(dbName);
//String tableName=changeTableNameCase(otableName);
JdbcTemplate jdbcTemplate =getMicroJdbcTemplate();
String sql = "delete from " + tableName + " where "+condition;
logger.debug(sql);
logger.debug(Arrays.toString(paramArray));
Integer retStatus=jdbcTemplate.update(sql,paramArray,typeArray);
return retStatus;
} | /*
锟斤拷荼锟斤拷锟缴撅拷锟� |
public int insertObj(String tableName, String cols,String values,Object[] paramArray,int[] typeArray) {
//JdbcTemplate jdbcTemplate = (JdbcTemplate) MicroDbHolder.getDbSource(dbName);
//String tableName=changeTableNameCase(otableName);
JdbcTemplate jdbcTemplate =getMicroJdbcTemplate();
String timeName=getTimeName();
if(autoOperTime){
cols="create_time,update_time,"+cols;
values=timeName+","+timeName+","+values;
}
String sql = "insert into " + tableName + " ("+cols+") values ("+values+")";
logger.debug(sql);
logger.debug(Arrays.toString(paramArray));
Integer retStatus=jdbcTemplate.update(sql,paramArray,typeArray);
return retStatus;
} | /*
锟斤拷荼锟斤拷锟斤拷锟斤拷 |
@Override
public void handleServerEvent(ISFSEvent event) throws SFSException {
try {
super.handleServerEvent(event);
} catch(Exception e) {
throw new SFSException(e);
}
} | /* (non-Javadoc)
@see com.tvd12.ezyfox.sfs2x.serverhandler.UserZoneEventHandler#handleServerEvent(com.smartfoxserver.v2.core.ISFSEvent) |
public boolean verify(KeyStoreChooser keyStoreChooser, PublicKeyChooserByAlias publicKeyChooserByAlias, String message,
String signature) {
Base64EncodedVerifier verifier = cache.get(cacheKey(keyStoreChooser, publicKeyChooserByAlias));
if (verifier != null) {
return verifier.verify(message, signature);
}
Base64EncodedVerifierImpl verifierImpl = new Base64EncodedVerifierImpl();
verifierImpl.setAlgorithm(algorithm);
verifierImpl.setCharsetName(charsetName);
verifierImpl.setProvider(provider);
PublicKey publicKey = publicKeyRegistryByAlias.get(keyStoreChooser, publicKeyChooserByAlias);
if (publicKey == null) {
throw new SignatureException("public key not found: keyStoreName=" + keyStoreChooser.getKeyStoreName()
+ ", alias=" + publicKeyChooserByAlias.getAlias());
}
verifierImpl.setPublicKey(publicKey);
cache.put(cacheKey(keyStoreChooser, publicKeyChooserByAlias), verifierImpl);
return verifierImpl.verify(message, signature);
} | Verifies the authenticity of a message using a base64 encoded digital
signature.
@param keyStoreChooser the keystore chooser
@param publicKeyChooserByAlias the public key chooser
@param message the message to sign
@param signature the base64 encoded digital signature
@return true if the authenticity of the message is verified by the
digital signature |
public void print() {
System.out.println("========================= attrs =========================");
for(Map.Entry<String, Attribute> entry : this.attributes.entrySet()) {
Attribute attr = entry.getValue();
System.out.println(entry.getKey() + ": " + attr.getName() + ": " + entry.getValue());
}
} | print detail |
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.
@param indexVars Variable set over which to iterate.
@param config Clamped assignment.
@return Iterator. |
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.
@see edu.jhu.pacaya.gm.model.IndexForVc#getConfigIter |
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.
@param vars The variable set over which to iterate.
@param config An assignment to a subset of vars.
@return The configuration index. |
public static boolean match(String pattern, String path, boolean fullMatch) {
if (path.startsWith(PATH_SEPARATOR) != pattern.startsWith(PATH_SEPARATOR)) {
return false;
}
String[] pattDirs = split(pattern, PATH_SEPARATOR);
String[] pathDirs = split(path, PATH_SEPARATOR);
int pattIdxStart = 0;
int pattIdxEnd = pattDirs.length - 1;
int pathIdxStart = 0;
int pathIdxEnd = pathDirs.length - 1;
// Match all elements up to the first **
while (pattIdxStart <= pattIdxEnd && pathIdxStart <= pathIdxEnd) {
String patDir = pattDirs[pattIdxStart];
if ("**".equals(patDir)) {
break;
}
if (!matchStrings(patDir, pathDirs[pathIdxStart])) {
return false;
}
pattIdxStart++;
pathIdxStart++;
}
if (pathIdxStart > pathIdxEnd) {
// Path is exhausted, only match if rest of pattern is * or **'s
if (pattIdxStart > pattIdxEnd) {
return (pattern.endsWith(PATH_SEPARATOR) ?
path.endsWith(PATH_SEPARATOR) : !path.endsWith(PATH_SEPARATOR));
}
if (!fullMatch) {
return true;
}
if (pattIdxStart == pattIdxEnd && pattDirs[pattIdxStart].equals("*") &&
path.endsWith(PATH_SEPARATOR)) {
return true;
}
for (int i = pattIdxStart; i <= pattIdxEnd; i++) {
if (!pattDirs[i].equals("**")) {
return false;
}
}
return true;
}
else if (pattIdxStart > pattIdxEnd) {
// String not exhausted, but pattern is. Failure.
return false;
}
else if (!fullMatch && "**".equals(pattDirs[pattIdxStart])) {
// Path start definitely matches due to "**" part in pattern.
return true;
}
// up to last '**'
while (pattIdxStart <= pattIdxEnd && pathIdxStart <= pathIdxEnd) {
String patDir = pattDirs[pattIdxEnd];
if (patDir.equals("**")) {
break;
}
if (!matchStrings(patDir, pathDirs[pathIdxEnd])) {
return false;
}
pattIdxEnd--;
pathIdxEnd--;
}
if (pathIdxStart > pathIdxEnd) {
// String is exhausted
for (int i = pattIdxStart; i <= pattIdxEnd; i++) {
if (!pattDirs[i].equals("**")) {
return false;
}
}
return true;
}
while (pattIdxStart != pattIdxEnd && pathIdxStart <= pathIdxEnd) {
int patIdxTmp = -1;
for (int i = pattIdxStart + 1; i <= pattIdxEnd; i++) {
if (pattDirs[i].equals("**")) {
patIdxTmp = i;
break;
}
}
if (patIdxTmp == pattIdxStart + 1) {
// '**/**' situation, so skip one
pattIdxStart++;
continue;
}
// Find the pattern between padIdxStart & padIdxTmp in str between
// strIdxStart & strIdxEnd
int patLength = (patIdxTmp - pattIdxStart - 1);
int strLength = (pathIdxEnd - pathIdxStart + 1);
int foundIdx = -1;
strLoop:
for (int i = 0; i <= strLength - patLength; i++) {
for (int j = 0; j < patLength; j++) {
String subPat = pattDirs[pattIdxStart + j + 1];
String subStr = pathDirs[pathIdxStart + i + j];
if (!matchStrings(subPat, subStr)) {
continue strLoop;
}
}
foundIdx = pathIdxStart + i;
break;
}
if (foundIdx == -1) {
return false;
}
pattIdxStart = patIdxTmp;
pathIdxStart = foundIdx + patLength;
}
for (int i = pattIdxStart; i <= pattIdxEnd; i++) {
if (!pattDirs[i].equals("**")) {
return false;
}
}
return true;
} | Actually match the given <code>path</code> against the given <code>pattern</code>.
@param pattern the pattern to match against
@param path the path String to test
@param fullMatch whether a full pattern match is required
(else a pattern match as far as the given base path goes is sufficient)
@return <code>true</code> if the supplied <code>path</code> matched,
<code>false</code> if it didn't |
public static int libDaiIxToConfigId(int libDaiIx, int[] dims, Var[] varArray, VarSet vs) {
int[] config = Tensor.unravelIndexMatlab(libDaiIx, dims);
VarConfig vc = new VarConfig(varArray, config);
return vc.getConfigIndexOfSubset(vs);
} | converts the index to the index used in pacaya the difference is that the
vars in vs may be reordered compared to varArray and that pacaya
representation has the leftmost v in vs be the slowest changing while
libdai has the rightmost in varArray be the slowest changing; dims and
varArray are assumed to both correspond to the order of the variables
that is left to right (slowest changing last); the resulting index will
respect the order of var in vs which is vs.get(0) as the slowest
changing. |
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 |
@Override
public ResponseToRoom param(String name, Object value) {
addition.put(name, value);
return this;
} | /* (non-Javadoc)
@see com.tvd12.ezyfox.core.command.ResponseToRoom#param(java.lang.String, java.lang.Object) |
@Override
public <U extends ApiBaseUser> ResponseToRoom exclude(Collection<U> users) {
for(U user : users)
this.excludedUsers.add(user.getName());
return this;
} | /* (non-Javadoc)
@see com.tvd12.ezyfox.core.command.ResponseToRoom#exclude(java.util.Collection) |
@Override
public ResponseToRoom only(String... params) {
includedVars.addAll(Arrays.asList(params));
return this;
} | /* (non-Javadoc)
@see com.tvd12.ezyfox.core.command.ResponseToRoom#only(java.lang.String[]) |
@Override
public ResponseToRoom ignore(String... params) {
excludedVars.addAll(Arrays.asList(params));
return this;
} | /* (non-Javadoc)
@see com.tvd12.ezyfox.core.command.ResponseToRoom#ignore(java.lang.String[]) |
@SuppressWarnings("unchecked")
@Override
public Boolean execute() {
validateCommand();
Room room = CommandUtil.getSfsRoom(roomName, extension);
validateRoom(room);
List<User> recipients = room.getUserList();
for(String exUser : excludedUsers)
recipients.remove(room.getUserByName(exUser));
ISFSObject params = createResponseParams();
api.sendExtensionResponse(command, params, recipients, room, useUDP);
logResponse(params);
return Boolean.TRUE;
} | /* (non-Javadoc)
@see com.lagente.core.command.BaseCommand#execute() |
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.
@param keyStoreChooser the keystore chooser
@param privateKeyChooserByAlias the private key chooser by alias
@return the selected private key or null if not found |
@SuppressWarnings("unchecked")
@Override
public Boolean execute() {
api.logout(CommandUtil.getSfsUser(username, api));
return Boolean.TRUE;
} | /* (non-Javadoc)
@see com.tvd12.ezyfox.core.command.BaseCommand#execute() |
@Override
public VarTensor forward() {
MVecArray<VarTensor> xs = modIn.getOutput();
y = new VarTensor(s, new VarSet(), s.one());
for (int a=0; a<xs.dim(); a++) {
VarTensor x = xs.get(a);
y.prod(x);
}
return y;
} | Forward pass: p(y) = \prod_a \psi(y_a) where y_a is a {@link VarTensor} and we use variable-tensor product. |
@Override
public void backward() {
MVecArray<VarTensor> xs = modIn.getOutput();
MVecArray<VarTensor> xsAdj = modIn.getOutputAdj();
for (int a=0; a<xsAdj.dim(); a++) {
VarTensor xAdj = xsAdj.get(a);
// Compute the product of all the input factors except for a.
// We compute this cavity by brute force, rather than dividing out from the joint.
VarTensor prod = new VarTensor(yAdj);
for (int b=0; b<xsAdj.dim(); b++) {
if (a == b) { continue; }
prod.prod(xs.get(b));
}
xAdj.add(prod.getMarginal(xAdj.getVars(), false));
}
} | Backward pass: dG/d\psi(y_a) += dG/dp(y) dp(y)/d\psi(y_a)
dp(y)/d\psi(y_a) = \prod_{b \neq a} \psi_b(y_b) |
@Override
public void info(String msg, Throwable e) {
LoggerFactory.getLogger(from).info(msg, e);
} | /* (non-Javadoc)
@see com.tvd12.ezyfox.core.command.Log#info(java.lang.String, java.lang.Throwable) |
@Override
public void warn(String msg, Throwable e) {
LoggerFactory.getLogger(from).warn(msg);
} | /* (non-Javadoc)
@see com.tvd12.ezyfox.core.command.Log#warn(java.lang.String, java.lang.Throwable) |
@Override
public void error(String msg, Throwable e) {
LoggerFactory.getLogger(from).error(msg);
} | /* (non-Javadoc)
@see com.tvd12.ezyfox.core.command.Log#error(java.lang.String, java.lang.Throwable) |
@Override
public void info(String msg, Object... args) {
LoggerFactory.getLogger(from).info(msg, args);
} | /* (non-Javadoc)
@see com.tvd12.ezyfox.core.command.Log#info(java.lang.String, java.lang.Object[]) |
@Override
public void handleServerEvent(ISFSEvent event) throws SFSException {
Zone sfsZone = (Zone) event.getParameter(SFSEventParam.ZONE);
User sfsUser = (User) event.getParameter(SFSEventParam.USER);
User recipient = (User)event.getParameter(SFSEventParam.RECIPIENT);
String message = (String)event.getParameter(SFSEventParam.MESSAGE);
ISFSObject params = (ISFSObject)event.getParameter(SFSEventParam.OBJECT);
ApiBuddyMessageImpl buddyMessage = new ApiBuddyMessageImpl();
buddyMessage.setContent(message);
buddyMessage.setSender((ApiBaseUser)sfsUser.getProperty(APIKey.USER));
buddyMessage.setZone((ApiZone)sfsZone.getProperty(APIKey.ZONE));
buddyMessage.setRecipient((ApiBaseUser)recipient.getProperty(APIKey.USER));
notifyToHandlers(buddyMessage, params);
} | /* (non-Javadoc)
@see com.smartfoxserver.v2.extensions.IServerEventHandler#handleServerEvent(com.smartfoxserver.v2.core.ISFSEvent) |
@Override
public boolean exists(int row, int column) {
return row >= 0 && row < rowCount() && column >= 0 && column < columnCount();
} | ----------------------------------------------------------------------- |
@Override
public ImmutableCollection<V> values() {
Builder<V> builder = ImmutableList.builder();
for (Cell<V> cell : cells()) {
builder.add(cell.getValue());
}
return builder.build();
} | ----------------------------------------------------------------------- |
Cell<V> finder(int row, int column) {
@SuppressWarnings({ "unchecked", "rawtypes" })
Cell<V> finder = new ImmutableCell(row, column, "");
return finder;
} | ----------------------------------------------------------------------- |
public boolean verify(String publicKeyId, String message, String signature) {
Base64EncodedVerifier verifier = cache.get(publicKeyId);
if (verifier != null) {
return verifier.verify(message, signature);
}
Base64EncodedVerifierImpl verifierImpl = new Base64EncodedVerifierImpl();
verifierImpl.setAlgorithm(algorithm);
verifierImpl.setCharsetName(charsetName);
verifierImpl.setProvider(provider);
PublicKey publicKey = publicKeyMap.get(publicKeyId);
if (publicKey == null) {
throw new SignatureException("public key not found: publicKeyId=" + publicKeyId);
}
verifierImpl.setPublicKey(publicKey);
cache.put(publicKeyId, verifierImpl);
return verifierImpl.verify(message, signature);
} | Verifies the authenticity of a message using a base64 encoded digital
signature.
@param publicKeyId the logical name of the public key as configured in
the underlying mapping
@param message the original message to verify
@param signature the base64 encoded digital signature
@return true if the original message is verified by the digital signature
@see #setPublicKeyMap(java.util.Map) |
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 |
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 |
public static int[] unravelIndexFromStrides(int configIx, int... strides) {
int offset = 0;
int[] config = new int[strides.length];
// fill things out from slowest to fastest
for (int i = 0; i < strides.length; i++) {
// how many strides are we passed the offset
int ix = (configIx - offset) / strides[i];
config[i] = ix;
// move the offset
offset += ix * strides[i];
}
return config;
} | strides are given in order from left to right, slowest to fastest |
public double set(int[] indices, double val) {
checkIndices(indices);
int c = getConfigIdx(indices);
double prev = values[c];
values[c] = val;
return prev;
} | Sets the value of the entry corresponding to the given indices.
@param indices The indices of the multi-dimensional array.
@param val The value to set.
@return The previous value. |
public double add(int[] indices, double val) {
checkIndices(indices);
int c = getConfigIdx(indices);
double prev = values[c];
values[c] = s.plus(values[c], val);
return prev;
} | Adds the value to the entry corresponding to the given indices.
@param indices The indices of the multi-dimensional array.
@param val The value to add.
@return The previous value. |
public double subtract(int[] indices, double val) {
checkIndices(indices);
int c = getConfigIdx(indices);
double prev = values[c];
values[c] = s.minus(values[c], val);
return prev;
} | Subtracts the value to the entry corresponding to the given indices.
@param indices The indices of the multi-dimensional array.
@param val The value to subtract.
@return The previous value. |
public int getConfigIdx(int... indices) {
int c = 0;
for (int i=0; i<indices.length; i++) {
c += strides[i] * indices[i];
}
return c;
} | Gets the index into the values array that corresponds to the indices. |
public static int ravelIndex(int[] indices, int[] dims) {
int c = 0;
int[] strides = getStrides(dims);
for (int i=0; i<indices.length; i++) {
c += strides[i] * indices[i];
}
return c;
} | Gets the index into the values array that corresponds to the indices. |
public static int ravelIndexMatlab(int[] indices, int[] dims) {
indices = indices.clone();
ArrayUtils.reverse(indices);
dims = dims.clone();
ArrayUtils.reverse(dims);
return ravelIndex(indices, dims);
} | Gets the index into the values array that corresponds to the indices. |
public double setValue(int idx, double val) {
double prev = values[idx];
values[idx] = val;
return prev;
} | Sets the value of the idx'th entry. |
public void addValue(int idx, double val) {
values[idx] = s.plus(values[idx], val);
} | Adds the value to the idx'th entry. |
public void subtractValue(int idx, double val) {
values[idx] = s.minus(values[idx], val);
} | Subtracts the value from the idx'th entry. |
public void multiplyValue(int idx, double val) {
values[idx] = s.times(values[idx], val);
} | Multiplies the value with the idx'th entry. |
public void divideValue(int idx, double val) {
values[idx] = s.divide(values[idx], val);
} | Divides the value from the idx'th entry. |
public void add(double addend) {
for (int c = 0; c < this.values.length; c++) {
addValue(c, addend);
}
} | Add the addend to each value. |
public void multiply(double val) {
for (int c = 0; c < this.values.length; c++) {
multiplyValue(c, val);
}
} | Scale each value by lambda. |
public void divide(double val) {
for (int c = 0; c < this.values.length; c++) {
divideValue(c, val);
}
} | Divide each value by lambda. |
public void elemAdd(Tensor other) {
checkEqualSize(this, other);
for (int c = 0; c < this.values.length; c++) {
addValue(c, other.values[c]);
}
} | Adds a factor elementwise to this one.
@param other The addend.
@throws IllegalArgumentException If the two tensors have different sizes. |
@Override
public void elemAdd(MVec addend) {
if (addend instanceof Tensor) {
elemAdd((Tensor)addend);
} else {
throw new IllegalArgumentException("Addend must be of type " + this.getClass());
}
} | Implements {@link MVec#elemAdd(MVec)}. |
public void elemSubtract(Tensor other) {
checkEqualSize(this, other);
for (int c = 0; c < this.values.length; c++) {
subtractValue(c, other.values[c]);
}
} | Subtracts a factor elementwise from this one.
@param other The subtrahend.
@throws IllegalArgumentException If the two tensors have different sizes. |
public void elemMultiply(Tensor other) {
checkEqualSize(this, other);
for (int c = 0; c < this.values.length; c++) {
multiplyValue(c, other.values[c]);
}
} | Multiply a factor elementwise with this one.
@param other The multiplier.
@throws IllegalArgumentException If the two tensors have different sizes. |
public void elemDivide(Tensor other) {
checkEqualSize(this, other);
for (int c = 0; c < this.values.length; c++) {
divideValue(c, other.values[c]);
}
} | Divide a factor elementwise from this one.
@param other The divisor.
@throws IllegalArgumentException If the two tensors have different sizes. |
public void elemApply(Lambda.FnIntDoubleToDouble fn) {
for (int c=0; c<this.values.length; c++) {
this.values[c] = fn.call(c, this.values[c]);
}
} | Adds a factor elementwise to this one.
@param other The addend.
@throws IllegalArgumentException If the two tensors have different sizes. |
public void exp() {
for (int c=0; c<this.values.length; c++) {
this.values[c] = s.exp(this.values[c]);
}
} | Take the exp of each entry. |
public void log() {
for (int c=0; c<this.values.length; c++) {
this.values[c] = s.log(this.values[c]);
}
} | Take the log of each entry. |
public double normalize() {
double propSum = this.getSum();
if (propSum == s.zero()) {
this.fill(s.divide(s.one(), s.fromReal(values.length)));
} else if (propSum == s.posInf()) {
int count = DoubleArrays.count(values, s.posInf());
if (count == 0) {
throw new RuntimeException("Unable to normalize since sum is infinite but contains no infinities: " + Arrays.toString(values));
}
double constant = s.divide(s.one(), s.fromReal(count));
for (int d=0; d<values.length; d++) {
if (values[d] == s.posInf()) {
values[d] = constant;
} else {
values[d] = s.zero();
}
}
} else {
this.divide(propSum);
assert !this.containsNaN();
}
return propSum;
} | Normalizes the values so that they sum to 1 |
public double getSum() {
double sum = s.zero();
for (int c = 0; c < this.values.length; c++) {
sum = s.plus(sum, values[c]);
}
return sum;
} | Gets the sum of all the entries in this tensor. |
public double getProd() {
double prod = s.one();
for (int c = 0; c < this.values.length; c++) {
prod = s.times(prod, values[c]);
}
return prod;
} | Gets the product of all the entries in this tensor. |
public double getMax() {
double max = s.minValue();
for (int c = 0; c < this.values.length; c++) {
if (s.gte(values[c], max)) {
max = values[c];
}
}
return max;
} | Gets the max value in the tensor. |
public int getArgmaxConfigId() {
int argmax = -1;
double max = s.minValue();
for (int c = 0; c < this.values.length; c++) {
if (s.gte(values[c], max)) {
max = values[c];
argmax = c;
}
}
return argmax;
} | Gets the ID of the configuration with the maximum value. |
public double getInfNorm() {
double max = s.negInf();
for (int c = 0; c < this.values.length; c++) {
double abs = s.abs(values[c]);
if (s.gte(abs, max)) {
max = abs;
}
}
return max;
} | Gets the infinity norm of this tensor. Defined as the maximum absolute
value of the entries. |
public double getDotProduct(Tensor other) {
checkEqualSize(this, other);
double dot = s.zero();
for (int c = 0; c < this.values.length; c++) {
dot = s.plus(dot, s.times(this.values[c], other.values[c]));
}
return dot;
} | Computes the sum of the entries of the pointwise product of two tensors with identical domains. |
public void set(Tensor other) {
checkEqualSize(this, other);
this.dims = IntArrays.copyOf(other.dims);
DoubleArrays.copy(other.values, this.values);
} | Sets the dimensions and values to be the same as the given tensor.
Assumes that the size of the two vectors are equal. |
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.
@param dim The dimension to treat as fixed.
@param idx The index of that dimension to fix.
@return The sub-tensor selected. |
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.
This is the larger tensor (i.e. the augend).
@param addend The smaller tensor (i.e. the addend)
@param dim The dimension which will be treated as fixed on the larger tensor.
@param idx The index at which that dimension will be fixed. |
public boolean containsNaN() {
for (int i = 0; i < values.length; i++) {
if (s.isNaN(values[i])) {
return true;
}
}
return false;
} | Returns true if this tensor contains any NaNs. |
public VarConfig getVarConfig(int configIndex) {
// Configuration as an array of ints, one for each variable.
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.
@param configIndex The config index.
@return The variable configuration. |
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. |
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 |
public static List<Var> getVarsOfType(List<Var> vars, VarType type) {
ArrayList<Var> subset = new ArrayList<Var>();
for (Var v : vars) {
if (v.getType() == type) {
subset.add(v);
}
}
return subset;
} | Gets the subset of vars with the specified type. |
public static VarSet getVarsOfType(VarSet vars, VarType type) {
VarSet subset = new VarSet();
for (Var v : vars) {
if (v.getType() == type) {
subset.add(v);
}
}
return subset;
} | Gets the subset of vars with the specified type. |
@Override
@SuppressWarnings("unchecked")
public T forward() {
T x = modIn.getOutput();
y = (T) x.copyAndConvertAlgebra(s);
return y;
} | Foward pass: y[i] = x[i].
x[i] is converted from a real to its semiring form. |
@Override
@SuppressWarnings("unchecked")
public void backward() {
T xAdj = modIn.getOutputAdj();
T tmp = (T) yAdj.copyAndConvertAlgebra(modIn.getAlgebra());
xAdj.elemAdd(tmp);
} | Backward pass: dG/dx_i = dG/dy_i.
dG/dy_i is converted to a real from the semiring form. |
@Override
public <U extends ApiBaseUser> Response recipients(Collection<U> users) {
for(ApiBaseUser user : users)
this.usernames.add(user.getName());
return this;
} | /* (non-Javadoc)
@see com.tvd12.ezyfox.core.command.Response#recipients(java.util.List) |
@Override
public Response recipients(Iterable<String> usernames) {
this.usernames.addAll(Sets.newHashSet(usernames));
return this;
} | /* (non-Javadoc)
@see com.tvd12.ezyfox.core.command.Response#recipients(java.lang.Iterable) |
@Override
public <U extends ApiBaseUser> Response exclude(Collection<U> users) {
for(U user : users)
this.usernames.remove(user.getName());
return this;
} | /* (non-Javadoc)
@see com.tvd12.ezyfox.core.command.Response#exclude(java.util.Collection) |
@SuppressWarnings("unchecked")
@Override
public Boolean execute() {
validateCommand();
List<User> users = new ArrayList<>();
for(String username : usernames) {
User sfsUser = CommandUtil.getSfsUser(username, api);
if(sfsUser != null) users.add(sfsUser);
}
ISFSObject params = createResponseParams();
extension.send(command, params, users, useUDP);
logResponse(params);
return Boolean.TRUE;
} | /* (non-Javadoc)
@see com.lagente.core.command.BaseCommand#execute() |
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. |
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) {
// Redirect stderr and stdout to logFile
// TODO: in Java 7, use redirectOutput(Redirect.to(logFile))
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) {
// Ignore new exceptions
}
throw new RuntimeException("Exception thrown while trying to exec command " + System.cmdToString(cmdArray) + "\n"
+ tail, e);
}
} | Returns the Process which contains the exit code. |
@SuppressWarnings("unchecked")
@Override
public <T> T by(String name) {
Room room = CommandUtil.getSfsRoom(name, extension);
if(room == null) return null;
return (T)room.getProperty(APIKey.ROOM);
} | /* (non-Javadoc)
@see com.tvd12.ezyfox.core.command.GetRoom#by(java.lang.String) |
@SuppressWarnings("unchecked")
@Override
public <T> T by(int id) {
Room sfsRoom = extension.getParentZone().getRoomById(id);
if(sfsRoom == null) return null;
return (T) sfsRoom.getProperty(APIKey.ROOM);
} | /* (non-Javadoc)
@see com.tvd12.ezyfox.core.command.GetRoom#by(int) |
@SuppressWarnings({ "unchecked"})
@Override
public <T> T by(ApiBaseUser user) {
User sfsUser = CommandUtil.getSfsUser(user, api);
if(sfsUser == null) return null;
Room sfsRoom = sfsUser.getLastJoinedRoom();
if(sfsRoom == null) return null;
return (T)sfsRoom.getProperty(APIKey.ROOM);
} | /* (non-Javadoc)
@see com.tvd12.ezyfox.core.command.GetRoom#by(com.tvd12.ezyfox.core.entities.ApiBaseUser) |
@Override
public Beliefs forward() {
// Initialization.
initForward();
// Message passing.
loops:
for (int iter=-1; iter < prm.maxIterations; iter++) {
List<Object> order = sched.getOrder(iter, fg);
for (Object item : order) {
List<Integer> edges = CachingBpSchedule.toEdgeList(fg, item);
List<?> elems = CachingBpSchedule.toFactorEdgeList(item);
TapeEntry te = prm.keepTape ? new TapeEntry(item, edges) : null;
for (Object elem : elems) {
if (elem instanceof Integer) {
forwardCreateMessage((Integer) elem);
} else if (elem instanceof AutodiffGlobalFactor) {
forwardGlobalFacToVar((AutodiffGlobalFactor) elem, te);
} else {
throw new RuntimeException("Unsupported type in schedule: " + elem.getClass());
}
}
for (Integer edge : edges) {
normalizeAndAddToTape(edge, te);
}
for (Integer edge : edges) {
forwardSendMessage(edge, iter);
}
if (prm.keepTape) { tape.add(te); }
if (isConverged()) {
// Stop on convergence: Break out of inner and outer loop.
log.trace("Stopping on convergence. Iterations = {}", (iter+1));
break loops;
}
}
maybeWriteAllBeliefs(iter);
}
log.trace("Oscillation rate: {}", ((double) oscillationCount.get() / sendCount.get()));
forwardVarAndFacBeliefs();
b = new Beliefs(varBeliefs, facBeliefs);
return b;
} | /* ---------------------------- BEGIN: Forward Pass Methods --------------------- |
private void forwardSendMessage(int edge, int iter) {
// Update the residual
double oldResidual = residuals[edge];
residuals[edge] = smartResidual(msgs[edge], newMsgs[edge], edge);
if (oldResidual > prm.convergenceThreshold && residuals[edge] <= prm.convergenceThreshold) {
// This message has (newly) converged.
numConverged ++;
}
if (oldResidual <= prm.convergenceThreshold && residuals[edge] > prm.convergenceThreshold) {
// This message was marked as converged, but is no longer converged.
numConverged--;
}
// Check for oscillation. Did the argmax change?
if (log.isTraceEnabled() && iter > 0) {
if (msgs[edge].getArgmaxConfigId() != newMsgs[edge].getArgmaxConfigId()) {
oscillationCount.incrementAndGet();
}
sendCount.incrementAndGet();
log.trace("Residual: {} {}", fg.edgeToString(edge), residuals[edge]);
}
// Update the cached belief.
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];
}
}
// Send message: Just swap the pointers to the current message and the new message, so
// that we don't have to create a new factor object.
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.
@param edge The edge over which the message should be sent.
@param iter The current iteration. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.