public RowMutation mutationForKey( ByteBuffer key, String keyspace, Long timestamp, ThriftClientState clientState, List<ByteBuffer> variables, CFMetaData metadata) throws InvalidRequestException { RowMutation rm = new RowMutation(keyspace, key); QueryProcessor.validateKeyAlias(metadata, keyName); AbstractType<?> comparator = metadata.getComparatorFor(null); if (columns.size() < 1) { // No columns, delete the row rm.delete( new QueryPath(columnFamily), (timestamp == null) ? getTimestamp(clientState) : timestamp); } else { // Delete specific columns for (Term column : columns) { ByteBuffer columnName = column.getByteBuffer(comparator, variables); validateColumnName(columnName); rm.delete( new QueryPath(columnFamily, null, columnName), (timestamp == null) ? getTimestamp(clientState) : timestamp); } } return rm; }
public boolean runTest(IEnv env) { try { TermSystem general = TermWare.getInstance().getRoot().resolveSystem("general"); Term t = TermWare.getInstance().getTermFactory().createParsedTerm("neq(p(x),p(x))"); Term r = general.reduce(t); if (!(r.isBoolean() && r.getBoolean() == false)) { System.out.println("r1=" + TermHelper.termToString(r)); return false; } t = TermWare.getInstance().getTermFactory().createParsedTerm("neq(p(\"x\"),p(\"x\"))"); r = general.reduce(t); if (r.isBoolean()) { if (r.getBoolean() == false) { return true; } else { return false; } } else { System.out.println("r2=" + TermHelper.termToString(r)); return false; } } catch (TermWareException ex) { ex.printStackTrace(); return false; } }
@Override public int hashCode() { int hash = sort.hashCode() + cons.hashCode(); for (Term t : contents) hash += t.hashCode(); return hash; }
public Set<Term> getDistinguishedVariables() { Set<Term> vars = new HashSet<Term>(); for (Term term : this.head.getTerms()) { if (term.isVariable()) vars.add(term); } return vars; }
/** * Try to make a new compound from two term. Called by the inference rules. * * @param term1 The first compoment * @param term2 The first compoment * @param memory Reference to the memory * @return A compound generated or a term it reduced to */ public static Term make(Term term1, Term term2, Memory memory) { TreeSet<Term> set; if ((term1 instanceof SetInt) && (term2 instanceof SetInt)) { set = new TreeSet<>(((CompoundTerm) term1).cloneTermsList()); set.addAll(((CompoundTerm) term2).cloneTermsList()); // set union return SetInt.make(set, memory); } if ((term1 instanceof SetExt) && (term2 instanceof SetExt)) { set = new TreeSet<>(((CompoundTerm) term1).cloneTermsList()); set.retainAll(((CompoundTerm) term2).cloneTermsList()); // set intersection return SetExt.make(set, memory); } if (term1 instanceof IntersectionExt) { set = new TreeSet<>(((CompoundTerm) term1).cloneTermsList()); if (term2 instanceof IntersectionExt) { set.addAll(((CompoundTerm) term2).cloneTermsList()); } // (&,(&,P,Q),(&,R,S)) = (&,P,Q,R,S) else { set.add(term2.clone()); } // (&,(&,P,Q),R) = (&,P,Q,R) } else if (term2 instanceof IntersectionExt) { set = new TreeSet<>(((CompoundTerm) term2).cloneTermsList()); set.add(term1.clone()); // (&,R,(&,P,Q)) = (&,P,Q,R) } else { set = new TreeSet<>(); set.add(term1.clone()); set.add(term2.clone()); } return make(set, memory); }
public void dump() { for (String s : uri2term.keySet()) { Term t = uri2term.get(s); System.out.println( s + " " + t.getAcn() + " " + t.getLabel() + " " + t.getChildren() + " " + t.getParents()); } }
public boolean atom_length_2(Term arg0, Term len) throws PrologError { arg0 = arg0.getTerm(); if (arg0 instanceof Var) throw PrologError.instantiation_error(engine.getEngineManager(), 1); if (!arg0.isAtom()) throw PrologError.type_error(engine.getEngineManager(), 1, "atom", arg0); Struct atom = (Struct) arg0; return unify(len, new Int(atom.getName().length())); }
public boolean makeOverlapSubst(Term t, Substitution theta) { if (equals(t)) return true; // check for the same constant if (args.length == 0) { // we are a constant if (t instanceof LogicalVar) { // they are a variable // can try to unify the other way return t.makeOverlapSubst(this, theta); } return false; } if (t instanceof FuncAppTerm) { FuncAppTerm ft = (FuncAppTerm) t; if (f != ft.f || args.length != ft.args.length) return false; for (int i = 0; i < args.length; i++) { if ((args[i] instanceof Term) && (ft.args[i] instanceof Term)) { Term arg = (Term) args[i]; if (!arg.makeOverlapSubst((Term) ft.args[i], theta)) { return false; } } } return true; } return false; }
@Override public void visit(SetUpdate setUpdate) { setUpdate.base().accept(this); for (Term key : setUpdate.removeSet()) { key.accept(this); } }
public static Term wrap(Term t, String label, Ellipses ellipses) { Cell cell = new Cell(t.getLocation(), t.getFilename()); cell.setLabel(label); cell.setEllipses(ellipses); cell.setContents(t); return cell; }
@Override public void visit(KCollectionFragment kCollectionFragment) { for (Term term : kCollectionFragment) { term.accept(this); } visit((Collection) kCollectionFragment); }
@Override public void backtrack() { if (!immutable) { head.backtrack(); tail.backtrack(); } }
private void findAliases(Term primeTerm, String target, String prefix) { Morpher morpher = null; try { morpher = new Morpher(target); if (morpher.getData()) { Set<String> aliases = new HashSet<String>(); for (Morpher.Morph morph : morpher.getAllMorph()) { if (morph == null) { return; } String alias = prefix + morph.text; if (morph != null && !alias.isEmpty() && !alias.equals(primeTerm.getName())) { if (!aliases.contains(alias)) { TermMorph termMorph = commonDao.get(TermMorph.class, alias); if (termMorph == null) { commonDao.save(new TermMorph(alias, primeTerm.getUri())); log.info("Alias added: " + alias); } aliases.add(alias); } } } /* for (Map.Entry<String, Term> entry : aliases.entrySet()) { if (primeTerm.getUri().equals(entry.getValue().generateUri())) continue; commonDao.save(new Link(primeTerm, entry.getValue(), Link.ALIAS, Link.MORPHEME_WEIGHT)); }*/ } } catch (Exception e) { log.throwing(getClass().getName(), "findAliases", e); throw new RuntimeException(e); } }
/** Gets a copy of this variable. */ Term copy(AbstractMap vMap, AbstractMap substMap) { Var v; Object temp = vMap.get(this); if (temp == null) { v = new Var( null, Var.PROGRESSIVE, vMap.size(), timestamp); // name,Var.PROGRESSIVE,vMap.size(),timestamp); vMap.put(this, v); } else { v = (Var) temp; } Term t = getTerm(); if (t instanceof Var) { Object tt = substMap.get(t); if (tt == null) { substMap.put(t, v); v.link = null; } else { v.link = (tt != v) ? (Var) tt : null; } } if (t instanceof Struct) { v.link = t.copy(vMap, substMap); } if (t instanceof Number) v.link = t; return v; }
/** * var unification. * * <p>First, verify the Term eventually already unified with the same Var if the Term exist, unify * var with that term, in order to handle situation as (A = p(X) , A = p(1)) which must produce * X/1. * * <p>If instead the var is not already unified, then: * * <p>if the Term is a var bound to X, then try unification with X so for example if A=1, B=A then * B is unified to 1 and not to A (note that it's coherent with chronological backtracking: the * eventually backtracked A unification is always after backtracking of B unification. * * <p>if are the same Var, unification must succeed, but without any new bindings (to avoid cycles * for extends in A = B, B = A) * * <p>if the term is a number, then it's a success and new link is created (retractable by means * of a code) * * <p>if the term is a compound, then occur check test is executed: the var must not appear in the * compound ( avoid X=p(X), or p(X,X)=p(Y,f(Y)) ); if occur check is ok then it's success and a * new link is created (retractable by a code) */ boolean unify(List vl1, List vl2, Term t) { Term tt = getTerm(); if (tt == this) { t = t.getTerm(); if (t instanceof Var) { if (this == t) { try { vl1.add(this); } catch (NullPointerException e) { /* vl1==null mean nothing intresting for the caller */ } return true; } } else if (t instanceof Struct) { // occur-check if (occurCheck(vl2, (Struct) t)) { return false; } } else if (!(t instanceof Number)) { return false; } link = t; try { vl1.add(this); } catch (NullPointerException e) { /* vl1==null mean nothing intresting for the caller */ } // System.out.println("VAR "+name+" BOUND to "+link+" - time: "+time+" - mark: "+mark); return true; } else { return (tt.unify(vl1, vl2, t)); } }
// Updates indexes, deleting informations about the last removed clause public void unregister(ClauseInfo ci) { Term clause = ci.getHead(); if (clause instanceof Struct) { Struct g = (Struct) clause.getTerm(); if (g.getArity() == 0) { return; } Term t = g.getArg(0).getTerm(); if (t instanceof Var) { numCompClausesIndex.removeShared(ci); constantCompClausesIndex.removeShared(ci); structCompClausesIndex.removeShared(ci); listCompClausesList.remove(ci); } else if (t.isAtomic()) { if (t instanceof Number) { numCompClausesIndex.delete((Number) t, ci); } else if (t instanceof Struct) { constantCompClausesIndex.delete(((Struct) t).getName(), ci); } } else if (t instanceof Struct) { if (t.isList()) { listCompClausesList.remove(ci); } else { structCompClausesIndex.delete(((Struct) t).getPredicateIndicator(), ci); } } } }
/** * Inference between a compound term and a statement * * @param compound The compound term * @param index The location of the current term in the compound * @param statement The statement * @param side The location of the current term in the statement * @param beliefTerm The content of the belief * @param memory Reference to the memory */ private static void compoundAndStatement( CompoundTerm compound, short index, Statement statement, short side, Term beliefTerm, Memory memory) { Term component = compound.componentAt(index); Task task = memory.currentTask; if (component.getClass() == statement.getClass()) { if ((compound instanceof Conjunction) && (memory.currentBelief != null)) { if (Variable.unify(Symbols.VAR_DEPENDENT, component, statement, compound, statement)) { SyllogisticRules.elimiVarDep(compound, component, statement.equals(beliefTerm), memory); } else if (task.getSentence().isJudgment()) { CompositionalRules.introVarInner(statement, (Statement) component, compound, memory); } } } else { if (!task.isStructural() && task.getSentence().isJudgment()) { if (statement instanceof Inheritance) { StructuralRules.structuralCompose1(compound, index, statement, memory); // if (!(compound instanceof SetExt) && !(compound instanceof SetInt)) // { if (!(compound instanceof SetExt || compound instanceof SetInt || compound instanceof Negation)) { StructuralRules.structuralCompose2(compound, index, statement, side, memory); } // {A --> B, A @ (A&C)} |- (A&C) --> (B&C) } else if ((statement instanceof Similarity) && !(compound instanceof Conjunction)) { StructuralRules.structuralCompose2(compound, index, statement, side, memory); } // {A <-> B, A @ (A&C)} |- (A&C) <-> (B&C) } } }
/** Concatenates terms of sort Set to this builder */ public void concatenate(Term... terms) { for (Term term : terms) { if (!term.sort().equals(Sort.SET)) { throw KEMException.criticalError( "unexpected sort " + term.sort() + " of concatenated term " + term + "; expected " + Sort.SET); } if (term instanceof BuiltinSet) { BuiltinSet set = (BuiltinSet) term; elements.addAll(set.elements); patternsBuilder.addAll(set.collectionPatterns); functionsBuilder.addAll(set.collectionFunctions); variablesBuilder.addAll(set.collectionVariables); } else if (term instanceof KItem && ((KLabel) ((KItem) term).kLabel()).isPattern()) { patternsBuilder.add((KItem) term); } else if (term instanceof KItem && ((KLabel) ((KItem) term).kLabel()).isFunction()) { functionsBuilder.add(term); } else if (term instanceof Variable) { variablesBuilder.add((Variable) term); } else { throw KEMException.criticalError("unexpected concatenated term" + term); } } }
/* Term */ public boolean unify(Term t, Trail trail) { t = t.dereference(); if (t.isVariable()) { ((VariableTerm) t).bind(this, trail); return true; } return eq(this, t); }
public boolean isGround() { Term t = getTerm(); if (t == this) { return false; } else { return t.isGround(); } }
public boolean isEmptyList() { Term t = getTerm(); if (t == this) { return false; } else { return t.isEmptyList(); } }
public String toString(QueryFormatter f) { String ret = ""; for (Term t : terms()) { if (!ret.isEmpty()) ret += " " + getOp() + " "; ret += t.toString(f); } return (terms().size() > 1 ? "(" + ret + ")" : ret); }
public static String getName(String categoryId, String TermId) { Term term = getTerm(categoryId, TermId); if (term == null) { return ""; } return term.getName(); }
@Override public boolean contains(Object o) { if (o instanceof Bracket) return contains(((Bracket) o).getContent()); if (o instanceof Cast) return contains(((Cast) o).getContent()); if (!(o instanceof KApp)) return false; KApp k = (KApp) o; return label.contains(k.label) && child.contains(k.child); }
/** Resolve the occurence of variables in a Term */ long resolveTerm(long count) { Term tt = getTerm(); if (tt != this) { return tt.resolveTerm(count); } else { timestamp = count; return count++; } }
protected Node checkReachability(Term n) throws SemanticException { FlowGraph g = currentFlowGraph(); if (g != null) { Collection peers = g.peers(n); if (peers != null && !peers.isEmpty()) { boolean isInitializer = (n instanceof Initializer); for (Iterator iter = peers.iterator(); iter.hasNext(); ) { FlowGraph.Peer p = (FlowGraph.Peer) iter.next(); // the peer is reachable if at least one of its out items // is reachable. This would cover all cases, except that some // peers may have no successors (e.g. peers that throw an // an exception that is not caught by the method). So we need // to also check the inItem. if (p.inItem() != null) { DataFlowItem dfi = (DataFlowItem) p.inItem(); // there will only be one peer for an initializer, // as it cannot occur in a finally block. if (isInitializer && !dfi.normalReachable) { throw new SemanticException( "Initializers must be able to complete normally.", n.position()); } if (dfi.reachable) { return n.reachable(true); } } if (p.outItems != null) { for (Iterator k = p.outItems.values().iterator(); k.hasNext(); ) { DataFlowItem item = (DataFlowItem) k.next(); if (item != null && item.reachable) { // n is reachable. return n.reachable(true); } } } } // if we fall through to here, then no peer for n was reachable. n = n.reachable(false); // Compound statements are allowed to be unreachable // (e.g., "{ // return; }" or "while (true) S"). If a compound // statement is truly unreachable, one of its sub-statements will // be also and we will report an error there. if ((n instanceof Block && ((Block) n).statements().isEmpty()) || (n instanceof Stmt && !(n instanceof CompoundStmt))) { throw new SemanticException("Unreachable statement.", n.position()); } } } return n; }
public boolean isEqual(Term t) { Term tt = getTerm(); if (tt == this) { t = t.getTerm(); return (t instanceof Var && timestamp == ((Var) t).timestamp); } else { return tt.isEqual(t); } }
public static String getIdByHiddenValue(String categoryId, String hiddenValue) { List<Term> termList = getTermList(categoryId); for (Term term : termList) { if (hiddenValue.equals(term.getHiddenValue())) { return term.getId(); } } return ""; }
public int countConstantTerms() { int ctr = 0; for (@NotNull Term term : terms) { if (term.isConstant()) { ctr++; } } return ctr; }
public static Term min(Iterable<? extends Term> iterable) { Term min = null; for (Term t : iterable) { if (min == null || t.name().compareTo(min.name()) < 0) { min = t; } } return min; }