code
stringlengths 67
466k
| docstring
stringlengths 1
13.2k
|
---|---|
private void notifyListener(RequestResponseClass clazz,
ISFSObject params, User user, Object userAgent) throws Exception {
Object listener = clazz.newInstance();
setDataToListener(clazz, listener, params);
invokeExecuteMethod(clazz.getExecuteMethod(), listener, userAgent);
responseClient(clazz, listener, user);
} | Notify all listeners
@param clazz structure of listener class
@param params request parameters
@param user request user
@param userAgent user agent's object
@throws Exception when has any error from listener |
protected void invokeExecuteMethod(Method method, Object listener, Object userAgent) {
ReflectMethodUtil.invokeExecuteMethod(
method, listener, context, userAgent);
} | Invoke the execute method
@param method the execute method
@param listener the listener
@param userAgent the user agent object |
private Object checkUserAgent(RequestResponseClass clazz, ApiUser userAgent) {
if(clazz.getUserClass().isAssignableFrom(userAgent.getClass()))
return userAgent;
return UserAgentUtil.getGameUser(userAgent, clazz.getUserClass());
} | For each listener, we may use a class of user agent, so we need check it
@param clazz structure of listener class
@param userAgent user agent object
@return instance of user agent |
private void responseClient(RequestResponseClass clazz, Object listener, User user) {
if(!clazz.isResponseToClient()) return;
String command = clazz.getResponseCommand();
ISFSObject params = (ISFSObject) new ParamTransformer(context)
.transform(listener).getObject();
send(command, params, user);
} | Response information to client
@param clazz structure of listener class
@param listener listener object
@param user smartfox user |
private void responseErrorToClient(Exception ex, User user) {
BadRequestException e = getBadRequestException(ex);
if(!e.isSendToClient()) return;
ISFSObject params = new SFSObject();
params.putUtfString(APIKey.MESSAGE, e.getReason());
params.putInt(APIKey.CODE, e.getCode());
send(APIKey.ERROR, params, user);
} | Response error to client
@param ex the exception
@param user the recipient |
private BadRequestException getBadRequestException(Exception ex) {
return (BadRequestException) ExceptionUtils
.getThrowables(ex)[ExceptionUtils.indexOfThrowable(ex, BadRequestException.class)];
} | Get BadRequestException from the exception
@param ex the exception
@return BadRequestException |
@Override
protected void send(String cmd, ISFSObject params, User recipient) {
super.send(cmd, params, recipient);
logResponse(cmd, params);
} | /* (non-Javadoc)
@see com.smartfoxserver.v2.extensions.BaseClientRequestHandler#send(java.lang.String, com.smartfoxserver.v2.entities.data.ISFSObject, com.smartfoxserver.v2.entities.User) |
@Override
protected void config() {
addExtendedEventHandler(
ServerEvent.ROOM_USER_RECONNECT,
new RoomUserReconnectEventHandler(getAppContext()));
addExtendedEventHandler(
ServerEvent.ROOM_USER_DISCONNECT,
new RoomUserDisconnectEventHandler(getAppContext()));
} | /* (non-Javadoc)
@see com.tvd12.ezyfox.sfs2x.extension.BaseExtension#config() |
@Override
protected BaseContext createContext() {
AppContextImpl context = getAppContext();
RoomContextImpl answer = new RoomContextImpl();
answer.init(context, getClass());
return answer;
} | /*
(non-Javadoc)
@see com.tvd12.ezyfox.sfs2x.extension.BaseExtension#createContext() |
@Override
public void handleEvent(String event, Map<ISFSEventParam, Object> params) {
handleExtendedEvent(event, new SFSEvent(null, params));
} | /*
(non-Javadoc)
@see com.tvd12.ezyfox.sfs2x.serverhandler.InternalEventHandler#handleEvent(java.lang.String, java.util.Map) |
@SuppressWarnings("unchecked")
@Override
public Boolean execute() {
api.leaveRoom(CommandUtil.getSfsUser(user, api),
CommandUtil.getSfsRoom(room, extension),
fireClientEvent, fireServerEvent);
return Boolean.TRUE;
} | /* (non-Javadoc)
@see com.tvd12.ezyfox.core.command.BaseCommand#execute() |
@SuppressWarnings("unchecked")
@Override
public Boolean execute() {
try {
api.createNPC(username,
SmartFoxServer.getInstance()
.getZoneManager().getZoneByName(zone),
forceLogin);
} catch (SFSLoginException e) {
throw new IllegalStateException(e);
}
return Boolean.TRUE;
} | /* (non-Javadoc)
@see com.tvd12.ezyfox.core.command.BaseCommand#execute() |
public <T extends Variable> Object deserialize(AgentClassWrapper wrapper,
List<T> variables) {
return deserialize(wrapper, wrapper.newInstance(), variables);
} | Deserialize list of smartfox variables to agent object
@param <T> the variable type
@param wrapper structure of agent class
@param variables list of smartfox variables
@return a agent object |
protected <T extends Variable> Object deserialize(AgentClassWrapper wrapper,
Object agent, List<T> variables) {
for(T variable : variables) {
SetterMethodCover method = wrapper.getMethod(variable.getName());
if(method != null)
method.invoke(agent, getValue(method, variable));
}
return agent;
} | Deserialize list of smartfox variables to agent object
@param <T> the variable type
@param wrapper structure of agent class
@param agent the agent object
@param variables list of smartfox variables
@return the agent object |
protected Object getValue(SetterMethodCover method, Variable variable) {
if(method.isTwoDimensionsArray())
return assignValuesToTwoDimensionsArray(method, variable.getSFSArrayValue());
if(method.isArray())
return assignValuesToArray(method, variable);
if(method.isColection())
return assignValuesToCollection(method, variable);
if(method.isObject())
return assignValuesToObject(method, variable.getSFSObjectValue());
if(method.isByte())
return variable.getIntValue().byteValue();
if(method.isChar())
return (char)variable.getIntValue().byteValue();
if(method.isFloat())
return variable.getDoubleValue().floatValue();
if(method.isLong())
return variable.getDoubleValue().longValue();
if(method.isShort())
return variable.getIntValue().shortValue();
return variable.getValue();
} | Get value from the variable
@param method structure of setter method
@param variable the variable
@return a value |
public ISFSObject object2params(ClassUnwrapper unwrapper,
Object object, ISFSObject result) {
List<GetterMethodCover> methods = unwrapper.getMethods();
for(GetterMethodCover method : methods) {
Object value = method.invoke(object);
if(value == null)
continue;
parseMethod(value, method, result);
}
return result;
} | Serialize a java object to a SFSObject
@param unwrapper structure of java class
@param object java object
@param result the SFSObject
@return the SFSObject |
protected ISFSObject parseMethods(ClassUnwrapper unwrapper,
Object object) {
return object2params(unwrapper, object, new SFSObject());
} | Invoke getter method and add returned value to SFSObject
@param unwrapper structure of java class
@param object the java object
@return the SFSObject |
@SuppressWarnings("rawtypes")
protected void parseMethod(Object value, GetterMethodCover method,
ISFSObject sfsObject) {
Object answer = value;
if(method.isColection()) {
answer = parseCollection(method, (Collection)value);
}
else if(method.isTwoDimensionsArray()) {
answer = parseTwoDimensionsArray(method, value);
}
else if(method.isArray()) {
answer = parseArray(method, value);
}
else if(method.isObject()) {
answer = parseObject(method, value);
}
else if(method.isChar()) {
answer = (byte)(((Character)value).charValue());
}
SFSDataType type = getSFSDataType(method);
sfsObject.put(method.getKey(), new SFSDataWrapper(type, answer));
} | Serialize a java object to a SFSObject
@param value value to parse
@param method structure of getter method
@param sfsObject the SFSObject |
protected Object parseTwoDimensionsArray(GetterMethodCover method,
Object array) {
ISFSArray answer = new SFSArray();
int size = Array.getLength(array);
for(int i = 0 ; i < size ; i++) {
SFSDataType dtype = getSFSArrayDataType(method);
Object value = parseArrayOfTwoDimensionsArray(method, Array.get(array, i));
answer.add(new SFSDataWrapper(dtype, value));
}
return answer;
} | Serialize two-dimensions array to ISFSArray
@param method method's structure
@param array the two-dimensions array
@return ISFSArray object |
protected Object parseArray(GetterMethodCover method,
Object array) {
if(method.isObjectArray()) {
return parseObjectArray(method, (Object[])array);
}
else if(method.isPrimitiveBooleanArray()) {
return primitiveArrayToBoolCollection((boolean[])array);
}
else if(method.isPrimitiveCharArray()) {
return charArrayToByteArray((char[])array);
}
else if(method.isPrimitiveDoubleArray()) {
return primitiveArrayToDoubleCollection((double[])array);
}
else if(method.isPrimitiveFloatArray()) {
return primitiveArrayToFloatCollection((float[])array);
}
else if(method.isPrimitiveIntArray()) {
return primitiveArrayToIntCollection((int[])array);
}
else if(method.isPrimitiveLongArray()) {
return primitiveArrayToLongCollection((long[])array);
}
else if(method.isPrimitiveShortArray()) {
return primitiveArrayToShortCollection((short[])array);
}
else if(method.isStringArray()) {
return stringArrayToCollection((String[])array);
}
else if(method.isWrapperBooleanArray()) {
return wrapperArrayToCollection((Boolean[])array);
}
else if(method.isWrapperByteArray()) {
return toPrimitiveByteArray((Byte[])array);
}
else if(method.isWrapperCharArray()) {
return charWrapperArrayToPrimitiveByteArray((Character[])array);
}
else if(method.isWrapperDoubleArray()) {
return wrapperArrayToCollection((Double[])array);
}
else if(method.isWrapperFloatArray()) {
return wrapperArrayToCollection((Float[])array);
}
else if(method.isWrapperIntArray()) {
return wrapperArrayToCollection((Integer[])array);
}
else if(method.isWrapperLongArray()) {
return wrapperArrayToCollection((Long[])array);
}
else if(method.isWrapperShortArray()) {
return wrapperArrayToCollection((Short[])array);
}
return array;
} | Convert array of values to collection of values
@param method structure of getter method
@param array the array of values
@return the collection of values |
@SuppressWarnings({ "rawtypes", "unchecked" })
protected Object parseCollection(GetterMethodCover method,
Collection collection) {
if(method.isArrayObjectCollection()) {
return parseArrayObjectCollection(method, collection);
}
else if(method.isObjectCollection()) {
return parseObjectCollection(method, collection);
}
else if(method.isByteCollection()) {
return collectionToPrimitiveByteArray(collection);
}
else if(method.isCharCollection()) {
return charCollectionToPrimitiveByteArray(collection);
}
else if(method.isArrayCollection()) {
return parseArrayCollection(method, collection);
}
return collection;
} | Parse collection of values and get the value mapped to smartfox value
@param method structure of getter method
@param collection collection of value
@return the value after parsed |
protected ISFSObject parseObject(GetterMethodCover method,
Object object) {
return object2params(method.getReturnClass(),
object);
} | Serialize a java object to a SFSObject
@param method structure of getter method
@param object object to serialize
@return the SFSObject |
protected ISFSArray parseObjectArray(GetterMethodCover method,
Object[] array) {
return parseObjectArray(method.getReturnClass(),
array);
} | Serialize array of object to a SFSArray
@param method structure of getter method
@param array array of objects
@return the SFSArray |
private ISFSArray parseObjectArray(ClassUnwrapper unwrapper,
Object[] array) {
ISFSArray result = new SFSArray();
for(Object obj : array) {
result.addSFSObject(object2params(unwrapper, obj));
}
return result;
} | Serialize array of object to a SFSArray
@param unwrapper structure of java class
@param array array of objects
@return the SFSArray |
@SuppressWarnings({ "rawtypes" })
protected ISFSArray parseObjectCollection(GetterMethodCover method,
Collection collection) {
ISFSArray result = new SFSArray();
for(Object obj : collection) {
result.addSFSObject(parseObject(
method, obj));
}
return result;
} | Serialize collection of objects to a SFSArray
@param method structure of getter method
@param collection collection of objects
@return the SFSArray |
@SuppressWarnings({ "rawtypes" })
protected ISFSArray parseArrayObjectCollection(GetterMethodCover method,
Collection collection) {
ISFSArray result = new SFSArray();
for(Object obj : collection) {
result.addSFSArray(parseObjectArray(
method,
(Object[])obj));
}
return result;
} | Serialize collection of java array object to a SFSArray
@param method structure of getter method
@param collection collection of java objects
@return the SFSArray |
@SuppressWarnings("rawtypes")
protected ISFSArray parseArrayCollection(GetterMethodCover method,
Collection collection) {
ISFSArray result = new SFSArray();
SFSDataType dataType = ParamTypeParser
.getParamType(method.getGenericType());
Class<?> type = method.getGenericType().getComponentType();
for(Object obj : collection) {
Object value = obj;
if(isPrimitiveChar(type)) {
value = charArrayToByteArray((char[])value);
}
else if(isWrapperByte(type)) {
value = toPrimitiveByteArray((Byte[])value);
}
else if(isWrapperChar(type)) {
value = charWrapperArrayToPrimitiveByteArray((Character[])value);
}
else {
value = arrayToList(value);
}
result.add(new SFSDataWrapper(dataType, value));
}
return result;
} | Serialize collection of array to a SFSArray
@param method structure of getter method
@param collection collection of objects
@return the SFSArray |
private SFSDataType getSFSDataType(MethodCover method) {
if(method.isBoolean())
return SFSDataType.BOOL;
if(method.isByte())
return SFSDataType.BYTE;
if(method.isChar())
return SFSDataType.BYTE;
if(method.isDouble())
return SFSDataType.DOUBLE;
if(method.isFloat())
return SFSDataType.FLOAT;
if(method.isInt())
return SFSDataType.INT;
if(method.isLong())
return SFSDataType.LONG;
if(method.isShort())
return SFSDataType.SHORT;
if(method.isString())
return SFSDataType.UTF_STRING;
if(method.isObject())
return SFSDataType.SFS_OBJECT;
if(method.isBooleanArray())
return SFSDataType.BOOL_ARRAY;
if(method.isByteArray())
return SFSDataType.BYTE_ARRAY;
if(method.isCharArray())
return SFSDataType.BYTE_ARRAY;
if(method.isDoubleArray())
return SFSDataType.DOUBLE_ARRAY;
if(method.isFloatArray())
return SFSDataType.FLOAT_ARRAY;
if(method.isIntArray())
return SFSDataType.INT_ARRAY;
if(method.isLongArray())
return SFSDataType.LONG_ARRAY;
if(method.isShortArray())
return SFSDataType.SHORT_ARRAY;
if(method.isStringArray())
return SFSDataType.UTF_STRING_ARRAY;
if(method.isObjectArray())
return SFSDataType.SFS_ARRAY;
if(method.isBooleanCollection())
return SFSDataType.BOOL_ARRAY;
if(method.isByteCollection())
return SFSDataType.BYTE_ARRAY;
if(method.isCharCollection())
return SFSDataType.BYTE_ARRAY;
if(method.isDoubleCollection())
return SFSDataType.DOUBLE_ARRAY;
if(method.isFloatCollection())
return SFSDataType.FLOAT_ARRAY;
if(method.isIntCollection())
return SFSDataType.INT_ARRAY;
if(method.isLongCollection())
return SFSDataType.LONG_ARRAY;
if(method.isShortCollection())
return SFSDataType.SHORT_ARRAY;
if(method.isStringCollection())
return SFSDataType.UTF_STRING_ARRAY;
if(method.isObjectCollection())
return SFSDataType.SFS_ARRAY;
if(method.isArrayObjectCollection())
return SFSDataType.SFS_ARRAY;
return SFSDataType.SFS_ARRAY;
} | Get SFSDataType mapped to returned value type of getter method
@param method structure of getter method
@return the SFSDataType |
@SuppressWarnings("unchecked")
@Override
public Boolean execute() {
try {
api.changeRoomPassword(CommandUtil.getSfsUser(owner, api),
CommandUtil.getSfsRoom(targetRoom, extension),
password);
} catch (SFSRoomException e) {
throw new IllegalStateException(e);
}
return Boolean.TRUE;
} | /* (non-Javadoc)
@see com.tvd12.ezyfox.core.command.BaseCommand#execute() |
protected void initContext() {
context = createContext();
SmartFoxContext sfsContext = (SmartFoxContext)context;
sfsContext.setApi(getApi());
sfsContext.setExtension(this);
} | Initialize application context |
protected void addClientRequestHandlers() {
Set<String> commands =
context.getClientRequestCommands();
for(String command : commands)
addClientRequestHandler(command);
} | Add client request handlers |
@Override
protected void addRequestHandler(String requestId, IClientRequestHandler requestHandler) {
super.addRequestHandler(requestId, requestHandler);
registerClientRequestHandler(requestId, requestHandler);
} | /* (non-Javadoc)
@see com.smartfoxserver.v2.extensions.SFSExtension#addRequestHandler(java.lang.String, com.smartfoxserver.v2.extensions.IClientRequestHandler) |
public byte[] sign(byte[] message) {
try {
// this way signatureInstance should be thread safe
final Signature signatureInstance = ((provider == null) || (provider.length() == 0)) ? Signature
.getInstance(algorithm) : Signature.getInstance(algorithm, provider);
signatureInstance.initSign(privateKey);
signatureInstance.update(message);
return signatureInstance.sign();
} catch (Exception e) {
throw new SignatureException("error generating the signature: algorithm=" + algorithm, e);
}
} | Signs a message.
@param message the message to sign
@return the signature |
@Override
public void handleServerEvent(ISFSEvent event) throws SFSException {
super.handleServerEvent(event);
if(context.isAutoResponse(APIEvent.ZONE_JOIN))
send(APIEvent.ZONE_JOIN, new SFSObject(), (User)event.getParameter(SFSEventParam.USER));
} | /* (non-Javadoc)
@see com.tvd12.ezyfox.sfs2x.serverhandler.UserZoneEventHandler#handleServerEvent(com.smartfoxserver.v2.core.ISFSEvent) |
protected ApiUser createUserAgent(User sfsUser) {
ApiUser answer = UserAgentFactory.newUserAgent(
sfsUser.getName(),
context.getUserAgentClass(),
context.getGameUserAgentClasses());
sfsUser.setProperty(APIKey.USER, answer);
answer.setId(sfsUser.getId());
answer.setIp(sfsUser.getIpAddress());
answer.setSession(new ApiSessionImpl(sfsUser.getSession()));
answer.setCommand(context.command(UserInfo.class).user(sfsUser.getId()));
return answer;
} | Create user agent object
@param sfsUser smartfox user object
@return user agent object |
public static Module<Factors> getFactorsModule(FactorGraph fg, Algebra s) {
ForwardOnlyFactorsModule fm = new ForwardOnlyFactorsModule(null, fg, s);
fm.forward();
return fm;
} | Constructs a factors module and runs the forward computation. |
public FactorGraph getClamped(VarConfig clampVars) {
FactorGraph clmpFg = new FactorGraph();
// Add ALL the original variables to the clamped factor graph.
for (Var v : this.getVars()) {
clmpFg.addVar(v);
}
// Add ALL the original factors to the clamped factor graph.
for (Factor origFactor : this.getFactors()) {
clmpFg.addFactor(origFactor);
}
// Add unary factors to the clamped variables to ensure they take on the correct value.
for (Var v : clampVars.getVars()) {
// TODO: We could skip these (cautiously) if there's already a
// ClampFactor attached to this variable.
int c = clampVars.getState(v);
clmpFg.addFactor(new ClampFactor(v, c));
}
return clmpFg;
} | Gets a new factor graph, identical to this one, except that specified variables are clamped
to their values. This is accomplished by adding a unary factor on each clamped variable. The
original K factors are preserved in order with IDs 1...K.
@param clampVars The variables to clamp. |
public void addFactor(Factor factor) {
int id = factor.getId();
boolean alreadyAdded = (0 <= id && id < factors.size());
if (alreadyAdded) {
if (factors.get(id) != factor) {
throw new IllegalStateException("Factor id already set, but factor not yet added.");
}
} else {
// Factor was not yet in the factor graph.
//
// Check and set the id.
if (id != -1 && id != factors.size()) {
throw new IllegalStateException("Factor id already set, but incorrect: " + id);
}
factor.setId(factors.size());
// Add the factor.
factors.add(factor);
// Add each variable...
for (Var var : factor.getVars()) {
// Add the variable.
addVar(var);
numUndirEdges++;
}
if (bg != null) { log.warn("Discarding BipartiteGraph. This may indicate inefficiency."); }
bg = null;
}
} | Adds a factor to this factor graph, if not already present, additionally adding any variables
in its VarSet which have not already been added.
@param var The factor to add.
@return The node for this factor. |
public void addVar(Var var) {
int id = var.getId();
boolean alreadyAdded = (0 <= id && id < vars.size());
if (alreadyAdded) {
if (vars.get(id) != var) {
throw new IllegalStateException("Var id already set, but factor not yet added.");
}
} else {
// Var was not yet in the factor graph.
//
// Check and set the id.
if (id != -1 && id != vars.size()) {
throw new IllegalStateException("Var id already set, but incorrect: " + id);
}
var.setId(vars.size());
// Add the Var.
vars.add(var);
if (bg != null) { log.warn("Discarding BipartiteGraph. This may indicate inefficiency."); }
bg = null;
}
} | Adds a variable to this factor graph, if not already present.
@param var The variable to add.
@return The node for this variable. |
public FgModel train(LogLinearXYData data) {
IntObjectBimap<String> alphabet = data.getFeatAlphabet();
FgExampleList list = getData(data);
log.info("Number of train instances: " + list.size());
log.info("Number of model parameters: " + alphabet.size());
FgModel model = new FgModel(alphabet.size(), new StringIterable(alphabet.getObjects()));
CrfTrainer trainer = new CrfTrainer(prm.crfPrm);
trainer.train(model, list);
return model;
} | Trains a log-linear model.
@param data The log-linear model training examples created by
LogLinearData.
@return Trained model. |
public Pair<String, VarTensor> decode(FgModel model, LogLinearExample llex) {
LFgExample ex = getFgExample(llex);
MbrDecoderPrm prm = new MbrDecoderPrm();
prm.infFactory = getBpPrm();
MbrDecoder decoder = new MbrDecoder(prm);
decoder.decode(model, ex);
List<VarTensor> marginals = decoder.getVarMarginals();
VarConfig vc = decoder.getMbrVarConfig();
String stateName = vc.getStateName(ex.getFactorGraph().getVar(0));
if (marginals.size() != 1) {
throw new IllegalStateException("Example is not from a LogLinearData factory");
}
return new Pair<String,VarTensor>(stateName, marginals.get(0));
} | Decodes a single example.
@param model The log-linear model.
@param ex The example to decode.
@return A pair containing the most likely label (i.e. value of y) and the
distribution over y values. |
public FgExampleList getData(LogLinearXYData data) {
IntObjectBimap<String> alphabet = data.getFeatAlphabet();
List<LogLinearExample> exList = data.getData();
if (this.alphabet == null) {
this.alphabet = alphabet;
this.stateNames = getStateNames(exList, data.getYAlphabet());
}
if (prm.cacheExamples) {
FgExampleMemoryStore store = new FgExampleMemoryStore();
for (final LogLinearExample desc : exList) {
LFgExample ex = getFgExample(desc);
store.add(ex);
}
return store;
} else {
return new FgExampleList() {
@Override
public LFgExample get(int i) {
return getFgExample(exList.get(i));
}
@Override
public int size() {
return exList.size();
}
};
}
} | For testing only. Converts to the graphical model's representation of the data. |
public Connection getConnection() throws SQLException {
MicroPooledConnection microConn=null;
String xGroupId=getXGroupIdByLocal();
String xBranchId=getXBranchIdByLocal();
if(xGroupId==null || "".equals(xGroupId)){
log.error("getConnection error xid is null");
throw new RuntimeException("getConnection error xid is null");
}
Connection conn=getConnByGbId(xGroupId,xBranchId);
if(conn!=null){
log.debug("get conn from holdermap xid="+getStr4XidLocal());
if(checkConn(conn)==false){
Connection reconn=recreateConn(conn);
microConn=new MicroPooledConnection(reconn);
}else{
microConn=new MicroPooledConnection(conn);
}
putConnByGbId(xGroupId,xBranchId, microConn);
return microConn;
}
int totalSize=getConnCount();
if(totalSize>=maxSize){
throw new RuntimeException("getConnection error totalsize > maxsize");
}
// synchronized (pool) {
if (pool.isEmpty()==false){
conn=pool.poll();
log.debug("get conn from pool xid="+getStr4XidLocal());
if(checkConn(conn)==false){
Connection reconn=recreateConn(conn);
microConn=new MicroPooledConnection(reconn);
}else{
microConn=new MicroPooledConnection(conn);
}
}else{
log.debug("create conn in pool xid="+getStr4XidLocal());
Connection nconn=DriverManager.getConnection(url, username, password);
nconn.setAutoCommit(false);
nconn.setTransactionIsolation(level);
microConn=new MicroPooledConnection(nconn);
}
putConnByGbId(xGroupId,xBranchId, microConn);
// }
return microConn;
} | 获取一个数据库连接
@return 一个数据库连接
@throws SQLException |
private void freeMicroConnection(MicroPooledConnection microConn) {
Connection tempConn=null;
try {
tempConn = microConn.getConnection();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(tempConn!=null){
int totalSize=getConnCount();
if(totalSize<=getMinSize()){
pool.add(tempConn);
}
}
} | 连接归池
@param conn |
private void swapVals(int e, int f, int[] vals) {
int vals_e = vals[e];
vals[e] = vals[f];
vals[f] = vals_e;
} | Swap the values of two positions in an array. |
public IntArrayList getConnectedComponentsT2() {
boolean[] marked1 = new boolean[nodes1.size()];
boolean[] marked2 = new boolean[nodes2.size()];
IntArrayList roots = new IntArrayList();
for (int t2=0; t2<nodes2.size(); t2++) {
if (!marked2[t2]) {
roots.add(t2);
// Depth first search.
dfs(t2, false, marked1, marked2, null);
}
}
return roots;
} | Gets the connected components of the graph.
@return A list containing an arbitrary node in each each connected component. |
public int dfs(int root, boolean isRootT1, boolean[] marked1, boolean[] marked2, BipVisitor<T1,T2> visitor) {
IntStack sNode = new IntStack();
ByteStack sIsT1 = new ByteStack(); // TODO: This should be a boolean stack.
sNode.push(root);
sIsT1.push((byte)(isRootT1 ? 1 : 0));
// The number of times we check if any node is marked.
// For acyclic graphs this should be two times the number of nodes.
int numMarkedChecks = 0;
while (sNode.size() != 0) {
int node = sNode.pop();
boolean isT1 = (sIsT1.pop() == 1);
if (isT1) {
// Visit node only if not marked.
int t1 = node;
if (!marked1[t1]) {
marked1[t1] = true;
if (visitor != null) { visitor.visit(t1, true, this); }
for (int nb = numNbsT1(t1)-1; nb >= 0; nb--) {
int t2 = childT1(t1, nb);
if (!marked2[t2]) {
sNode.push(t2);
sIsT1.push((byte)0);
}
numMarkedChecks++;
}
}
numMarkedChecks++;
} else {
// Visit node only if not marked.
int t2 = node;
if (!marked2[t2]) {
marked2[t2] = true;
if (visitor != null) { visitor.visit(t2, false, this); }
for (int nb = numNbsT2(t2)-1; nb >= 0; nb--) {
int t1 = childT2(t2, nb);
if (!marked1[t1]) {
sNode.push(t1);
sIsT1.push((byte)1);
}
numMarkedChecks++;
}
}
numMarkedChecks++;
}
}
return numMarkedChecks;
} | Runs a depth-first-search starting at the root node. |
public IntArrayList bfs(int root, boolean isRootT1) {
boolean[] marked1 = new boolean[nodes1.size()];
boolean[] marked2 = new boolean[nodes2.size()];
return bfs(root, isRootT1, marked1, marked2);
} | Runs a breadth-first-search starting at the root node. |
public IntArrayList bfs(int root, boolean isRootT1, boolean[] marked1, boolean[] marked2) {
IntArrayList ccorder = new IntArrayList();
Queue<Integer> qNode = new ArrayDeque<>();
Queue<Boolean> qIsT1 = new ArrayDeque<>();
qNode.add(root);
qIsT1.add(isRootT1);
while (!qNode.isEmpty()) {
// Process the next node in the queue.
int parent = qNode.remove();
boolean isT1 = qIsT1.remove();
if (isT1) {
// Visit node only if not marked.
if (!marked1[parent]) {
log.trace("Visiting node {} of type T1", parent);
// For each neighbor...
for (int nb = 0; nb < this.numNbsT1(parent); nb++) {
int e = this.edgeT1(parent, nb);
int child = this.childE(e);
if (!marked2[child]) {
// If the neighbor is not marked, queue the node and add the edge to
// the order.
qNode.add(child);
qIsT1.add(false);
ccorder.add(e);
}
}
// Mark the node as visited.
marked1[parent] = true;
}
} else {
// Visit node only if not marked.
if (!marked2[parent]) {
log.trace("Visiting node {} of type T2", parent);
// For each neighbor...
for (int nb = 0; nb < this.numNbsT2(parent); nb++) {
int e = this.edgeT2(parent, nb);
int child = this.childE(e);
if (!marked1[child]) {
// If the neighbor is not marked, queue the node and add the edge to
// the order.
qNode.add(child);
qIsT1.add(true);
ccorder.add(e);
}
}
// Mark the node as visited.
marked2[parent] = true;
}
}
}
return ccorder;
} | Runs a breadth-first-search starting at the root node. |
@Override
protected void onCreate(Bundle savedInstanceState) {
final RoboInjector injector = RoboGuice.getInjector(this);
eventManager = injector.getInstance(EventManager.class);
preferenceListener = injector.getInstance(PreferenceListener.class);
injector.injectMembersWithoutViews(this);
super.onCreate(savedInstanceState);
eventManager.fire(new OnCreateEvent(savedInstanceState));
} | BUG find a better place to put this |
private void notifyHandlers(ApiUser apiUser) {
for(ServerUserHandlerClass handler : serverUserEventHandler) {
Object userAgent = checkUserAgent(handler, apiUser);
ReflectMethodUtil.invokeHandleMethod(
handler.getHandleMethod(),
handler.newInstance(),
context,
userAgent);
}
} | Propagate event to handlers
@param apiUser user agent object |
public String encrypt(String key, String initializationVector, String message) {
try {
IvParameterSpec initializationVectorSpec = new IvParameterSpec(Base64.decodeBase64(initializationVector));
final SecretKeySpec keySpec = new SecretKeySpec(Base64.decodeBase64(key), keyAlgorithm);
final Cipher cipher = (((provider == null) || (provider.length() == 0))
? Cipher.getInstance(cipherAlgorithm)
: Cipher.getInstance(cipherAlgorithm, provider));
byte[] messageAsByteArray;
switch (mode) {
case ENCRYPT:
cipher.init(Cipher.ENCRYPT_MODE, keySpec, initializationVectorSpec);
messageAsByteArray = message.getBytes(charsetName);
final byte[] encryptedMessage = cipher.doFinal(messageAsByteArray);
return new String(Base64.encodeBase64(encryptedMessage, chunkOutput));
case DECRYPT:
cipher.init(Cipher.DECRYPT_MODE, keySpec, initializationVectorSpec);
messageAsByteArray = Base64.decodeBase64(message);
final byte[] decryptedMessage = cipher.doFinal(messageAsByteArray);
return new String(decryptedMessage, charsetName);
default:
return null;
}
} catch (Exception e) {
throw new SymmetricEncryptionException("error encrypting/decrypting message; mode=" + mode, e);
}
} | Encrypts or decrypts a message. The encryption/decryption mode depends on
the configuration of the mode parameter.
@param key a base64 encoded version of the symmetric key
@param initializationVector a base64 encoded version of the
initialization vector
@param message if in encryption mode, the clear-text message to encrypt,
otherwise a base64 encoded version of the message to decrypt
@return if in encryption mode, returns a base64 encoded version of the
encrypted message, otherwise returns the decrypted clear-text
message
@throws SymmetricEncryptionException on runtime errors
@see #setMode(com.google.code.springcryptoutils.core.cipher.Mode) |
public static double[] insideAlgorithm(final Hypergraph graph, final Hyperpotential w, final Semiring s) {
final int n = graph.getNodes().size();
final double[] beta = new double[n];
// \beta_i = 0 \forall i
Arrays.fill(beta, s.zero());
graph.applyTopoSort(new HyperedgeFn() {
@Override
public void apply(Hyperedge e) {
// \beta_{H(e)} += w_e \prod_{j \in T(e)} \beta_j
double prod = s.one();
for (Hypernode jNode : e.getTailNodes()) {
prod = s.times(prod, beta[jNode.getId()]);
}
int i = e.getHeadNode().getId();
prod = s.times(w.getScore(e, s), prod);
beta[i] = s.plus(beta[i], prod);
//if (log.isTraceEnabled()) { log.trace(String.format("inside: %s w_e=%f prod=%f beta[%d] = %f", e.getLabel(), ((Algebra)s).toReal(w.getScore(e, s)), prod, i, ((Algebra)s).toReal(beta[i]))); }
}
});
return beta;
} | Runs the inside algorithm on a hypergraph.
@param graph The hypergraph.
@return The beta value for each Hypernode. Where beta[i] is the inside
score for the i'th node in the Hypergraph, graph.getNodes().get(i). |
public static double[] outsideAlgorithm(final Hypergraph graph, final Hyperpotential w, final Semiring s, final double[] beta) {
final int n = graph.getNodes().size();
final double[] alpha = new double[n];
// \alpha_i = 0 \forall i
Arrays.fill(alpha, s.zero());
// \alpha_{root} = 1
alpha[graph.getRoot().getId()] = s.one();
graph.applyRevTopoSort(new HyperedgeFn() {
@Override
public void apply(Hyperedge e) {
int i = e.getHeadNode().getId();
// \forall j \in T(e):
// \alpha_j += \alpha_{H(e)} * w_e * \prod_{k \in T(e) : k \neq j} \beta_k
for (Hypernode jNode : e.getTailNodes()) {
int j = jNode.getId();
double prod = s.one();
for (Hypernode kNode : e.getTailNodes()) {
int k = kNode.getId();
if (k == j) { continue; }
prod = s.times(prod, beta[k]);
}
prod = s.times(prod, alpha[i]);
prod = s.times(prod, w.getScore(e, s));
alpha[j] = s.plus(alpha[j], prod);
//if (log.isTraceEnabled()) { log.trace(String.format("outside: %s w_e=%f prod=%f alpha[%d]=%f", e.getLabel(), w.getScore(e,s), prod, j, alpha[j])); }
}
}
});
return alpha;
} | Runs the outside algorithm on a hypergraph.
@param graph The hypergraph
@param w The potential function.
@param s The semiring.
@param beta The beta value for each Hypernode. Where beta[i] is the inside
score for the i'th node in the Hypergraph, graph.getNodes().get(i).
@return The alpha value for each Hypernode. Where alpha[i] is the outside
score for the i'th node in the Hypergraph, graph.getNodes().get(i). |
public static void insideAlgorithmFirstOrderExpect(final Hypergraph graph, final HyperpotentialFoe w,
final Algebra s, final Scores scores) {
final int n = graph.getNodes().size();
final double[] beta = new double[n];
final double[] betaFoe = new double[n];
// \beta_i = 0 \forall i
Arrays.fill(beta, s.zero());
Arrays.fill(betaFoe, s.zero());
graph.applyTopoSort(new HyperedgeFn() {
@Override
public void apply(Hyperedge e) {
// \beta_{H(e)} += w_e \prod_{j \in T(e)} \beta_j
double prod = s.one();
double prodFoe = s.zero();
for (Hypernode jNode : e.getTailNodes()) {
int j = jNode.getId();
// prod = s.times(prod, beta[j]);
// prodFoe = s.plus(s.times(prod, betaFoe[j]), s.times(beta[j], prodFoe));
double p1 = prod;
double p2 = beta[j];
double r1 = prodFoe;
double r2 = betaFoe[j];
prod = s.times(p1, p2);
prodFoe = s.plus(s.times(p1, r2), s.times(p2, r1));
}
// prod = s.times(prod, w.getScore(e, s));
// prodFoe = s.plus(s.times(prod, w.getScoreFoe(e, s)), s.times(w.getScore(e, s), prodFoe));
double p1 = prod;
double p2 = w.getScore(e, s);
double r1 = prodFoe;
double r2 = w.getScoreFoe(e, s);
prod = s.times(p1, p2);
prodFoe = s.plus(s.times(p1, r2), s.times(p2, r1));
int i = e.getHeadNode().getId();
//if (log.isTraceEnabled()) { log.trace(String.format("old beta[%d] = %f", i, s.toReal(beta[i]))); }
beta[i] = s.plus(beta[i], prod);
betaFoe[i] = s.plus(betaFoe[i], prodFoe);
assert !s.isNaN(beta[i]);
assert !s.isNaN(betaFoe[i]);
// log.debug(String.format("%s w_e=%f beta[%d] = %.3f betaFoe[%d] = %.3f", e.getLabel(), s.toReal(w.getScore(e, s)), i, s.toReal(beta[i]), i, s.toReal(betaFoe[i])));
}
});
scores.beta = beta;
scores.betaFoe = betaFoe;
} | Runs the inside algorithm on a hypergraph with the first-order expectation semiring.
@param graph The hypergraph.
@return The beta value for each Hypernode. Where beta[i] is the inside
score for the i'th node in the Hypergraph, graph.getNodes().get(i). |
public static void insideAlgorithm(final Hypergraph graph, final Hyperpotential w, final Semiring s,
final Scores scores) {
scores.beta = insideAlgorithm(graph, w, s);
} | Runs the inside algorithm on a hypergraph.
INPUT:
OUTPUT: scores.beta.
@param graph The hypergraph.
@param w The potential function.
@param s The semiring.
@param scores Input and output struct. |
public static void outsideAlgorithm(final Hypergraph graph, final Hyperpotential w, final Semiring s,
final Scores scores) {
scores.alpha = outsideAlgorithm(graph, w, s, scores.beta);
} | Runs the outside algorithm on a hypergraph.
INPUT: scores.beta.
OUTPUT: scores.alpha.
@param graph The hypergraph.
@param w The potential function.
@param s The semiring.
@param scores Input and output struct. |
public static void marginals(final Hypergraph graph, final Hyperpotential w, final Algebra s,
final Scores scores) {
final int n = graph.getNodes().size();
final double[] alpha = scores.alpha;
final double[] beta = scores.beta;
final double[] marginal = new double[n];
int root = graph.getRoot().getId();
// p(i) = \alpha_i * \beta_i / \beta_{root}
for (Hypernode iNode : graph.getNodes()) {
int i = iNode.getId();
marginal[i] = s.divide(s.times(alpha[i], beta[i]), beta[root]);
}
scores.marginal = marginal;
} | Computes the marginal for each hypernode.
INPUT: scores.alpha, scores.beta.
OUTPUT: scores.marginal.
@param graph The hypergraph.
@param w The potential function.
@param s The semiring.
@param scores Input and output struct. |
private static void marginalsBackward(final Hypergraph graph, final Hyperpotential w, final Algebra s,
final Scores scores) {
final int n = graph.getNodes().size();
final double[] marginalAdj = scores.marginalAdj;
final double[] alpha = scores.alpha;
final double[] beta = scores.beta;
if (scores.alphaAdj == null) {
// \adj{alpha_i} = 0 \forall i
scores.alphaAdj = DoubleArrays.newFilled(alpha.length, s.zero());
}
final double[] alphaAdj = scores.alphaAdj;
if (scores.betaAdj == null) {
// \adj{beta_j} = 0 \forall j
scores.betaAdj = DoubleArrays.newFilled(beta.length, s.zero());
}
final double[] betaAdj = scores.betaAdj;
int root = graph.getRoot().getId();
// ----- Computes the adjoints of the outside scores -----
for (Hypernode iNode : graph.getNodes()) {
int i = iNode.getId();
// \adj{\alpha_i} += \adj{p(i)} * \beta_i / \beta_{root}
double prod = s.times(marginalAdj[i], beta[i]);
prod = s.divide(prod, beta[graph.getRoot().getId()]);
alphaAdj[i] = s.plus(alphaAdj[i], prod);
}
// ----- Computes the adjoints of the partition function (i.e. inside of root) -----
for (Hypernode jNode : graph.getNodes()) {
// \adj{beta_{root}} = - \sum_{j \in G : j \neq root} \adj{p(j)} * \alpha_j * \beta_j / (\beta_{root}^2)
int j = jNode.getId();
if (j == root) { continue; }
double prod = s.times(marginalAdj[j], alpha[j]);
prod = s.times(prod, beta[j]);
prod = s.divide(prod, s.times(beta[root], beta[root]));
betaAdj[root] = s.minus(betaAdj[root], prod);
}
// ----- Computes the adjoints of the other inside scores -----
for (Hypernode jNode : graph.getNodes()) {
// \adj{\beta_j} += \adj{p(j)} * \alpha_j / \beta_{root}, \forall j \neq root
int j = jNode.getId();
if (j == root) { continue; }
double prod = s.divide(s.times(marginalAdj[j], alpha[j]), beta[root]);
betaAdj[j] = s.plus(betaAdj[j], prod);
}
} | Computes the adjoints of the inside and outside scores.
INPUT: scores.beta, scores.alpha scores.marginalAdj. (OPTIONALLY: scores.betaAdj, scores.alphaAdj)
OUTPUT: scores.betaAdj, scores.alphaAdj.
@param graph The hypergraph
@param w The potential function.
@param s The semiring.
@param scores Input and output struct. |
public static void insideBackward(final Hypergraph graph, final Hyperpotential w,
final Algebra s, final Scores scores) {
insideAdjoint(graph, w, s, scores, false);
weightAdjoint(graph, w, s, scores, false);
} | This method is identical to
{@link Hyperalgo#insideBackward(Hypergraph, Hyperpotential, Algebra, Scores, HyperedgeDoubleFn)}
except that the adjoints of the weights are add to {@link Scores#weightAdj}.
INPUT: scores.alpha, scores.beta, scores.betaAdj.
OUTPUT: scores.betaAdj, scores.weightsAdj. |
public static void insideOutsideBackward(final Hypergraph graph, final Hyperpotential w,
final Algebra s, final Scores scores) {
outsideAdjoint(graph, w, s, scores);
insideAdjoint(graph, w, s, scores, true);
weightAdjoint(graph, w, s, scores, true);
} | This method is identical to
{@link Hyperalgo#insideOutsideBackward(Hypergraph, Hyperpotential, Algebra, Scores, HyperedgeDoubleFn)}
except that the adjoints of the weights are add to {@link Scores#weightAdj}.
INPUT: scores.alpha, scores.beta, scores.alphaAdj, scores.betaAdj.
OUTPUT: scores.alphaAdj, scores.betaAdj, scores.weightsAdj. |
private static void outsideAdjoint(final Hypergraph graph, final Hyperpotential w, final Algebra s,
final Scores scores) {
final double[] beta = scores.beta;
final double[] alphaAdj = scores.alphaAdj;
graph.applyTopoSort(new HyperedgeFn() {
@Override
public void apply(Hyperedge e) {
int i = e.getHeadNode().getId();
// \forall j \in T(e):
// \adj{\alpha_i} += \adj{\alpha_j} * w_e * \prod_{k \in T(e): k \neq j} \beta_k
for (Hypernode j : e.getTailNodes()) {
double prod = s.times(alphaAdj[j.getId()], w.getScore(e, s));
for (Hypernode k : e.getTailNodes()) {
if (k == j) { continue; }
prod = s.times(prod, beta[k.getId()]);
}
alphaAdj[i] = s.plus(alphaAdj[i], prod);
}
}
});
scores.alphaAdj = alphaAdj;
} | Computes the adjoints of the outside scores only.
Performs only a partial backwards pass through the outside algorithm.
INPUT: scores.beta, scores.alphaAdj.
OUTPUT: scores.alphaAdj.
@param graph The hypergraph
@param w The potential function.
@param s The semiring.
@param scores Input and output struct. |
private static void insideAdjoint(final Hypergraph graph, final Hyperpotential w, final Algebra s,
final Scores scores, final boolean backOutside) {
final double[] alpha = scores.alpha;
final double[] beta = scores.beta;
final double[] alphaAdj = scores.alphaAdj;
final double[] betaAdj = scores.betaAdj;
graph.applyRevTopoSort(new HyperedgeFn() {
@Override
public void apply(Hyperedge e) {
int i = e.getHeadNode().getId();
for (Hypernode jNode : e.getTailNodes()) {
int j = jNode.getId();
// \adj{\beta_{j}} += \sum_{e \in O(j)} \adj{\beta_{H(e)}} * w_e * \prod_{k \in T(e) : k \neq j} \beta_k
double prod = s.times(betaAdj[i], w.getScore(e, s));
for (Hypernode kNode : e.getTailNodes()) {
int k = kNode.getId();
if (j == k) { continue; }
prod = s.times(prod, beta[k]);
}
betaAdj[j] = s.plus(betaAdj[j], prod);
if (backOutside) {
// \adj{\beta_{j}} += \sum_{e \in O(j)} \sum_{k \in T(e) : k \neq j} \adj{\alpha_k} * w_e * \alpha_{H(e)} * \prod_{l \in T(e) : l \neq k, l \neq j} \beta_l
for (Hypernode kNode : e.getTailNodes()) {
int k = kNode.getId();
if (k == j) { continue; };
prod = s.times(alphaAdj[k], w.getScore(e, s));
prod = s.times(prod, alpha[i]);
for (Hypernode lNode : e.getTailNodes()) {
int l = lNode.getId();
if (l == j || l == k) { continue; }
prod = s.times(prod, beta[l]);
}
betaAdj[j] = s.plus(betaAdj[j], prod);
}
}
}
}
});
scores.betaAdj = betaAdj;
} | Computes the adjoints of the inside scores only. Performs a partial
backwards pass through the outside algorithm, and a partial backwards
pass through the inside algorithm.
INPUT: scores.alpha, scores.beta, scores.betaAdj.
OUTPUT: scores.betaAdj.
@param graph The hypergraph
@param w The potential function.
@param s The semiring.
@param scores Input and output struct. |
private static void weightAdjoint(final Hypergraph graph, final Hyperpotential w, final Algebra s,
final Scores scores, boolean backOutside) {
final double[] weightAdj = new double[graph.getNumEdges()];
HyperedgeDoubleFn lambda = new HyperedgeDoubleFn() {
public void apply(Hyperedge e, double val) {
weightAdj[e.getId()] = val;
}
};
weightAdjoint(graph, w, s, scores, lambda, backOutside);
scores.weightAdj = weightAdj;
} | Computes the adjoints of the hyperedge weights.
INPUT: scores.alpha, scores.beta, scores.alphaAdj, scores.betaAdj.
OUTPUT: scores.weightsAdj.
@param graph The hypergraph
@param w The potential function.
@param s The semiring.
@param scores Input and output struct. |
private static void weightAdjoint(final Hypergraph graph, final Hyperpotential w,
final Algebra s, final Scores scores, final HyperedgeDoubleFn lambda, final boolean backOutside) {
final double[] alpha = scores.alpha;
final double[] beta = scores.beta;
final double[] alphaAdj = scores.alphaAdj;
final double[] betaAdj = scores.betaAdj;
graph.applyTopoSort(new HyperedgeFn() {
@Override
public void apply(Hyperedge e) {
// \adj{w_e} += \adj{\beta_{H(e)} * \prod_{j \in T(e)} \beta_j
int i = e.getHeadNode().getId();
double prod = betaAdj[i];
for (Hypernode jNode : e.getTailNodes()) {
int j = jNode.getId();
prod = s.times(prod, beta[j]);
}
double w_e = prod;
if (backOutside) {
// \adj{w_e} += \adj{\alpha_j} * \alpha_{H(e)} * \prod_{k \in T(e) : k \neq j} \beta_k
for (Hypernode jNode : e.getTailNodes()) {
int j = jNode.getId();
prod = s.times(alphaAdj[j], alpha[i]);
for (Hypernode kNode : e.getTailNodes()) {
int k = kNode.getId();
if (k == j) { continue; }
prod = s.times(prod, beta[k]);
}
w_e = s.plus(w_e, prod);
}
}
lambda.apply(e, w_e);
}
});
} | Computes the adjoints of the hyperedge weights.
INPUT: scores.alpha, scores.beta, scores.alphaAdj, scores.betaAdj.
OUTPUT: The adjoints of the weights.
@param graph The hypergraph
@param w The potential function.
@param s The semiring.
@param scores Input struct.
@param lambda Function to call with the edge and the edge adjoint. |
private void addFlagFileOption() {
String name = "flagfile";
String shortName = getAndAddUniqueShortName(name);
String description = "Special flag: file from which to read additional flags"
+ " (lines starting with # are ignored as comments,"
+ " and these flags are always processed before those on the command line).";
flagfileOpt = new Option(shortName, name, true, description);
flagfileOpt.setRequired(false);
options.addOption(flagfileOpt);
} | Adds a special option --flagfile (akin to gflags' flagfile option
http://gflags.github.io/gflags/#special) that specifies a file from which to read additional
flags. |
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); }
// Add an Apache Commons CLI Option for this 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);
// Check that only boolean has hasArg() == false.
if (!field.getType().equals(Boolean.TYPE) && !opt.hasArg()) {
throw new RuntimeException("Only booleans can not have arguments.");
}
}
}
} | Registers all the @Opt annotations on a class with this ArgParser. |
private String getAndAddUniqueShortName(String name) {
// Capitalize the first letter of the name.
String initCappedName = name.substring(0, 1).toUpperCase() + name.substring(1, name.length());
// Make the short name all the capital letters in the long name.
Matcher matcher = capitals.matcher(initCappedName);
StringBuilder sbShortName = new StringBuilder();
while(matcher.find()) {
sbShortName.append(matcher.group());
}
String shortName = sbShortName.toString().toLowerCase();
if (!shortNames.add(shortName)) {
int i;
for (i=0; i<10; i++) {
String tmpsn = shortName + i;
if (shortNames.add(tmpsn)) {
shortName = tmpsn;
break;
}
}
if (i == 10) {
throw new RuntimeException("Multiple options have the same short name: -" + shortName + " (--" + name + ")");
}
}
return shortName;
} | Creates a unique short name from the name of a field. For example, the field "trainPredOut"
would have a long name of "--trainPredOut" and a short name of "-tpo". |
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 @Opt(name=...) if present, or the name of the field otherwise. |
public void parseArgs(String[] args) {
try {
parseArgsNoExit(args);
} catch (ParseException e1) {
log.error(e1.getMessage() + " (See usage below)");
this.printUsage();
log.error(e1.getMessage() + " (See usage above)");
System.exit(1);
}
} | Parses the command line arguments and sets any of public static fields annotated with @Opt
that have been registered with this {@link ArgParser} via {@link #registerClass(Class)}.
If a parser error occurs, the error is logged, the usage is printed, and System.exit(1) is called.
See also {@link #parseArgsNoExit(String[])}. |
public void parseArgsNoExit(String[] args) throws ParseException {
// Parse command line.
CommandLine cmd = null;
CommandLineParser parser = new PosixParser();
cmd = parser.parse(options, args);
// Special handling of --flagfile.
if (cmd.hasOption(flagfileOpt.getLongOpt())) {
String value = cmd.getOptionValue(flagfileOpt.getLongOpt());
String[] ffArgs = readFlagFile(value);
parseArgs(ffArgs);
}
// Process each flag mapped to a field.
fieldValueMap = new HashMap<>();
try {
for (Option apacheOpt : optionFieldMap.keySet()) {
Field field = optionFieldMap.get(apacheOpt);
if (cmd.hasOption(apacheOpt.getLongOpt())) {
String value = apacheOpt.hasArg() ? cmd.getOptionValue(apacheOpt.getLongOpt()) : "true";
if (Modifier.isStatic(field.getModifiers())) {
// For static fields, set the value directly to the field.
setStaticField(field, value);
} else {
// For non-static fields, cache the value for later use by getInstanceFromParsedArgs().
fieldValueMap.put(field, value);
}
}
}
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
} | Parses the command line arguments and sets any of public static fields annotated with @Opt
that have been registered with this {@link ArgParser} via {@link #registerClass(Class)}.
@throws ParseException if a parser error occurs. |
private static String[] readFlagFile(String path) throws ParseException {
Path p = Paths.get(path);
if (!Files.isRegularFile(p)) {
throw new ParseException("--flagfile specified a file that does not exist: " + path);
}
StringBuilder sb = new StringBuilder();
try {
for (String line : Files.readAllLines(p)) {
if (line.startsWith("#")) { continue; }
sb.append(line);
}
} catch (IOException e) {
throw new ParseException("Error while reading flagfile: " + e.getMessage());
}
return sb.toString().split("\\s+");
} | Reads a flag file: skips lines beginning with # as comments and splits on whitespace. |
public <T> T getInstanceFromParsedArgs(Class<T> clazz) {
if (!registeredClasses.contains(clazz)) {
throw new IllegalArgumentException("Class not registered: " + clazz);
}
try {
T obj = clazz.newInstance();
for (Field field : clazz.getFields()) {
if (field.isAnnotationPresent(Opt.class)) {
String value = fieldValueMap.get(field);
if (value != null) {
setField(obj, field, value);
}
}
}
return obj;
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InstantiationException e) {
throw new RuntimeException(e);
}
} | Gets an instance of the given class by using the no-argument constructor (which must exist)
and then setting all fields annotated with @Opt with values cached by {@link #parseArgs(String[])}. |
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. |
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. |
protected void notifyToHandlers(Object message, ISFSObject params) {
if(params == null) params = new SFSObject();
for(ServerHandlerClass handler : handlers) {
notifyToHandler(handler, message, params);
}
} | Propagate event to handlers
@param message message data
@param params addition data to send |
protected void notifyToHandler(ServerHandlerClass handler,
Object message, ISFSObject params) {
Object object = handler.newInstance();
MessageParamsClass paramsClass = context.getMessageParamsClass(object.getClass());
if(paramsClass == null) paramsClass = new MessageParamsClass(object.getClass());
new RequestParamDeserializer().deserialize(paramsClass.getWrapper(), params, object);
ReflectMethodUtil.invokeHandleMethod(
handler.getHandleMethod(),
object, context, message);
new ResponseParamSerializer().object2params(paramsClass.getUnwrapper(), object, params);
} | Propagate event to handler
@param handler structure of handler class
@param message message data
@param params addition data to send |
public static double convertAlgebra(double value, Algebra src, Algebra dst) {
if (dst.equals(src)) {
return value;
} else if (src.equals(RealAlgebra.getInstance())) {
return dst.fromReal(value);
} else if (src.equals(LogSemiring.getInstance())) {
return dst.fromLogProb(value);
} else if (dst.equals(RealAlgebra.getInstance())) {
return src.toReal(value);
} else if (dst.equals(LogSemiring.getInstance())) {
return src.toLogProb(value);
} else {
// We pivot through the real numbers, but this could cause a loss of
// floating point precision.
log.warn("FOR TESTING ONLY: unsafe conversion from " + src + " to " + dst);
return dst.fromReal(src.toReal(value));
}
} | TODO: unit test. |
@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
@param unwrapper structure of agent class
@param agent the agent object
@return List of variables |
@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
@param method structure of getter method
@param value object to call method
@return a value |
@Override
public void handleServerEvent(ISFSEvent event) throws SFSException {
User sfsUser = (User)event.getParameter(SFSEventParam.USER);
ApiUser apiUser = (ApiUser) sfsUser.getProperty(APIKey.USER);
if(apiUser.getBuddyProperties() != null)
updateBuddyProperties(sfsUser.getBuddyProperties(),
apiUser.getBuddyProperties());
removeAddedBuddies(sfsUser);
super.handleServerEvent(event);
} | /* (non-Javadoc)
@see com.tvd12.ezyfox.sfs2x.serverhandler.UserZoneEventHandler#handleServerEvent(com.smartfoxserver.v2.core.ISFSEvent) |
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
@param buddyProperties smartfox user's buddy properties
@param apiBuddyProperties api user's buddy properties |
public void report() {
if (log.isTraceEnabled()) {
log.trace(String.format("Timers avg (ms): model=%.1f inf=%.1f val=%.1f grad=%.1f",
updTimer.avgMs(), infTimer.avgMs(), valTimer.avgMs(), gradTimer.avgMs()));
}
double sum = initTimer.totMs() + updTimer.totMs() + infTimer.totMs() + valTimer.totMs() + gradTimer.totMs();
double mult = 100.0 / sum;
log.debug(String.format("Timers: init=%.1f%% model=%.1f%% inf=%.1f%% val=%.1f%% grad=%.1f%% avg(ms)=%.1f max(ms)=%.1f stddev(ms)=%.1f",
initTimer.totMs()*mult, updTimer.totMs()*mult, infTimer.totMs()*mult, valTimer.totMs()*mult, gradTimer.totMs()*mult,
tot.avgMs(), tot.maxSplitMs(), tot.stdDevMs()));
} | TODO: Use this somewhere. |
void apply(final LambdaUnaryOpDouble lambda) {
params.apply(new FnIntDoubleToDouble() {
@Override
public double call(int idx, double val) {
return lambda.call(val);
}
});
} | ONLY FOR TESTING. |
public void setRandomStandardNormal() {
FnIntDoubleToDouble lambda = new FnIntDoubleToDouble() {
@Override
public double call(int idx, double val) {
return Gaussian.nextDouble(0.0, 1.0);
}
};
apply(lambda);
} | Fill the model parameters with values randomly drawn from ~ Normal(0, 1). |
@Override
public Tensor forward() {
Tensor x = modInX.getOutput();
y = new Tensor(x); // copy
y.exp();
return y;
} | Foward pass: y_i = exp(x_i) |
@Override
public void backward() {
Tensor tmp = new Tensor(yAdj); // copy
tmp.elemMultiply(y);
modInX.getOutputAdj().elemAdd(tmp);
} | Backward pass:
dG/dx_i += dG/dy_i dy_i/dx_i = dG/dy_i exp(x_i) |
@SuppressWarnings("unchecked")
@Override
protected BuddyVariable newVariable(String name, Object value, boolean isHidden) {
return new SFSBuddyVariable(name, value);
} | /* (non-Javadoc)
@see com.tvd12.ezyfox.sfs2x.serializer.AgentUnwrapper#newVariable(java.lang.String, java.lang.Object, boolean) |
public static <R> ImmutableCell<R> of(int row, int column, R value) {
if (row < 0) {
throw new IndexOutOfBoundsException("Row must not be negative: " + row + " < 0");
}
if (column < 0) {
throw new IndexOutOfBoundsException("Column must not be negative: " + column + " < 0");
}
if (value == null) {
throw new IllegalArgumentException("Value must not be null");
}
return new ImmutableCell<R>(row, column, value);
} | Obtains an instance of {@code Cell}.
@param <R> the type of the value
@param row the row, zero or greater
@param column the column, zero or greater
@param value the value to put into the grid, not null
@return the immutable cell, not null
@throws IndexOutOfBoundsException if either index is less than zero |
public static <R> ImmutableCell<R> copyOf(Cell<? extends R> cell) {
if (cell == null) {
throw new IllegalArgumentException("Cell must not be null");
}
if (cell instanceof ImmutableCell) {
@SuppressWarnings("unchecked")
ImmutableCell<R> result = (ImmutableCell<R>) cell;
return result;
}
return ImmutableCell.<R>of(cell.getRow(), cell.getColumn(), cell.getValue());
} | Obtains an instance of {@code Cell}.
@param <R> the type of the value
@param cell the cell to copy, not null
@return the immutable cell, not null |
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. |
@SuppressWarnings("unchecked")
@Override
public Boolean execute() {
User sfsOwner = CommandUtil.getSfsUser(owner, api);
ISFSBuddyApi buddyApi = SmartFoxServer.getInstance()
.getAPIManager().getBuddyApi();
buddyApi.removeBuddy(sfsOwner, buddy, fireClientEvent, fireServerEvent);
return Boolean.TRUE;
} | /* (non-Javadoc)
@see com.tvd12.ezyfox.core.command.BaseCommand#execute() |
public static double approxSumPaths(WeightedIntDiGraph g, RealVector startWeights, RealVector endWeights,
Iterator<DiEdge> seq, DoubleConsumer c) {
// we keep track of the total weight of discovered paths ending along
// each edge and the total weight
// of all paths ending at each node (including the empty path); on each
// time step, we
// at each step, we pick an edge (s, t), update the sum at s, and extend
// each of those (including
// the empty path starting there) with the edge (s, t)
DefaultDict<DiEdge, Double> prefixWeightsEndingAt = new DefaultDict<DiEdge, Double>(Void -> 0.0);
// we'll maintain node sums and overall sum with subtraction rather than
// re-adding (it's an approximation anyway!)
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();
// compute the new sums
double oldTargetSum = currentSums.getEntry(t);
double oldEdgeSum = prefixWeightsEndingAt.get(e);
// new edge sum is the source sum times the edge weight
double newEdgeSum = currentSums.getEntry(s) * g.getWeight(e);
// new target sum is the old target sum plus the difference between
// the new and old edge sums
double newTargetSum = oldTargetSum + (newEdgeSum - oldEdgeSum);
// the new total is the old total plus the difference in new and
// target
double newTotal = currentTotal + (newTargetSum - oldTargetSum) * endWeights.getEntry(t);
// store the new sums
prefixWeightsEndingAt.put(e, newEdgeSum);
currentSums.setEntry(t, newTargetSum);
currentTotal = newTotal;
// and report the new total to the consumer
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;
If consumer c is not null, it will be given the intermediate estimates as
they are available |
private Iterator<DiEdge> edges(Schedule s) {
Iterator<Integer> ixIter = s.iterator();
return new Iterator<DiEdge>() {
@Override
public DiEdge next() {
return edgesToNodes.lookupObject(ixIter.next());
}
@Override
public boolean hasNext() {
return ixIter.hasNext();
}
};
} | /*
TODO: probably better to just have halt be explicit as an int rather than an action
private Pair<Iterator<DiEdge>, Integer> filterOutStopTime(Schedule s) {
int haltTime = -1;
List<DiEdge> nonStopActions = new LinkedList<>();
for (Indexed<Integer> a : enumerate(s)) {
if (a.get() == haltAction) {
if (haltTime > -1) {
throw new IllegalStateException("cannot have more than one halt action in schedule");
}
haltTime = a.index();
} else {
nonStopActions.add(edgesToNodes.lookupObject(a.get()));
}
}
if (haltTime == -1) {
haltTime = nonStopActions.size();
}
return new Pair<>(nonStopActions.iterator(), haltTime);
} |
public static int hash32(final long data, int seed) {
// 'm' and 'r' are mixing constants generated offline.
// They're not really 'magic', they just happen to work well.
final int m = 0x5bd1e995;
final int r = 24;
// Initialize the hash to a random value
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. |
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. |
@SuppressWarnings("unchecked")
@Override
public <T> T by(String name) {
User user = api.getUserByName(name);
return (user == null) ? null :
(T)user.getProperty(APIKey.USER);
} | /* (non-Javadoc)
@see com.tvd12.ezyfox.core.command.GetUser#by(java.lang.String) |
@SuppressWarnings("unchecked")
@Override
public <T> T by(int userId) {
User sfsUser = api.getUserById(userId);
if(sfsUser != null)
return (T)sfsUser.getProperty(APIKey.USER);
return null;
} | /* (non-Javadoc)
@see com.tvd12.ezyfox.core.command.GetUser#by(int) |
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
@param handler structure of handler
@param userAgent user agent object
@return user agent or game user agent object |
public String getLabel() {
if (label == null) {
// Lazily construct an edge label from the head and tail nodes.
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. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.