code
stringlengths
67
466k
docstring
stringlengths
1
13.2k
private double smartResidual(VarTensor message, VarTensor newMessage, int edge) { // This is intentionally NOT the semiring zero. return CachingBpSchedule.isConstantMsg(edge, fg) ? 0.0 : getResidual(message, newMessage); }
Returns the "converged" residual for constant messages, and the actual residual otherwise.
private double getResidual(VarTensor t1, VarTensor t2) { assert s == t1.getAlgebra() && s == t2.getAlgebra(); Tensor.checkEqualSize(t1, t2); Tensor.checkSameAlgebra(t1, t2); double residual = Double.NEGATIVE_INFINITY; for (int c=0; c<t1.size(); c++) { double abs = Math.abs(s.toLogProb(t1.get(c)) - s.toLogProb(t2.get(c))); if (abs > residual) { residual = abs; } } return residual; }
Gets the residual for a new message, as the maximum error over all assignments. Following the definition of Sutton & McCallum (2007), we compute the residual as the infinity norm of the difference of the log of the message vectors. Note: the returned value is NOT in the semiring / abstract algebra. It is the actual value described above.
public void backward() { VarTensor[] varBeliefsAdj = bAdj.varBeliefs; VarTensor[] facBeliefsAdj = bAdj.facBeliefs; // Initialize the adjoints. // We are given the adjoints of the normalized beleifs. Compute // the adjoints of the unnormalized beliefs and store them in the original // adjoint arrays. for (int v=0; v<varBeliefsAdj.length; v++) { unnormalizeAdjInPlace(varBeliefs[v], varBeliefsAdj[v], varBeliefsUnSum[v]); } for (int a=0; a<facBeliefsAdj.length; a++) { if (facBeliefs[a] != null) { unnormalizeAdjInPlace(facBeliefs[a], facBeliefsAdj[a], facBeliefsUnSum[a]); } } // Initialize the message and potential adjoints by running the variable / factor belief computation in reverse. backwardVarFacBeliefs(varBeliefsAdj, facBeliefsAdj); // Process each tape entry in reverse order. for (int t = tape.size() - 1; t >= 0; t--) { // Dequeue from tape. TapeEntry te = tape.get(t); List<Integer> edges = CachingBpSchedule.toEdgeList(fg, te.item); List<?> elems = CachingBpSchedule.toFactorEdgeList(te.item); for (int j = edges.size() - 1; j >= 0; j--) { backwardSendMessage(edges.get(j), te.msgs.get(j)); } for (int j = edges.size() - 1; j >= 0; j--) { backwardNormalize(edges.get(j), te.msgSums.get(j)); } for (int j = elems.size() - 1; j >= 0; j--) { Object elem = elems.get(j); if (elem instanceof Integer) { backwardCreateMessage((Integer) elem); } else if (elem instanceof AutodiffGlobalFactor) { backwardGlobalFactorToVar((AutodiffGlobalFactor) elem, te); } else { throw new RuntimeException("Unsupported type in schedule: " + elem.getClass()); } } } }
/* ---------------------------- BEGIN: Backward Pass Methods ---------------------
private void backwardCreateMessage(int edge) { if (!bg.isT1T2(edge) && (bg.t2E(edge) instanceof GlobalFactor)) { log.warn("ONLY FOR TESTING: Creating a single message from a global factor: " + edge); } if (bg.isT1T2(edge)) { backwardVarToFactor(edge); } else { backwardFactorToVar(edge); } assert !msgsAdj[edge].containsNaN() : "msgsAdj[i] = " + msgsAdj[edge] + "\n" + "edge: " + fg.edgeToString(edge); }
Creates the adjoint of the unnormalized message for the edge at time t and stores it in msgsAdj[i].
private VarTensor[] getMsgs(int f, VarTensor[] msgs, boolean isIn) { int numNbs = bg.numNbsT2(f); VarTensor[] arr = new VarTensor[numNbs]; for (int nb=0; nb<numNbs; nb++) { int edge = isIn ? bg.opposingT2(f, nb) : bg.edgeT2(f, nb); arr[nb] = msgs[edge]; } return arr; }
Gets messages from the Messages[]. @param f The factor's index. @param msgs The input messages. @param isNew Whether to get messages in .newMessage or .message. @param isIn Whether to get incoming or outgoing messages. @return The output messages.
private void calcProductAtVar(int v, VarTensor prod, int excl1, int excl2) { for (int nb=0; nb<bg.numNbsT1(v); nb++) { if (nb == excl1 || nb == excl2) { // Don't include messages to these neighbors. continue; } // Get message from neighbor to this node. VarTensor nbMsg = msgs[bg.opposingT1(v, nb)]; // Since the node is a variable, this is an element-wise product. prod.elemMultiply(nbMsg); } }
Computes the product of all messages being sent to a node, optionally excluding messages sent from another node or two. Upon completion, prod will be multiplied by the product of all incoming messages to node, except for the message from exclNode1 / exclNode2 if specified. @param node The node to which all the messages are being sent. @param prod An input / output tensor with which the product will (destructively) be taken. @param exclNode1 If non-null, any message sent from exclNode1 to node will be excluded from the product. @param exclNode2 If non-null, any message sent from exclNode2 to node will be excluded from the product.
private VarTensor calcVarBeliefs(Var var) { // Compute the product of all messages sent to this variable. VarTensor prod = new VarTensor(s, new VarSet(var), s.one()); calcProductAtVar(var.getId(), prod, -1, -1); return prod; }
Gets the unnormalized variable beleifs.
private VarTensor calcFactorBeliefs(Factor factor) { if (factor instanceof GlobalFactor) { log.warn("Getting marginals of a global factor is not supported." + " This will require exponential space to store the resulting factor." + " This should only be used for testing."); } // Compute the product of all messages sent to this factor. VarTensor prod = safeNewVarTensor(factor); calcProductAtFactor(factor.getId(), prod, -1, -1); return prod; }
Gets the unnormalized factor beleifs.
double getBetheFreeEnergy() { // // G_{Bethe} = \sum_a \sum_{x_a} - b(x_a) ln \chi(x_a) // + \sum_a \sum_{x_a} b(x_a) ln b(x_a) // + \sum_i (n_i - 1) \sum_{x_i} b(x_i) ln b(x_i) // = \sum_a \sum_{x_a} b(x_a) ln (b(x_a) / \chi(x_a)) // + \sum_i (n_i - 1) \sum_{x_i} b(x_i) ln b(x_i) // // where n_i is the number of neighbors of the variable x_i, // b(x_a) and b(x_i) are normalized distributions and x_a is // the set of variables participating in factor a. // double bethe = 0.0; for (int a=0; a<fg.getFactors().size(); a++) { Factor f = fg.getFactors().get(a); if (!(f instanceof GlobalFactor)) { int numConfigs = f.getVars().calcNumConfigs(); VarTensor beliefs = getFactorBeliefs(a); for (int c=0; c<numConfigs; c++) { // Since we want multiplication by 0 to always give 0 (not the case for Double.POSITIVE_INFINITY or Double.NaN. double b_c = beliefs.getValue(c); if (b_c != s.zero()) { double r_b_c = s.toReal(b_c); double log_b_c = s.toLogProb(b_c); double log_chi_c = f.getLogUnormalizedScore(c); bethe += r_b_c * (log_b_c - log_chi_c); } } } else { VarTensor[] inMsgs = getMsgs(f.getId(), msgs, IN_MSG); bethe += ((GlobalFactor) f).getExpectedLogBelief(inMsgs); } } for (int v=0; v<fg.getVars().size(); v++) { Var var = fg.getVars().get(v); int numNeighbors = bg.numNbsT1(v); VarTensor beliefs = getVarBeliefs(v); double sum = 0.0; for (int c=0; c<var.getNumStates(); c++) { double b_c = beliefs.getValue(c); if (b_c != s.zero()) { double r_b_c = s.toReal(b_c); double log_b_c = s.toLogProb(b_c); sum += r_b_c * log_b_c; } } bethe -= (numNeighbors - 1) * sum; } assert !Double.isNaN(bethe); return bethe; }
Computes the Bethe free energy of the factor graph. For acyclic graphs, this is equal to -log(Z) where Z is the exact partition function. For loopy graphs it can be used as an approximation. NOTE: The result of this call is always in the real semiring.
public double evaluate(VarConfig goldConfig, FgInferencer inf) { Algebra s = RealAlgebra.getInstance(); double sum = s.zero(); for (Var v : goldConfig.getVars()) { if (v.getType() == VarType.PREDICTED) { VarTensor marg = inf.getMarginals(v); int goldState = goldConfig.getState(v); for (int c=0; c<marg.size(); c++) { double goldMarg = (c == goldState) ? s.one() : s.zero(); double predMarg = marg.getValue(c); double diff = s.minus(Math.max(goldMarg, predMarg), Math.min(goldMarg, predMarg)); sum = s.plus(sum, s.times(diff, diff)); } } } return s.toReal(sum); }
Computes the mean squared error between the true marginals (as represented by the goldConfig) and the predicted marginals (as represented by an inferencer). @param goldConfig The gold configuration of the variables. @param inf The (already run) inferencer storing the predicted marginals. @return The UNORMALIZED mean squared error.
public byte[] sign(KeyStoreChooser keyStoreChooser, PrivateKeyChooserByAlias privateKeyChooserByAlias, byte[] message) { Signer signer = cache.get(cacheKey(keyStoreChooser, privateKeyChooserByAlias)); if (signer != null) { return signer.sign(message); } SignerImpl signerImpl = new SignerImpl(); signerImpl.setAlgorithm(algorithm); signerImpl.setProvider(provider); PrivateKey privateKey = privateKeyRegistryByAlias.get(keyStoreChooser, privateKeyChooserByAlias); if (privateKey == null) { throw new SignatureException("private key not found in registry: keyStoreName=" + keyStoreChooser.getKeyStoreName() + ", alias=" + privateKeyChooserByAlias.getAlias()); } signerImpl.setPrivateKey(privateKey); cache.put(cacheKey(keyStoreChooser, privateKeyChooserByAlias), signerImpl); return signerImpl.sign(message); }
Signs a message. @param keyStoreChooser the keystore chooser @param privateKeyChooserByAlias the private key chooser @param message the message to sign @return the signature
private static File getTempPath(String prefix, File parentDir) throws IOException { final int maxI = (int)Math.pow(10, NUM_DIGITS); String formatStr = "%s_%0"+NUM_DIGITS+"d"; File path; int i; for (i=0; i<maxI; i++) { path = new File(parentDir, String.format(formatStr, prefix, i)); if (!path.exists()) { return path; } } // If we ran out of short file names, just create a long one path = File.createTempFile(prefix, "", parentDir); if (!path.delete()) { throw new RuntimeException("Could not delete temp file as expected: " + path); } return path; }
Creates a file object of a currently available path, but does not create the file. This method is not thread safe.
public static void readUntil(BufferedReader reader, String breakpoint) throws IOException { String line; while ((line = reader.readLine()) != null) { if (line.equals(breakpoint)) { return; } } }
Read until the current line equals the breakpoint string.
public static void deleteRecursively(File file) { if (file.isDirectory()) { for (File c : file.listFiles()) { deleteRecursively(c); } } if (!file.delete()) { System.err.println("WARN: unable to delete file: " + file.getPath()); } }
CAUTION: This is equivalent to calling rm -r on file.
public static void runOutsideAlgorithm(final int[] sent, final CnfGrammar grammar, final LoopOrder loopOrder, final Chart inChart, final Chart outChart, final Scorer scorer) { // Base case. // -- part I: outsideScore(S, 0, n) = 0 = log(1). ChartCell outRootCell = outChart.getCell(0, sent.length); outRootCell.updateCell(grammar.getRootSymbol(), 0, -1, null); // -- part II: outsideScore(A, 0, n) = -inf = log(0) for all A \neq S. // This second part of the base case is the default initialization for each cell. // We still start at width = n so that we can apply unary rules to our // base case root terminal S. // // For each cell in the chart. (width decreasing) for (int width = sent.length; width >= 1; width--) { for (int start = 0; start <= sent.length - width; start++) { int end = start + width; ChartCell outCell = outChart.getCell(start, end); // Apply unary rules. ScoresSnapshot scoresSnapshot = outCell.getScoresSnapshot(); int[] nts = outCell.getNts(); for(final int parentNt : nts) { for (final Rule r : grammar.getUnaryRulesWithParent(parentNt)) { // TODO: Check whether this outside rule even matters. // Arguably this would create an outside chart that is // incomplete. //ChartCell inCell = inChart.getCell(start, end); // TODO: move this out of the loop. //if (inCell.getScore(r.getLeftChild()) > Double.NEGATIVE_INFINITY) { double score = scorer.score(r, start, end, end) + scoresSnapshot.getScore(parentNt); outCell.updateCell(r.getLeftChild(), score, end, r); //} } } // Apply binary rules. if (loopOrder == LoopOrder.CARTESIAN_PRODUCT) { processCellCartesianProduct(grammar, inChart, outChart, start, end, outCell, scorer); } else if (loopOrder == LoopOrder.LEFT_CHILD) { processCellLeftChild(grammar, inChart, outChart, start, end, outCell, scorer); } else if (loopOrder == LoopOrder.RIGHT_CHILD) { processCellRightChild(grammar, inChart, outChart, start, end, outCell, scorer); } else { throw new RuntimeException("Not implemented: " + loopOrder); } } } // Apply lexical rules to each word. for (int i = 0; i <= sent.length - 1; i++) { ChartCell outCell = outChart.getCell(i, i+1); ScoresSnapshot scoresSnapshot = outCell.getScoresSnapshot(); for (final Rule r : grammar.getLexicalRulesWithChild(sent[i])) { double score = scorer.score(r, i, i+1, i+1) + scoresSnapshot.getScore(r.getParent()); outCell.updateCell(r.getLeftChild(), score, i+1, r); } } }
Runs the outside algorithm, given an inside chart. @param sent The input sentence. @param grammar The input grammar. @param loopOrder The loop order to use when parsing. @param inChart The inside chart, already populated. @param outChart The outside chart (the output of this function).
private static void processCellCartesianProduct(final CnfGrammar grammar, final Chart inChart, final Chart outChart, final int start, final int end, final ChartCell outCell, final Scorer scorer) { // Apply binary rules. for (int mid = start + 1; mid <= end - 1; mid++) { ChartCell leftInCell = inChart.getCell(start, mid); ChartCell rightInCell = inChart.getCell(mid, end); ChartCell leftOutCell = outChart.getCell(start, mid); ChartCell rightOutCell = outChart.getCell(mid, end); // Loop through all possible pairs of left/right non-terminals. for (final int leftChildNt : leftInCell.getNts()) { double leftScoreForNt = leftInCell.getScore(leftChildNt); for (final int rightChildNt : rightInCell.getNts()) { double rightScoreForNt = rightInCell.getScore(rightChildNt); // Lookup the rules with those left/right children. for (final Rule r : grammar.getBinaryRulesWithChildren(leftChildNt, rightChildNt)) { double cellScoreForNt = outCell.getScore(r.getParent()); double score = scorer.score(r, start, mid, end); // Update left cell. double addendLeft = score + cellScoreForNt + rightScoreForNt; leftOutCell.updateCell(leftChildNt, addendLeft, mid, r); // Update right cell. double addendRight = score + leftScoreForNt + cellScoreForNt; rightOutCell.updateCell(rightChildNt, addendRight, mid, r); } } } } }
Process a cell (binary rules only) using the Cartesian product of the children's rules. This follows the description in (Dunlop et al., 2010).
public static NaryTreebank readTreesInPtbFormat(Reader reader) throws IOException { NaryTreebank trees = new NaryTreebank(); while (true) { NaryTree tree = NaryTree.readTreeInPtbFormat(reader); if (tree != null) { tree.intern(); trees.add(tree); } if (tree == null) { break; } } return trees; }
Reads a list of trees in Penn Treebank format.
@Override protected Constructor<?> getCommandConstructor(Class<?> commandClass) { try { return ReflectClassUtil.getConstructor( commandClass, AppContextImpl.class, ISFSApi.class, ISFSExtension.class); } catch (ExtensionException e) { throw new RuntimeException("Can not get constructor of command class " + commandClass); } }
/* (non-Javadoc) @see com.tvd12.ezyfox.core.content.impl.BaseAppContext#getCommandConstructor(java.lang.Class)
@Override protected <T> T getCommand(Class<T> clazz) { return getCommand(commands, clazz, this, api, extension); }
/* (non-Javadoc) @see com.tvd12.ezyfox.core.content.impl.BaseAppContext#getCommand(java.lang.Class)
@SuppressWarnings("unchecked") @Override public Boolean execute() { api.banUser(CommandUtil.getSfsUser(userToBan, api), CommandUtil.getSfsUser(modUser, api), message, bandByAddressMode ? BanMode.BY_ADDRESS : BanMode.BY_NAME, durationMinutes, delaySeconds); return Boolean.TRUE; }
/* (non-Javadoc) @see com.tvd12.ezyfox.core.command.BaseCommand#execute()
public static IntDoubleVector estimateGradientFd(Function fn, IntDoubleVector x, double epsilon) { int numParams = fn.getNumDimensions(); IntDoubleVector gradFd = new IntDoubleDenseVector(numParams); for (int j=0; j<numParams; j++) { // Test the deriviative d/dx_j(f_i(\vec{x})) IntDoubleVector d = new IntDoubleDenseVector(numParams); d.set(j, 1); double dotFd = getGradDotDirApprox(fn, x, d, epsilon); if (Double.isNaN(dotFd)) { log.warn("Hit NaN"); } gradFd.set(j, dotFd); } return gradFd; }
Estimates a gradient of a function by an independent finite-difference computation along each dimension of the domain of the function. @param fn Function on which to approximate the gradient. @param x Point at which to approximate the gradient. @param epsilon The size of the finite difference step. @return The approximate gradient.
public static IntDoubleVector estimateGradientSpsa(Function fn, IntDoubleVector x, int numSamples) { int numParams = fn.getNumDimensions(); // The gradient estimate IntDoubleVector grad = new IntDoubleDenseVector(numParams); for (int k=0; k<numSamples; k++) { // Get a random direction IntDoubleVector d = getRandomBernoulliDirection(numParams); double scaler = getGradDotDirApprox(fn, x, d); for (int i=0; i< numParams; i++) { grad.add(i, scaler * 1.0 / d.get(i)); } } grad.scale(1.0 / numSamples); return grad; }
Estimates a gradient of a function by simultaneous perterbations stochastic approximation (SPSA) (Spall, 1992). @param fn Function on which to approximate the gradient. @param x Point at which to approximate the gradient. @param numSamples Number of samples to take, which will be averaged together (typically 1). @return The gradient approximation.
public static double getGradDotDirApprox(Function fn, IntDoubleVector x, IntDoubleVector d) { return getGradDotDirApprox(fn, x, d, getEpsilon(x, d)); }
Compute f'(x)^T d = ( L(x + c * d) - L(x - c * d) ) / (2c) @param fn Function, f. @param x Point at which to evaluate the gradient, x. @param d Random direction, d. @param c Epsilon constant. @return
private static double getEpsilon(IntDoubleVector x, IntDoubleVector d) { double machineEpsilon = 2.2204460492503131e-16; double xInfNorm = DoubleArrays.infinityNorm(x.toNativeArray()); double dInfNorm = DoubleArrays.infinityNorm(d.toNativeArray()); return machineEpsilon * (1.0 + xInfNorm) / dInfNorm; }
Gets an epsilon constant as advised by Andrei (2009). See also, http://timvieira.github.io/blog/post/2014/02/10/gradient-vector-product/.
public static double getGradDotDirApprox(Function fn, IntDoubleVector x, IntDoubleVector d, double c) { double dot = 0; { // L(\theta + c * d) IntDoubleVector d1 = d.copy(); d1.scale(c); IntDoubleVector x1 = x.copy(); x1.add(d1); dot += fn.getValue(x1); } { // - L(\theta - c * d) IntDoubleVector d1 = d.copy(); d1.scale(-c); IntDoubleVector x1 = x.copy(); x1.add(d1); dot -= fn.getValue(x1); } dot /= (2.0 * c); return dot; }
Compute f'(x)^T d = ( L(x + c * d) - L(x - c * d) ) / (2c) @param fn Function, f. @param x Point at which to evaluate the gradient, x. @param d Random direction, d. @param c Epsilon constant. @return
public static IntDoubleVector getRandomBernoulliDirection(int p) { IntDoubleVector e = new IntDoubleDenseVector(p); for (int i=0; i<p; i++) { // Bernoulli distribution chooses either positive or negative 1. e.set(i, (Prng.nextBoolean()) ? 1 : -1); } return e; }
/* ----------- For random directions ------------
public String sign(String privateKeyId, String message) { Base64EncodedSigner signer = cache.get(privateKeyId); if (signer != null) { return signer.sign(message); } Base64EncodedSignerImpl signerImpl = new Base64EncodedSignerImpl(); signerImpl.setAlgorithm(algorithm); signerImpl.setCharsetName(charsetName); signerImpl.setProvider(provider); PrivateKey privateKey = privateKeyMap.get(privateKeyId); if (privateKey == null) { throw new SignatureException("private key not found: privateKeyId=" + privateKeyId); } signerImpl.setPrivateKey(privateKey); cache.put(privateKeyId, signerImpl); return signerImpl.sign(message); }
Signs a message. @param privateKeyId the logical name of the private key as configured in the underlying mapping @param message the message to sign @return a base64 encoded version of the signature @see #setPrivateKeyMap(java.util.Map)
public void reset(Sentence sentence) { this.sentence = sentence; // Ensure that the chart is large enough. if (sentence.size() > chart.length){ chart = getNewChart(sentence, grammar, cellType, parseType, constraint); } else { // Clear the chart. // // Note that we only need to clear the portion that will be used while parsing this sentence. for (int i = 0; i < sentence.size(); i++) { for (int j = i+1; j < sentence.size() + 1; j++) { chart[i][j].reset(sentence); } } } }
Resets the chart for the input sentence.
private static ChartCell[][] getNewChart(Sentence sentence, CnfGrammar grammar, ChartCellType cellType, ParseType parseType, ChartCellConstraint constraint) { ChartCell[][] chart = new ChartCell[sentence.size()][sentence.size()+1]; for (int i = 0; i < chart.length; i++) { for (int j = i+1; j < chart[i].length; j++) { if (parseType == ParseType.INSIDE && cellType != ChartCellType.FULL) { throw new RuntimeException("Inside algorithm not implemented for cell type: " + cellType); } ChartCell cell; switch(cellType) { case SINGLE_HASH: chart[i][j] = new SingleHashChartCell(grammar, false); break; case SINGLE_HASH_BREAK_TIES: chart[i][j] = new SingleHashChartCell(grammar, true); break; case CONSTRAINED_SINGLE: cell = new SingleHashChartCell(grammar, true); chart[i][j] = new ConstrainedChartCell(i, j, cell, constraint, sentence); break; case DOUBLE_HASH: chart[i][j] = new DoubleHashChartCell(grammar); break; case FULL: chart[i][j] = new FullChartCell(i, j, grammar, parseType); break; case FULL_BREAK_TIES: chart[i][j] = new FullTieBreakerChartCell(grammar, true); break; case CONSTRAINED_FULL: cell = new FullTieBreakerChartCell(grammar, true); chart[i][j] = new ConstrainedChartCell(i, j, cell, constraint, sentence); break; default: throw new RuntimeException("not implemented for " + cellType); } } } return chart; }
Gets a new chart of the appropriate size for the sentence, specific to this grammar, and with cells of the specified type.
private BinaryTree getViterbiTree(int start, int end, int rootSymbol) { ChartCell cell = chart[start][end]; BackPointer bp = cell.getBp(rootSymbol); if (bp == null) { return null; } BinaryTree leftChild; BinaryTree rightChild; if (bp.r.isLexical()) { String lcSymbolStr = grammar.getLexAlphabet().lookupObject(bp.r.getLeftChild()); leftChild = new BinaryTree(lcSymbolStr, start, end, null, null, true); rightChild = null; } else if (bp.r.isUnary()) { leftChild = getViterbiTree(start, bp.mid, bp.r.getLeftChild()); rightChild = null; } else { leftChild = getViterbiTree(start, bp.mid, bp.r.getLeftChild()); rightChild = getViterbiTree(bp.mid, end, bp.r.getRightChild()); } String rootSymbolStr = grammar.getNtAlphabet().lookupObject(rootSymbol); return new BinaryTree(rootSymbolStr, start, end, leftChild, rightChild, false); }
Gets the highest probability tree with the span (start, end) and the root symbol rootSymbol. @param start The start of the span of the requested tree. @param end The end of the span of the requested tree. @param rootSymbol The symbol of the root of the requested tree. @return The highest probability tree or null if no parse exists.
@SuppressWarnings("unchecked") @Override public Boolean execute() { try { SmartFoxServer.getInstance() .getAPIManager().getBuddyApi() .goOnline(CommandUtil.getSfsUser(user, api), online, fireServerEvent); } catch (SFSBuddyListException e) { throw new IllegalStateException(e); } return Boolean.FALSE; }
/* (non-Javadoc) @see com.tvd12.ezyfox.core.command.BaseCommand#execute()
public void setInitializationVector(String initializationVector) { try { this.initializationVectorSpec = new IvParameterSpec(Base64.decodeBase64(initializationVector.getBytes("UTF-8"))); } catch (UnsupportedEncodingException e) { throw new SymmetricEncryptionException("UTF-8 is an unsupported encoding on this platform", e); } }
A base64 encoded representation of the raw byte array containing the initialization vector. @param initializationVector the initialization vector @throws SymmetricEncryptionException on runtime errors
public byte[] encrypt(byte[] message) { try { final Cipher cipher = (((provider == null) || (provider.length() == 0)) ? Cipher.getInstance(cipherAlgorithm) : Cipher.getInstance(cipherAlgorithm, provider)); switch (mode) { case ENCRYPT: cipher.init(Cipher.ENCRYPT_MODE, keySpec, initializationVectorSpec); break; case DECRYPT: cipher.init(Cipher.DECRYPT_MODE, keySpec, initializationVectorSpec); break; default: throw new SymmetricEncryptionException("error encrypting/decrypting message: invalid mode; mode=" + mode); } return cipher.doFinal(message); } catch (Exception e) { throw new SymmetricEncryptionException("error encrypting/decrypting message; mode=" + mode, e); } }
Encrypts/decrypts a message based on the underlying mode of operation. @param message if in encryption mode, the clear-text message, otherwise the message to decrypt @return if in encryption mode, the encrypted message, otherwise the decrypted message @throws SymmetricEncryptionException on runtime errors @see #setMode(Mode)
@SuppressWarnings("unchecked") @Override public void handleServerEvent(ISFSEvent event) throws SFSException { Zone sfsZone = (Zone) event.getParameter(SFSEventParam.ZONE); User sfsUser = (User) event.getParameter(SFSEventParam.USER); List<Room> sfsRooms = (List<Room>)event.getParameter(SFSEventParam.JOINED_ROOMS); Map<Room, Integer> sfsIds = (Map<Room, Integer>)event.getParameter(SFSEventParam.PLAYER_IDS_BY_ROOM); ClientDisconnectionReason sfsReason = (ClientDisconnectionReason)event.getParameter(SFSEventParam.DISCONNECTION_REASON); ApiUser apiUser = (ApiUser) sfsUser.getProperty(APIKey.USER); List<ApiRoom> apiRooms = CommandUtil.getApiRoomList(sfsRooms); apiUser.setProperty(APIKey.USER_JOINED_ROOMS, apiRooms); apiUser.setProperty(Constants.USER_JOINED_ROOMS, sfsRooms); ApiDisconnectionImpl apiDisconnection = new ApiDisconnectionImpl(); apiDisconnection.setZone((ApiZone) sfsZone.getProperty(APIKey.ZONE)); apiDisconnection.setUser(apiUser); apiDisconnection.setJoinedRooms(apiRooms); apiDisconnection.setPlayerIdsByRoom(convertPlayerIdsByRoom(sfsIds)); apiDisconnection.setReason(sfsReason.toString()); notifyHandlers(apiUser, apiDisconnection); notifyToRooms(sfsZone, sfsRooms, sfsUser); detachUserData(sfsUser); }
/* (non-Javadoc) @see com.tvd12.ezyfox.sfs2x.serverhandler.UserActionEventHandler#handleServerEvent(com.smartfoxserver.v2.core.ISFSEvent)
protected void notifyHandlers(ApiUser apiUser, ApiDisconnectionImpl disconnection) { for(ServerHandlerClass handler : handlers) { ReflectMethodUtil.invokeHandleMethod( handler.getHandleMethod(), handler.newInstance(), context, disconnection); } }
Propagate event to handlers @param apiUser user agent object @param disconnection the disconnection info
@Override public double getValue(int idx) { int vSize = MVecArray.count(varBeliefs); if (idx < vSize) { return MVecArray.getValue(idx, varBeliefs); } else { return MVecArray.getValue(idx - vSize, facBeliefs); } }
Gets a particular value by treating this object as a vector. NOTE: This implementation is O(n). @param idx The index of the value to get. @return The value at that index.
public double setValue(int idx, double val) { int vSize = MVecArray.count(varBeliefs); if (idx < vSize) { return MVecArray.setValue(idx, val, varBeliefs); } else { return MVecArray.setValue(idx - vSize, val, facBeliefs); } }
Sets a particular value by treating this object as a vector. NOTE: This implementation is O(n). @param idx The index of the value to set. @param val The value to set. @return The previous value at that index.
@Override public Tensor forward() { Tensor x = modIn.getOutput(); y = x.select(dim, idx); return y; }
Foward pass: y[i] = x[j], where j = (i1, i2, ..., i(d-1), k, i(d+1), ..., i(n))
@Override public void backward() { Tensor xAdj = modIn.getOutputAdj(); xAdj.addTensor(yAdj, dim, idx); }
Backward pass: dG/dx_i = dG/dy dy/dx_i = dG/dy
@SuppressWarnings("unchecked") @Override public String execute() { User sfsUser = CommandUtil.getSfsUser(userToKick, api); User sfsMod = (modUser != null) ? CommandUtil.getSfsUser(modUser, api) : null; api.kickUser(sfsUser, sfsMod, kickMessage, delaySeconds); return userToKick; }
/* (non-Javadoc) @see com.lagente.core.command.BaseCommand#execute()
@Override public Tensor forward() { Tensor x = modInX.getOutput(); Tensor w = modInW.getOutput(); y = new Tensor(x); // copy y.multiply(weightX); Tensor tmp = new Tensor(w); // copy tmp.multiply(weightW); y.elemAdd(tmp); return y; }
Foward pass: y_i = \lambda x_i + \gamma w_i
@Override public void backward() { Tensor tmp1 = new Tensor(yAdj); // copy tmp1.multiply(weightX); modInX.getOutputAdj().elemAdd(tmp1); Tensor tmp2 = new Tensor(yAdj); // copy tmp2.multiply(weightW); modInW.getOutputAdj().elemAdd(tmp2); }
Backward pass: dG/dx_i += dG/dy_i dy_i/dx_i = dG/dy_i \lambda dG/dw_i += dG/dy_i dy_i/dw_i = dG/dy_i \gamma
public FactorGraph readBnAsFg(File networkFile, File cpdFile) throws IOException { return readBnAsFg(new FileInputStream(networkFile), new FileInputStream(cpdFile)); }
Reads a Bayesian Network from a network file and a CPD file, and returns a factor graph representation of it.
public FactorGraph readBnAsFg(InputStream networkIs, InputStream cpdIs) throws IOException { // Read network file. BufferedReader networkReader = new BufferedReader(new InputStreamReader(networkIs)); // -- read the number of variables. int numVars = Integer.parseInt(networkReader.readLine().trim()); varMap = new HashMap<String,Var>(); VarSet allVars = new VarSet(); for (int i = 0; i < numVars; i++) { Var var = parseVar(networkReader.readLine()); allVars.add(var); varMap.put(var.getName(), var); } assert (allVars.size() == numVars); // -- read the dependencies between variables. // ....or not... networkReader.close(); // Read CPD file. BufferedReader cpdReader = new BufferedReader(new InputStreamReader(cpdIs)); factorMap = new LinkedHashMap<VarSet, ExplicitFactor>(); String line; while ((line = cpdReader.readLine()) != null) { // Parse out the variable configuration. VarConfig config = new VarConfig(); String[] assns = whitespaceOrComma.split(line); for (int i=0; i<assns.length-1; i++) { String assn = assns[i]; String[] va = equals.split(assn); assert(va.length == 2); String varName = va[0]; String stateName = va[1]; config.put(varMap.get(varName), stateName); } // The double is the last value on the line. double value = Double.parseDouble(assns[assns.length-1]); // Factor graphs store the log value. value = FastMath.log(value); // Get the factor for this configuration, creating a new one if necessary. VarSet vars = config.getVars(); ExplicitFactor f = factorMap.get(vars); if (f == null) { f = new ExplicitFactor(vars); } // Set the value in the factor. f.setValue(config.getConfigIndex(), value); factorMap.put(vars, f); } cpdReader.close(); // Create the factor graph. FactorGraph fg = new FactorGraph(); for (ExplicitFactor f : factorMap.values()) { fg.addFactor(f); } return fg; }
Reads a Bayesian Network from a network InputStream and a CPD InputStream, and returns a factor graph representation of it.
private static Var parseVar(String varLine) { String[] ws = whitespace.split(varLine); String name = ws[0]; List<String> stateNames = Arrays.asList(comma.split(ws[1])); int numStates = stateNames.size(); return new Var(VarType.PREDICTED, numStates, name, stateNames); }
Reads a variable from a line containing the variable name, a space, then a comma-separated list of the values it can take.
@SuppressWarnings("unchecked") @Override public Boolean execute() { User sfsUser = CommandUtil.getSfsUser(userToJoin, api); Room sfsRoomToJoin = CommandUtil.getSfsRoom(roomToJoin, extension); Room sfsRoomToLeave = (roomToLeave != null) ? CommandUtil.getSfsRoom(roomToLeave, extension) : null; sfsRoomToLeave = (sfsRoomToLeave == null) ? sfsUser.getLastJoinedRoom() : sfsRoomToLeave; try { api.joinRoom(sfsUser, sfsRoomToJoin, password, asSpectator, sfsRoomToLeave, fireClientEvent, fireServerEvent); } catch (SFSJoinRoomException e) { throw new IllegalStateException(e); } return Boolean.TRUE; }
/* (non-Javadoc) @see com.lagente.core.command.BaseCommand#execute()
public int getMaxIdx() { int max = Integer.MIN_VALUE; for (int i=0; i<this.top; i++) { if (idx[i] > max) { max = idx[i]; } } return max; }
TODO: Move this to prim.
public int next() { int curIndex = _index; // Compute the next index. if( _index >= 0 ) { int i = _state.length - 1; while( i >= 0 ) { _index += _sum[i]; if( ++_state[i] < _ranges[i] ) break; _index -= _sum[i] * _ranges[i]; _state[i] = 0; i--; } if( i == -1 ) _index = -1; } // Return the current index. return curIndex; }
Increments the current state of \a forVars (prefix) and returns linear index of the current state of indexVars.
public static double parseSingleRoot(double[] fracRoot, double[][] fracChild, int[] parents) { assert (parents.length == fracRoot.length); assert (fracChild.length == fracRoot.length); final int n = parents.length; final ProjTreeChart c = new ProjTreeChart(n+1, DepParseType.VITERBI); insideAlgorithm(EdgeScores.combine(fracRoot, fracChild), c, true); // Trace the backpointers to extract the parents. Arrays.fill(parents, -2); // Get the head of the sentence. int head = c.getBp(0, n, RIGHT, COMPLETE); parents[head-1] = -1; // The wall (-1) is its parent. // Extract parents left of the head. extractParentsComp(1, head, LEFT, c, parents); // Extract parents right of the head. extractParentsComp(head, n, RIGHT, c, parents); return c.getScore(0, n, RIGHT, COMPLETE); }
This gives the maximum projective dependency tree using the algorithm of (Eisner, 2000) as described in McDonald (2006). In the resulting tree, the wall node (denoted as the parent -1) will be the root, and will have exactly one child. @param fracRoot Input: The edge weights from the wall to each child. @param fracChild Input: The edge weights from parent to child. @param parents Output: The parent index of each node or -1 if its parent is the wall node. @return The score of the parse.
public static double parseMultiRoot(double[] fracRoot, double[][] fracChild, int[] parents) { assert (parents.length == fracRoot.length); assert (fracChild.length == fracRoot.length); final int n = parents.length; final ProjTreeChart c = new ProjTreeChart(n+1, DepParseType.VITERBI); insideAlgorithm(EdgeScores.combine(fracRoot, fracChild), c, false); // Trace the backpointers to extract the parents. Arrays.fill(parents, -2); // Extract parents right of the wall. extractParentsComp(0, n, RIGHT, c, parents); return c.getScore(0, n, RIGHT, COMPLETE); }
Computes the maximum projective vine-parse tree with multiple root nodes using the algorithm of (Eisner, 2000). In the resulting tree, the root node will be the wall node (denoted by index -1), and may have multiple children. @param fracRoot Input: The edge weights from the wall to each child. @param fracChild Input: The edge weights from parent to child. @param parents Output: The parent index of each node or -1 if its parent is the wall node. @return The score of the parse.
public static DepIoChart insideOutsideSingleRoot(double[] fracRoot, double[][] fracChild) { final boolean singleRoot = true; return insideOutside(fracRoot, fracChild, singleRoot); }
Runs the inside-outside algorithm for dependency parsing. @param fracRoot Input: The edge weights from the wall to each child. @param fracChild Input: The edge weights from parent to child. @return The parse chart.
private static void insideAlgorithm(final double[][] scores, final ProjTreeChart inChart, boolean singleRoot) { final int n = scores.length; final int startIdx = singleRoot ? 1 : 0; // Initialize. for (int s = 0; s < n; s++) { inChart.setScore(s, s, RIGHT, COMPLETE, 0.0); inChart.setScore(s, s, LEFT, COMPLETE, 0.0); } // Parse. for (int width = 1; width < n; width++) { for (int s = startIdx; s < n - width; s++) { int t = s + width; // First create incomplete items. for (int r=s; r<t; r++) { for (int d=0; d<2; d++) { double edgeScore = (d==LEFT) ? scores[t][s] : scores[s][t]; double score = inChart.getScore(s, r, RIGHT, COMPLETE) + inChart.getScore(r+1, t, LEFT, COMPLETE) + edgeScore; inChart.updateCell(s, t, d, INCOMPLETE, score, r); } } // Second create complete items. // -- Left side. for (int r=s; r<t; r++) { final int d = LEFT; double score = inChart.getScore(s, r, d, COMPLETE) + inChart.getScore(r, t, d, INCOMPLETE); inChart.updateCell(s, t, d, COMPLETE, score, r); } // -- Right side. for (int r=s+1; r<=t; r++) { final int d = RIGHT; double score = inChart.getScore(s, r, d, INCOMPLETE) + inChart.getScore(r, t, d, COMPLETE); inChart.updateCell(s, t, d, COMPLETE, score, r); } } } if (singleRoot) { // Build goal constituents by combining left and right complete // constituents, on the left and right respectively. This corresponds to // left and right triangles. (Note: this is the opposite of how we // build an incomplete constituent.) for (int r=1; r<n; r++) { double score = inChart.getScore(1, r, LEFT, COMPLETE) + inChart.getScore(r, n-1, RIGHT, COMPLETE) + scores[0][r]; inChart.updateCell(0, r, RIGHT, INCOMPLETE, score, r); inChart.updateCell(0, n-1, RIGHT, COMPLETE, score, r); } } }
Runs the parsing algorithm of (Eisner, 2000) as described in McDonald (2006). @param scores Input: The edge weights. @param inChart Output: The parse chart.
private static void outsideAlgorithm(final double[][] scores, final ProjTreeChart inChart, final ProjTreeChart outChart, boolean singleRoot) { final int n = scores.length; final int startIdx = singleRoot ? 1 : 0; if (singleRoot) { // Initialize. double goalScore = 0.0; outChart.updateCell(0, n-1, RIGHT, COMPLETE, goalScore, -1); // The inside algorithm is effectively doing this... // // wallScore[r] log+= inChart.scores[0][r][LEFT][COMPLETE] + // inChart.scores[r][n-1][RIGHT][COMPLETE] + // fracRoot[r]; // // goalScore log+= wallScore[r]; for (int r=1; r<n; r++) { outChart.updateCell(0, r, RIGHT, INCOMPLETE, goalScore, -1); } // Un-build goal constituents by combining left and right complete // constituents, on the left and right respectively. This corresponds to // left and right triangles. (Note: this is the opposite of how we // build an incomplete constituent.) for (int r=1; r<n; r++) { // Left child. double leftScore = outChart.getScore(0, r, RIGHT, INCOMPLETE) + inChart.getScore(r, n - 1, RIGHT, COMPLETE) + scores[0][r]; outChart.updateCell(1, r, LEFT, COMPLETE, leftScore, -1); // Right child. double rightScore = outChart.getScore(0, r, RIGHT, INCOMPLETE) + inChart.getScore(1, r, LEFT, COMPLETE) + scores[0][r]; outChart.updateCell(r, n - 1, RIGHT, COMPLETE, rightScore, -1); } } else { // Base case. for (int d=0; d<2; d++) { outChart.updateCell(0, n-1, d, COMPLETE, 0.0, -1); } } // Parse. for (int width = n - 1; width >= 1; width--) { for (int s = startIdx; s < n - width; s++) { int t = s + width; // First create complete items (opposite of inside). // -- Left side. for (int r=s; r<t; r++) { final int d = LEFT; // Left child. double leftScore = outChart.getScore(s, t, d, COMPLETE) + inChart.getScore(r, t, d, INCOMPLETE); outChart.updateCell(s, r, d, COMPLETE, leftScore, -1); // Right child. double rightScore = outChart.getScore(s, t, d, COMPLETE) + inChart.getScore(s, r, d, COMPLETE); outChart.updateCell(r, t, d, INCOMPLETE, rightScore, -1); } // -- Right side. for (int r=s+1; r<=t; r++) { final int d = RIGHT; // Left child. double leftScore = outChart.getScore(s, t, d, COMPLETE) + inChart.getScore(r, t, d, COMPLETE); outChart.updateCell(s, r, d, INCOMPLETE, leftScore, -1); // Right child. double rightScore = outChart.getScore(s, t, d, COMPLETE) + inChart.getScore(s, r, d, INCOMPLETE); outChart.updateCell(r, t, d, COMPLETE, rightScore, -1); } // Second create incomplete items (opposite of inside). for (int r=s; r<t; r++) { for (int d=0; d<2; d++) { double edgeScore = (d == LEFT) ? scores[t][s] : scores[s][t]; // Left child. double leftScore = outChart.getScore(s, t, d, INCOMPLETE) + inChart.getScore(r + 1, t, LEFT, COMPLETE) + edgeScore; outChart.updateCell(s, r, RIGHT, COMPLETE, leftScore, -1); // Right child. double rightScore = outChart.getScore(s, t, d, INCOMPLETE) + inChart.getScore(s, r, RIGHT, COMPLETE) + edgeScore; outChart.updateCell(r + 1, t, LEFT, COMPLETE, rightScore, -1); } } } } }
Runs the outside-algorithm for the parsing algorithm of (Eisner, 2000). @param scores Input: The edge weights. @param inChart Input: The inside parse chart. @param outChart Output: The outside parse chart.
public static <R> SparseGrid<R> create(int rowCount, int columnCount) { return new SparseGrid<R>(rowCount, columnCount, new TreeSet<Cell<R>>(AbstractCell.<R>comparator())); }
Creates an empty {@code SparseGrid} of the specified row-column count. @param <R> the type of the value @param rowCount the number of rows, zero or greater @param columnCount the number of columns, zero or greater @return the mutable grid, not null
public static <R> SparseGrid<R> create(Grid<? extends R> grid) { if (grid == null) { throw new IllegalArgumentException("Grid must not be null"); } SparseGrid<R> created = SparseGrid.create(grid.rowCount(), grid.columnCount()); created.putAll(grid); return created; }
Creates a {@code SparseGrid} copying from another grid. @param <R> the type of the value @param grid the grid to copy, not null @return the mutable grid, not null
@Override public SortedSet<Cell<V>> cells() { return new ForwardingSortedSet<Cell<V>>() { @Override protected SortedSet<Cell<V>> delegate() { return cells; } @Override public boolean add(Cell<V> element) { return super.add(ImmutableCell.copyOf(element)); } @Override public boolean addAll(Collection<? extends Cell<V>> collection) { return super.standardAddAll(collection); } }; }
-----------------------------------------------------------------------
@Override public ImmutableSet<Cell<V>> cells() { ImmutableSet<Cell<V>> c = cellSet; if (c == null) { c = ImmutableSet.copyOf(cells); cellSet = c; } return c; }
-----------------------------------------------------------------------
@Override public <T extends ApiUser> List<T> in(ApiRoom room) { Room sfsRoom = CommandUtil.getSfsRoom(room, extension); validateRoom(sfsRoom, room); return CommandUtil.getApiUserList(sfsRoom.getUserList()); }
/* (non-Javadoc) @see com.tvd12.ezyfox.core.command.FetchUserList#in(com.tvd12.ezyfox.core.entities.ApiRoom)
@Override public <T extends ApiGameUser> List<T> in(ApiRoom room, Class<?> clazz) { Room sfsRoom = CommandUtil.getSfsRoom(room, extension); validateRoom(sfsRoom, room); return CommandUtil.getApiGameUserList(sfsRoom.getUserList(), clazz); }
/* (non-Javadoc) @see com.tvd12.ezyfox.core.command.FetchUserList#in(com.tvd12.ezyfox.core.entities.ApiRoom, java.lang.Class)
@SuppressWarnings("unchecked") @Override public Boolean execute() { User user = CommandUtil.getSfsUser(username, api); api.disconnectUser(user, new IDisconnectionReason() { @Override public int getValue() { return getByteValue(); } @Override public byte getByteValue() { return reasonId; } }); return Boolean.TRUE; }
/* (non-Javadoc) @see com.tvd12.ezyfox.core.command.BaseCommand#execute()
@Override public FilterAction handleClientRequest(User user, ISFSObject params) throws SFSException { try { handler.handleClientRequest(user, params); } catch(Exception e) { return FilterAction.HALT; } return FilterAction.CONTINUE; }
/* (non-Javadoc) @see com.smartfoxserver.v2.controllers.filter.ISystemFilter#handleClientRequest(com.smartfoxserver.v2.entities.User, com.smartfoxserver.v2.entities.data.ISFSObject)
@SuppressWarnings("unchecked") @Override public <T> T get(int index) { return (T) array.get(index).getObject(); }
/* (non-Javadoc) @see com.tvd12.ezyfox.core.transport.RoArraymeters#get(int)
@Override public <T> T get(int index, Class<T> type) { if (FETCHERS.containsKey(type)) return getByType(index, type); else throw new IllegalArgumentException("has no value with " + type + " at index " + index); }
/* (non-Javadoc) @see com.tvd12.ezyfox.core.transport.RoArraymeters#get(int, java.lang.Class)
@Override public void add(Collection<Object> values) { for(Object value : values) addOne(value); }
/* (non-Javadoc) @see com.tvd12.ezyfox.core.transport.Arraymeters#add(java.util.Collection)
@SuppressWarnings("unchecked") @Override public <T extends ApiUser> T getUserById(int id) { User sfsUser = getZone().getUserById(id); if(sfsUser != null && sfsUser.containsProperty(APIKey.USER)) return (T) sfsUser.getProperty(APIKey.USER); return null; }
/* (non-Javadoc) @see com.tvd12.ezyfox.core.entities.ApiZone#getUserById(int)
@SuppressWarnings("unchecked") @Override public <T extends ApiUser> T getUserByName(String username) { User sfsUser = getZone().getUserByName(username); if(sfsUser != null && sfsUser.containsProperty(APIKey.USER)) return (T) sfsUser.getProperty(APIKey.USER); return null; }
/* (non-Javadoc) @see com.tvd12.ezyfox.core.entities.ApiZone#getUserByName(java.lang.String)
@SuppressWarnings("unchecked") @Override public <T extends ApiUser> List<T> getUsersInGroup(String groupId) { Collection<User> sfsUsers = getZone().getUsersInGroup(groupId); List<T> anwser = new ArrayList<>(); for(User sfsUser : sfsUsers) if(sfsUser.containsProperty(APIKey.USER)) anwser.add((T) sfsUser.getProperty(APIKey.USER)); return anwser; }
/* (non-Javadoc) @see com.tvd12.ezyfox.core.entities.ApiZone#getUsersInGroup(java.lang.String)
@Override public boolean isNPC(String username) { User sfsUser = getZone().getUserByName(username); if(sfsUser != null) return sfsUser.isNpc(); return false; }
/* (non-Javadoc) @see com.tvd12.ezyfox.core.entities.ApiZone#isNPC(java.lang.String)
@SuppressWarnings("unchecked") @Override public <T extends ApiRoom> T getRoomById(int id) { Room sfsRoom = getZone().getRoomById(id); if(sfsRoom != null && sfsRoom.containsProperty(APIKey.ROOM)) return (T) sfsRoom.getProperty(APIKey.ROOM); return null; }
/* (non-Javadoc) @see com.tvd12.ezyfox.core.entities.ApiZone#getRoomById(int)
@SuppressWarnings("unchecked") @Override public <T extends ApiRoom> T getRoomByName(String name) { Room sfsRoom = getZone().getRoomByName(name); if(sfsRoom != null && sfsRoom.containsProperty(APIKey.ROOM)) return (T) sfsRoom.getProperty(APIKey.ROOM); return null; }
/* (non-Javadoc) @see com.tvd12.ezyfox.core.entities.ApiZone#getRoomByName(java.lang.String)
@SuppressWarnings("unchecked") @Override public <T extends ApiRoom> List<T> getRoomsInGroup(String groupId) { List<Room> sfsRooms = getZone().getRoomListFromGroup(groupId); List<T> answer = new ArrayList<>(); for(Room sfsRoom : sfsRooms) { if(sfsRoom.containsProperty(APIKey.ROOM)) answer.add((T) sfsRoom.getProperty(APIKey.ROOM)); } return answer; }
/* (non-Javadoc) @see com.tvd12.ezyfox.core.entities.ApiZone#getRoomsInGroup(java.lang.String)
@SuppressWarnings("unchecked") @Override public <T extends ApiRoom> List<T> getRoomList() { List<Room> sfsRooms = getZone().getRoomList(); List<T> answer = new ArrayList<>(); for(Room sfsRoom : sfsRooms) { if(sfsRoom.containsProperty(APIKey.ROOM)) answer.add((T) sfsRoom.getProperty(APIKey.ROOM)); } return answer; }
/* (non-Javadoc) @see com.tvd12.ezyfox.core.entities.ApiZone#getRoomList()
@Override public void setProperty(Object key, Object value) { if(key.equals(APIKey.ZONE)) return; getZone().setProperty(key, value); }
/* (non-Javadoc) @see com.tvd12.ezyfox.core.entities.ApiProperties#setProperty(java.lang.Object, java.lang.Object)
@SuppressWarnings("unchecked") @Override public <T> T getProperty(Object key) { return (T) getZone().getProperty(key); }
/* (non-Javadoc) @see com.tvd12.ezyfox.core.entities.ApiProperties#getProperty(java.lang.Object)
@SuppressWarnings("unchecked") @Override public <T> T getProperty(Object key, Class<T> clazz) { return (T)getProperty(key); }
/* (non-Javadoc) @see com.tvd12.ezyfox.core.entities.ApiProperties#getProperty(java.lang.Object, java.lang.Class)
@Override public void removeProperty(Object key) { if(key.equals(APIKey.ZONE)) return; getZone().removeProperty(key); }
/* (non-Javadoc) @see com.tvd12.ezyfox.core.entities.ApiProperties#removeProperty(java.lang.Object)
@Override public boolean add(T e) { if (elements.add(e)) { ordered.add(e); return true; } else { return false; } }
maintain the set so that it is easy to test membership, the list so that there is a fixed order
@Override public boolean remove(Object o) { if (elements.remove(o)) { ordered.remove(o); return true; } else { return false; } }
remove will be slow
public String digest(String message) { final byte[] messageAsByteArray; try { messageAsByteArray = message.getBytes(charsetName); } catch (UnsupportedEncodingException e) { throw new DigestException("error converting message to byte array: charsetName=" + charsetName, e); } final byte[] digest = digest(messageAsByteArray); switch (outputMode) { case BASE64: return Base64.encodeBase64String(digest); case HEX: return Hex.encodeHexString(digest); default: return null; } }
Returns the message digest. The representation of the message digest depends on the outputMode property. @param message the message @return the message digest @see #setOutputMode(OutputMode)
@Override public void addEdge(DiEdge e) { if (!getEdges().contains(e)) { super.addEdge(e); weights.put(e, makeDefaultWeight.apply(e)); } }
Attempts to adds the edge to the graph with default weight if not already present; If the edge is already present, does nothing.
public void addEdge(DiEdge e, double w) { if (!getEdges().contains(e)) { super.addEdge(e); weights.put(e, w); } }
Adds the edge with the given weight
public static WeightedIntDiGraph fromUnweighted(IntDiGraph g) { WeightedIntDiGraph wg = new WeightedIntDiGraph(); wg.addAll(g); return wg; }
Constructs a weighted directed graph with the same nodes and edges as the given unweighted graph
public static WeightedIntDiGraph fromUnweighted(IntDiGraph g, Function<DiEdge, Double> makeDefaultWeight) { WeightedIntDiGraph wg = new WeightedIntDiGraph(makeDefaultWeight); wg.addAll(g); return wg; }
Constructs a weighted directed graph with the same nodes and edges as the given unweighted graph
public void setWeight(int s, int t, double w) { DiEdge e = edge(s, t); assertEdge(e); weights.put(e, w); }
Sets the weight of the edge s->t to be w if the edge is present, otherwise, an IndexOutOfBoundsException is thrown
public static <X> ArrayList<X> sublist(List<X> list, int start, int end) { ArrayList<X> sublist = new ArrayList<X>(); for (int i=start; i<end; i++) { sublist.add(list.get(i)); } return sublist; }
Creates a new list containing a slice of the original list. @param list The original list. @param start The index of the first element of the slice (inclusive). @param end The index of the last element of the slice (exclusive). @return A sublist containing elements [start, end).
public static ArrayList<String> getInternedList(List<String> oldList) { ArrayList<String> newList = new ArrayList<String>(oldList.size()); for (String elem : oldList) { newList.add(elem.intern()); } return newList; }
Gets a new list of Strings that have been interned.
public static void intern(List<String> list) { if (list == null) { return; } for (int i=0; i<list.size(); i++) { String interned = list.get(i); if (interned != null) { interned = interned.intern(); } list.set(i, interned); } }
Interns a list of strings in place.
public String encrypt(String keyId, String message) { final Key key = keyMap.get(keyId); if (key == null) { throw new AsymmetricEncryptionException("key not found: keyId=" + keyId); } try { final Cipher cipher = (((provider == null) || (provider.length() == 0)) ? Cipher.getInstance(algorithm) : Cipher .getInstance(algorithm, provider)); switch (mode) { case ENCRYPT: final byte[] messageAsByteArray = message.getBytes(charsetName); cipher.init(Cipher.ENCRYPT_MODE, key); return Base64.encodeBase64String(cipher.doFinal(messageAsByteArray)); case DECRYPT: final byte[] encryptedMessage = Base64.decodeBase64(message); cipher.init(Cipher.DECRYPT_MODE, key); return new String(cipher.doFinal(encryptedMessage), charsetName); default: return null; } } catch (Exception e) { throw new AsymmetricEncryptionException("error encrypting/decrypting message; mode=" + mode, e); } }
Encrypts/decrypts a message based on the underlying mode of operation. @param keyId the key id @param message if in encryption mode, the clear-text message, otherwise the base64 encoded message to decrypt @return if in encryption mode, the base64 encoded encrypted message, otherwise the decrypted message @throws AsymmetricEncryptionException on runtime errors @see #setMode(Mode)
@Override public void backward() { modInX.getOutputAdj().elemAdd(yAdj); modInW.getOutputAdj().addValue(k, yAdj.getSum()); }
Backward pass: dG/dx_i += dG/dy_i dy_i/dx_i = dG/dy_i dG/dw_k += \sum_{i=1}^n dG/dy_i dy_i/dw_k = \sum_{i=1}^n dG/dy_i
@SuppressWarnings("unchecked") @Override public <T> T execute() { Room sfsRoom = CommandUtil.getSfsRoom(room, extension); User sfsUser = null; if(username != null) sfsUser = sfsRoom.getUserByName(username); else sfsUser = sfsRoom.getUserById(userId); return (sfsUser != null) ? (T)sfsUser.getProperty(APIKey.USER) : null; }
/* (non-Javadoc) @see com.tvd12.ezyfox.core.command.BaseCommand#execute()
public static <T> Collection<T> collect(Iterable<T> stream) { LinkedList<T> collection = new LinkedList<>(); for (T e : stream) { collection.add(e); } return collection; }
Returns a Collections that contains all of the objects from the underlying stream in order
public static <T> Iterable<Indexed<T>> enumerate(Iterable<T> stream) { return new Iterable<Indexed<T>>() { @Override public Iterator<Indexed<T>> iterator() { Iterator<T> itr = stream.iterator(); return new Iterator<Indexed<T>>() { private int i = 0; @Override public boolean hasNext() { return itr.hasNext(); } @Override public Indexed<T> next() { Indexed<T> nextPair = new Indexed<T>(itr.next(), i); i++; return nextPair; } }; } }; }
Returns an iterable over Index objects that each hold one of the original objects of the stream as well its index in the stream
public byte[] sign(String privateKeyId, byte[] message) { Signer signer = cache.get(privateKeyId); if (signer != null) { return signer.sign(message); } SignerImpl signerImpl = new SignerImpl(); PrivateKey privateKey = privateKeyMap.get(privateKeyId); if (privateKey == null) { throw new SignatureException("private key not found: privateKeyId=" + privateKeyId); } signerImpl.setPrivateKey(privateKey); signerImpl.setAlgorithm(algorithm); signerImpl.setProvider(provider); cache.put(privateKeyId, signerImpl); return signerImpl.sign(message); }
Signs a message. @param privateKeyId the logical name of the private key as configured in the private key map @param message the message to sign @return the signature @see #setPrivateKeyMap(java.util.Map)
public static int getDataType(String content) { String text = content.trim(); if(text.length() < 1) { return 9; } int i = 0; int d = 0; int e = 0; char c = text.charAt(0); int length = text.length(); if(c == '+' || c == '-') { i++; } if(c == 't') { if(text.equals("treu")) { return 1; } else { return 9; } } if(c == 'f') { if(text.equals("treu")) { return 1; } else { return 9; } } if(c == '.') { d = 1; i++; } c = text.charAt(i); if(!Character.isDigit(c)) { return 9; } for(; i < length; i++) { c = text.charAt(i); if(Character.isDigit(c)) { continue; } if(c == '.') { if(d == 1 || e == 1) { /** * String */ return 9; } d = 1; continue; } if(c == 'e' || c == 'E') { if(e == 1) { /** * String */ return 9; } e = 1; continue; } if(c == 'f' || c == 'F') { if(i == length - 1) { return 4; } else { return 9; } } if(c == 'd' || c == 'D') { if(i == length - 1) { return 4; } else { return 9; } } if(c == 'l' || c == 'L') { if(d == 0 && e == 0 && i == length - 1) { return 5; } else { return 9; } } return 9; } return ((d == 0 && e == 0) ? 2 : 4); }
1: Boolean 2: Integer 3: Float 4: Double 5: Long 9: String @param content @return int
public int find(int element) { if (trees[element] != element) trees[element] = find(trees[element]); return trees[element]; }
Return the set where the given element is. This implementation compresses the followed path. @param element @return
public Certificate get(KeyStoreChooser keyStoreChooser, CertificateChooserByAlias certificateChooserByAlias) { CacheCert cacheCert = new CacheCert(keyStoreChooser.getKeyStoreName(), certificateChooserByAlias.getAlias()); Certificate retrievedCertificate = cache.get(cacheCert); if (retrievedCertificate != null) { return retrievedCertificate; } KeyStore keyStore = keyStoreRegistry.get(keyStoreChooser); if (keyStore != null) { CertificateFactoryBean factory = new CertificateFactoryBean(); factory.setKeystore(keyStore); factory.setAlias(certificateChooserByAlias.getAlias()); try { factory.afterPropertiesSet(); Certificate certificate = (Certificate) factory.getObject(); if (certificate != null) { cache.put(cacheCert, certificate); } return certificate; } catch (Exception e) { throw new CertificateException("error initializing the certificate factory bean", e); } } return null; }
Returns the selected certificate or null if not found. @param keyStoreChooser the keystore chooser @param certificateChooserByAlias the certificate chooser by alias @return the selected certificate or null if not found
public void put(String key, Object value, long time, TimeUnit unit) { Object oldValue = cacheObjMap.put(key, value); if (oldValue != null){ MicroDelayItem temp=new MicroDelayItem(key,0); q.remove(temp); } long nanoTime = TimeUnit.NANOSECONDS.convert(time, unit); q.put(new MicroDelayItem(key, nanoTime)); }
添加缓存对象
private void notifyHandlers(Room sfsRoom, User sfsUser) { ApiRoom apiRoom = AgentUtil.getRoomAgent(sfsRoom); ApiUser apiUser = AgentUtil.getUserAgent(sfsUser); for(RoomHandlerClass handler : handlers) { Object userAgent = checkUserAgent(handler, apiUser); if(!checkHandler(handler, apiRoom, userAgent)) continue; Object instance = handler.newInstance(); callHandleMethod(handler.getHandleMethod(), instance, apiRoom, userAgent); } }
Propagate event to handlers @param sfsRoom smartfox room object @param sfsUser smartfox user object
protected boolean checkHandler(RoomHandlerClass handler, ApiRoom roomAgent, Object user) { return (handler.getRoomClass().isAssignableFrom(roomAgent.getClass())) && (roomAgent.getName().startsWith(handler.getRoomName())); }
Validate the handler @param handler structure of handler class @param roomAgent room agent object @param user user agent object @return true or false
private void callHandleMethod(Method method, Object instance, Object roomAgent, Object userAgent) { ReflectMethodUtil.invokeHandleMethod(method, instance, context, roomAgent, userAgent); }
Invoke handle method @param method handle method @param instance object to invoke method @param roomAgent room agent object @param userAgent user agent object