public static Hashtable findConfidence(Hashtable table) {
    Hashtable confidences = new Hashtable();
    Iterator key_iter = table.keySet().iterator();
    while (key_iter.hasNext()) {
      // System.out.println("here");
      ArrayList<Integer> combo = (ArrayList<Integer>) key_iter.next();
      // System.out.println("current combo"+combo);
      if (combo.size() >= 2) {
        ArrayList<Integer> current_combo =
            new ArrayList<Integer>(combo.subList(0, combo.size() - 1));
        ArrayList<Integer> last_combo =
            new ArrayList<Integer>(combo.subList(combo.size() - 1, combo.size()));
        /*System.out.println(combo);
        System.out.println(current_combo);
        System.out.println(last_combo);
        System.out.println(table.get(current_combo));*/

        if (table.get(current_combo) != null) {
          // System.out.println("it contains!");
          int first = (Integer) table.get(current_combo);
          int second = (Integer) table.get(combo);
          double dub_first = (double) first;
          double dub_second = (double) second;
          double combo_conf = dub_second / dub_first;
          confidences.put(combo, combo_conf);
          // System.out.println("combo:"+combo+" has the confience: "+combo_conf);
        }
      }
    }
    // System.out.println(confidences+"O");

    return confidences;
  }
Exemple #2
0
 public static void main(String[] args) {
   try {
     if (args.length == 1) {
       URL url = new URL(args[0]);
       System.out.println("Content-Type: " + url.openConnection().getContentType());
       // 				Vector links = extractLinks(url);
       // 				for (int n = 0; n < links.size(); n++) {
       // 					System.out.println((String) links.elementAt(n));
       // 				}
       Set links = extractLinksWithText(url).entrySet();
       Iterator it = links.iterator();
       while (it.hasNext()) {
         Map.Entry en = (Map.Entry) it.next();
         String strLink = (String) en.getKey();
         String strText = (String) en.getValue();
         System.out.println(strLink + " \"" + strText + "\" ");
       }
       return;
     } else if (args.length == 2) {
       writeURLtoFile(new URL(args[0]), args[1]);
       return;
     }
   } catch (Exception e) {
     System.err.println("An error occured: ");
     e.printStackTrace();
     // 			System.err.println(e.toString());
   }
   System.err.println("Usage: java SaveURL <url> [<file>]");
   System.err.println("Saves a URL to a file.");
   System.err.println("If no file is given, extracts hyperlinks on url to console.");
 }
Exemple #3
0
  private void installParameters(boolean isStatic, String className) throws TypeException {
    Type type;
    // add a binding for the helper so we can call builtin static methods
    type = typeGroup.create(helperClass.getName());
    Binding ruleBinding = bindings.lookup("$$");
    if (ruleBinding != null) {
      ruleBinding.setType(type);
    } else {
      bindings.append(new Binding(this, "$$", type));
    }

    if (!isStatic) {
      Binding recipientBinding = bindings.lookup("$0");
      if (recipientBinding != null) {
        type = typeGroup.create(className);
        if (type.isUndefined()) {
          throw new TypeException(
              "Rule.installParameters : Rule " + name + " unable to load class " + className);
        }
        recipientBinding.setType(type);
      }
    }

    String returnTypeName = Type.parseMethodReturnType(triggerDescriptor);

    returnType = typeGroup.create(returnTypeName);

    Iterator<Binding> iterator = bindings.iterator();

    while (iterator.hasNext()) {
      Binding binding = iterator.next();
      // these bindings are typed via the descriptor installed during trigger injection
      // note that the return type has to be done this way because it may represent the
      // trigger method return type or the invoke method return type
      if (binding.isParam() || binding.isLocalVar() || binding.isReturn()) {
        String typeName = binding.getDescriptor();
        String[] typeAndArrayBounds = typeName.split("\\[");
        Type baseType = typeGroup.create(typeAndArrayBounds[0]);
        Type fullType = baseType;
        if (baseType.isUndefined()) {
          throw new TypeException(
              "Rule.installParameters : Rule " + name + " unable to load class " + baseType);
        }
        for (int i = 1; i < typeAndArrayBounds.length; i++) {
          fullType = typeGroup.createArray(fullType);
        }
        binding.setType(fullType);
      } else if (binding.isThrowable()) {
        // TODO -- enable a more precise specification of the throwable type
        // we need to be able to obtain the type descriptor for the throw operation
        binding.setType(typeGroup.ensureType(Throwable.class));
      } else if (binding.isParamCount()) {
        binding.setType(Type.I);
      } else if (binding.isParamArray() || binding.isInvokeParamArray()) {
        binding.setType(Type.OBJECT.arrayType());
      } else if (binding.isTriggerClass() || binding.isTriggerMethod()) {
        binding.setType(Type.STRING);
      }
    }
  }
  public ListIterator<ICFLibAnyObj> enumerateDetails(MssCFGenContext genContext) {
    final String S_ProcName = "CFAsteriskMssCFIterateHostNodeConfFile.enumerateDetails() ";

    if (genContext == null) {
      throw CFLib.getDefaultExceptionFactory()
          .newNullArgumentException(getClass(), S_ProcName, 1, "genContext");
    }

    ICFLibAnyObj genDef = genContext.getGenDef();
    if (genDef == null) {
      throw CFLib.getDefaultExceptionFactory()
          .newNullArgumentException(getClass(), S_ProcName, 1, "genContext.getGenDef()");
    }

    List<ICFLibAnyObj> list = new LinkedList<ICFLibAnyObj>();

    if (genDef instanceof ICFAsteriskHostNodeObj) {
      Iterator<ICFAsteriskConfigurationFileObj> elements =
          ((ICFAsteriskHostNodeObj) genDef).getOptionalComponentsConfFile().iterator();
      while (elements.hasNext()) {
        list.add(elements.next());
      }
    } else {
      throw CFLib.getDefaultExceptionFactory()
          .newUnsupportedClassException(
              getClass(), S_ProcName, "genContext.getGenDef()", genDef, "ICFAsteriskHostNodeObj");
    }

    return (list.listIterator());
  }
Exemple #5
0
  // ---------------------------------------------------------------------------
  private void writeCache() {
    try {
      Debug.print("Writing cache");
      FileOutputStream fos = new FileOutputStream(m_cacheFile);
      ObjectOutputStream oos = new ObjectOutputStream(fos);

      oos.writeObject(m_depCache);

      oos.writeInt(m_newModificationCache.size());

      Iterator<String> it = m_newModificationCache.keySet().iterator();

      while (it.hasNext()) {
        String key = it.next();

        oos.writeUTF(key);
        oos.writeLong(m_newModificationCache.get(key));
      }

      oos.close();
    } catch (Exception e) {
      Debug.print(e.getMessage());
      StringWriter sw = new StringWriter();
      e.printStackTrace(new PrintWriter(sw));
      Debug.print(sw.toString());
    }
  }
  /*
   * show software components
   */
  protected void showComponents(
      HttpServletRequest request, HttpServletResponse response, HttpSession session)
      throws IOException, ServletException {
    Iterator compIterator;
    int rowID = 1;

    VendorDBConnector vendorDBConnector = new VendorDBConnector();
    compIterator =
        vendorDBConnector.getSoftwareComponents((String) session.getAttribute("name")).iterator();

    response.setContentType("text/xml; charset=UTF-8");
    PrintWriter out = response.getWriter();
    out.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
    out.write("<rows>");

    while (compIterator.hasNext()) {
      SoftwareComponent comp = (SoftwareComponent) compIterator.next();
      out.write(
          "<row id=\""
              + (rowID++)
              + "_"
              + comp.getSoftwareID()
              + "_"
              + comp.getName()
              + "\">"
              + "<cell style='font-weight:bold;color: #055A78;'>"
              + comp.getName()
              + "</cell><cell>"
              + comp.getVersion()
              + "</cell>"
              // + "<cell>Delete^../VendorManager?op=delete_software&amp;software_id="+
              // comp.getSoftwareID()+ "^_self</cell>"
              + "<cell>Delete Software^javascript:deletesoftcomp("
              + comp.getSoftwareID()
              + ")^_self</cell>"
              // + "<cell>Update^../VendorManager?op=load_software_reg&amp;software_id=" +
              // comp.getSoftwareID()
              // + "&amp;software_name=" + comp.getName() + "&amp;software_version=" +
              // comp.getVersion()
              // + "^_self</cell>"
              + "<cell type=\"img\">../js/dhtmlxSuite/dhtmlxTree/codebase/imgs/xsd.png^Schemas^../DIController?op=show_schema&amp;xsd="
              + rowID
              + "_"
              + comp.getNum_xsds()
              + "_"
              + comp.getSoftwareID()
              + "^_self</cell>"
              + "<cell type=\"img\">../js/dhtmlxSuite/dhtmlxTree/codebase/imgs/wsdl.png^Services^../DIController?op=show_service&amp;service="
              + rowID
              + "_"
              + comp.getNum_services()
              + "_"
              + comp.getSoftwareID()
              + "^_self</cell>"
              + "</row>");
    }

    out.write("</rows>");
    out.flush();
  }
    /** @see Graph#getAllEdges(Object, Object) */
    public Set<E> getAllEdges(V sourceVertex, V targetVertex) {
      Set<E> edges = null;

      if (containsVertex(sourceVertex) && containsVertex(targetVertex)) {
        edges = new ArrayUnenforcedSet<E>();

        Iterator<E> iter = getEdgeContainer(sourceVertex).vertexEdges.iterator();

        while (iter.hasNext()) {
          E e = iter.next();

          boolean equalStraight =
              sourceVertex.equals(getEdgeSource(e)) && targetVertex.equals(getEdgeTarget(e));

          boolean equalInverted =
              sourceVertex.equals(getEdgeTarget(e)) && targetVertex.equals(getEdgeSource(e));

          if (equalStraight || equalInverted) {
            edges.add(e);
          }
        }
      }

      return edges;
    }
  public static String[] parseString(String text, String seperator) {
    Vector vResult = new Vector();
    if (text == null || "".equals(text)) {
      return null;
    }
    String tempStr = text.trim();
    String currentLabel = null;
    int index = tempStr.indexOf(seperator);
    while (index != -1) {
      currentLabel = tempStr.substring(0, index).trim();

      if (!"".equals(currentLabel)) {
        vResult.addElement(currentLabel);
      }
      tempStr = tempStr.substring(index + 1);
      index = tempStr.indexOf(seperator);
    } // Last label
    currentLabel = tempStr.trim();
    if (!"".equals(currentLabel)) {
      vResult.addElement(currentLabel);
    }
    String[] re = new String[vResult.size()];
    Iterator it = vResult.iterator();
    index = 0;
    while (it.hasNext()) {
      re[index] = (String) it.next();
      index++;
    }
    return re;
  }
Exemple #9
0
  protected int processModifiers(List l) {
    int modifier = 0;
    Iterator it = l.iterator();

    while (it.hasNext()) {
      Object t = it.next();
      if (t instanceof AAbstractModifier) modifier |= Modifier.ABSTRACT;
      else if (t instanceof AFinalModifier) modifier |= Modifier.FINAL;
      else if (t instanceof ANativeModifier) modifier |= Modifier.NATIVE;
      else if (t instanceof APublicModifier) modifier |= Modifier.PUBLIC;
      else if (t instanceof AProtectedModifier) modifier |= Modifier.PROTECTED;
      else if (t instanceof APrivateModifier) modifier |= Modifier.PRIVATE;
      else if (t instanceof AStaticModifier) modifier |= Modifier.STATIC;
      else if (t instanceof ASynchronizedModifier) modifier |= Modifier.SYNCHRONIZED;
      else if (t instanceof ATransientModifier) modifier |= Modifier.TRANSIENT;
      else if (t instanceof AVolatileModifier) modifier |= Modifier.VOLATILE;
      else if (t instanceof AEnumModifier) modifier |= Modifier.ENUM;
      else if (t instanceof AAnnotationModifier) modifier |= Modifier.ANNOTATION;
      else
        throw new RuntimeException(
            "Impossible: modifier unknown - Have you added a new modifier and not updated this file?");
    }

    return modifier;
  }
  /**
   * Compares this LTS to another for debugging purposes.
   *
   * @param other the other LTS to compare to
   * @return <code>true</code> if these are equivalent
   */
  public boolean compare(LetterToSound other) {

    // compare letter index table
    //
    for (Iterator i = letterIndex.keySet().iterator(); i.hasNext(); ) {
      String key = (String) i.next();
      Integer thisIndex = (Integer) letterIndex.get(key);
      Integer otherIndex = (Integer) other.letterIndex.get(key);
      if (!thisIndex.equals(otherIndex)) {
        if (RiTa.PRINT_LTS_INFO) System.err.println("[WARN] LTSengine -> Bad index: " + key);
        return false;
      }
    }

    // compare states
    //
    for (int i = 0; i < stateMachine.length; i++) {
      State state = getState(i);
      State otherState = other.getState(i);
      if (!state.compare(otherState)) {
        if (RiTa.PRINT_LTS_INFO) System.err.println("[WARN] LTSengine -> Bad state: " + i);
        return false;
      }
    }

    return true;
  }
 private void writeContent(final int end, final List childElements, final int depth)
     throws IOException {
   // sets index to end
   for (final Iterator i = childElements.iterator(); i.hasNext(); ) {
     final Element element = (Element) i.next();
     final int elementBegin = element.begin;
     if (elementBegin >= end) break;
     if (indentAllElements) {
       writeText(elementBegin, depth);
       writeElement(element, depth, end, false, false);
     } else {
       if (inlinable(element)) continue; // skip over elements that can be inlined.
       writeText(elementBegin, depth);
       final String elementName = element.getName();
       if (elementName == HTMLElementName.PRE || elementName == HTMLElementName.TEXTAREA) {
         writeElement(element, depth, end, true, true);
       } else if (elementName == HTMLElementName.SCRIPT) {
         writeElement(element, depth, end, true, false);
       } else {
         writeElement(
             element,
             depth,
             end,
             false,
             !removeLineBreaks && containsOnlyInlineLevelChildElements(element));
       }
     }
   }
   writeText(end, depth);
 }
  public ListIterator<ICFLibAnyObj> enumerateDetails(MssCFGenContext genContext) {
    final String S_ProcName = "CFBamMssCFIterateNumberTypeRef.enumerateDetails() ";

    if (genContext == null) {
      throw CFLib.getDefaultExceptionFactory()
          .newNullArgumentException(getClass(), S_ProcName, 1, "genContext");
    }

    ICFLibAnyObj genDef = genContext.getGenDef();
    if (genDef == null) {
      throw CFLib.getDefaultExceptionFactory()
          .newNullArgumentException(getClass(), S_ProcName, 1, "genContext.getGenDef()");
    }

    List<ICFLibAnyObj> list = new LinkedList<ICFLibAnyObj>();

    if (genDef instanceof ICFBamNumberTypeObj) {
      Iterator<ICFBamTableColObj> elements =
          ((ICFBamNumberTypeObj) genDef).getOptionalChildrenRef().iterator();
      while (elements.hasNext()) {
        list.add(elements.next());
      }
    } else {
      throw CFLib.getDefaultExceptionFactory()
          .newUnsupportedClassException(
              getClass(), S_ProcName, "genContext.getGenDef()", genDef, "ICFBamNumberTypeObj");
    }

    return (list.listIterator());
  }
 protected final AbstractAudioChunk findChunk(List<AbstractAudioChunk> chunks, Class c) {
   for (Iterator<AbstractAudioChunk> i = chunks.iterator(); i.hasNext(); ) {
     AbstractAudioChunk chunk = i.next();
     if (c.isInstance(chunk)) return chunk;
   }
   return null;
 }
Exemple #14
0
  /**
   * Reload the composite nodes of the circuit, this is recursive
   *
   * @param g the graphics that will paint the node
   * @throws CircuitLoadingException if the internal circuit can not be loaded
   */
  public void reloadCompositeNodes(Graphics g) throws CircuitLoadingException {
    for (iterNodes = this.nodes.iterator(); iterNodes.hasNext(); ) {
      Node n = iterNodes.next();

      if (n.getCategoryID() == Node.COMPOSITE) ((CompositeNode) n).reload(g);
    }
  }
  /**
   * Use the completors to modify the buffer with the appropriate completions.
   *
   * @return true if successful
   */
  private final boolean complete() throws IOException {
    // debug ("tab for (" + buf + ")");
    if (completors.size() == 0) {
      return false;
    }

    List candidates = new LinkedList();
    String bufstr = buf.buffer.toString();
    int cursor = buf.cursor;

    int position = -1;

    for (Iterator i = completors.iterator(); i.hasNext(); ) {
      Completor comp = (Completor) i.next();

      if ((position = comp.complete(bufstr, cursor, candidates)) != -1) {
        break;
      }
    }

    // no candidates? Fail.
    if (candidates.size() == 0) {
      return false;
    }

    return completionHandler.complete(this, candidates, position);
  }
Exemple #16
0
 // -----------------------------------------------------------
 // for "SrvRqst"
 // find the matched URLs with (type, scope, predicate, ltag)
 // return: error code (short)
 //         number of matched URLs (short)
 //         URL blocks (decided bt previous #URL)
 // -----------------------------------------------------------
 public synchronized byte[] getMatchedURL(String type, String scope, String pred, String ltag) {
   byte[] buf = null;
   int ecode = Const.OK;
   if (!Util.shareString(daf.getScope(), scope, ",")) {
     ecode = Const.SCOPE_NOT_SUPPORTED;
   }
   b.reset();
   try {
     int count = 0;
     d.writeShort(ecode); // error code
     d.writeShort(count); // URL count, place holder
     if (ecode == Const.OK) { // no error, find matched URLs
       Iterator values = table.values().iterator();
       while (values.hasNext()) {
         Entry e = (Entry) values.next();
         if (e.match(type, scope, pred, ltag)) {
           count++;
           d.writeByte(0);
           d.writeShort(e.getLifetime());
           d.writeShort(e.getURL().length());
           d.writeBytes(e.getURL());
           d.writeByte(0);
         }
       }
     }
     buf = b.toByteArray();
     if (count > 0) Util.writeInt(buf, 2, count, 2); // update count
   } catch (Exception e) {
     if (ServiceLocationManager.displayMSLPTrace) e.printStackTrace();
   }
   return buf;
 }
Exemple #17
0
 // ------------------------------------------------
 // save database to either the stdout or the file
 // ------------------------------------------------
 public synchronized void saveDatabase(BufferedWriter o) {
   Iterator values = table.values().iterator();
   while (values.hasNext()) {
     Entry e = (Entry) values.next();
     e.prtEntry(daf, o);
   }
 }
  public SecurityToken logon(
      String anEndpointReference, String aUserName, String aPassword, String anApplicationID)
      throws LogonManagerException, SOAPException, IOException {
    SecurityToken result;
    SOAPMessage message;
    SOAPConnection conn = null;

    try {
      result = null;
      String request =
          REQUEST_FORMAT.format(
              ((Object) (new Object[] {fURL, aUserName, aPassword, anEndpointReference})));
      message =
          MessageFactory.newInstance()
              .createMessage(new MimeHeaders(), new ByteArrayInputStream(request.getBytes()));
      conn = SOAPConnectionFactory.newInstance().createConnection();
      SOAPMessage response = conn.call(message, fURL);
      SOAPBody body = response.getSOAPBody();
      if (body.hasFault()) throw new LogonManagerException(body.getFault());
      result = new SecurityToken();
      result.setSOAPBody(body);
      for (Iterator it = body.getChildElements(); it.hasNext(); fill(result, (Node) it.next())) ;
      return result;
    } finally {
      if (conn != null) conn.close();
    }
  }
  /** Loads streamhost address and ports from the proxies on the local server. */
  private void initStreamHosts() {
    List<Bytestream.StreamHost> streamHosts = new ArrayList<Bytestream.StreamHost>();
    Iterator it = proxies.iterator();
    IQ query;
    PacketCollector collector;
    Bytestream response;
    while (it.hasNext()) {
      String jid = it.next().toString();
      query =
          new IQ() {
            public String getChildElementXML() {
              return "<query xmlns=\"http://jabber.org/protocol/bytestreams\"/>";
            }
          };
      query.setType(IQ.Type.GET);
      query.setTo(jid);

      collector = connection.createPacketCollector(new PacketIDFilter(query.getPacketID()));
      connection.sendPacket(query);

      response = (Bytestream) collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
      if (response != null) {
        streamHosts.addAll(response.getStreamHosts());
      }
      collector.cancel();
    }
    this.streamHosts = streamHosts;
  }
 private void commandMethods(StringTokenizer t) throws NoSessionException {
   if (!t.hasMoreTokens()) {
     env.error("No class specified.");
     return;
   }
   String idClass = t.nextToken();
   ReferenceType cls = findClass(idClass);
   if (cls != null) {
     List<Method> methods = cls.allMethods();
     OutputSink out = env.getOutputSink();
     for (int i = 0; i < methods.size(); i++) {
       Method method = methods.get(i);
       out.print(method.declaringType().name() + " " + method.name() + "(");
       Iterator<String> it = method.argumentTypeNames().iterator();
       if (it.hasNext()) {
         while (true) {
           out.print(it.next());
           if (!it.hasNext()) {
             break;
           }
           out.print(", ");
         }
       }
       out.println(")");
     }
     out.show();
   } else {
     // ### Should validate class name syntax.
     env.failure("\"" + idClass + "\" is not a valid id or class name.");
   }
 }
  /** INTERNAL: Transform the object-level value into a database-level value */
  public Object getFieldValue(Object objectValue, AbstractSession session) {
    DatabaseMapping mapping = getMapping();
    Object fieldValue = objectValue;
    if ((mapping != null)
        && (mapping.isDirectToFieldMapping() || mapping.isDirectCollectionMapping())) {
      // CR#3623207, check for IN Collection here not in mapping.
      if (objectValue instanceof Collection) {
        // This can actually be a collection for IN within expressions... however it would be better
        // for expressions to handle this.
        Collection values = (Collection) objectValue;
        Vector fieldValues = new Vector(values.size());
        for (Iterator iterator = values.iterator(); iterator.hasNext(); ) {
          Object value = iterator.next();
          if (!(value instanceof Expression)) {
            value = getFieldValue(value, session);
          }
          fieldValues.add(value);
        }
        fieldValue = fieldValues;
      } else {
        if (mapping.isDirectToFieldMapping()) {
          fieldValue = ((AbstractDirectMapping) mapping).getFieldValue(objectValue, session);
        } else if (mapping.isDirectCollectionMapping()) {
          fieldValue = ((DirectCollectionMapping) mapping).getFieldValue(objectValue, session);
        }
      }
    }

    return fieldValue;
  }
Exemple #22
0
  static synchronized String sourceLine(Location location, int lineNumber) throws IOException {
    if (lineNumber == -1) {
      throw new IllegalArgumentException();
    }

    try {
      String fileName = location.sourceName();

      Iterator<SourceCode> iter = sourceCache.iterator();
      SourceCode code = null;
      while (iter.hasNext()) {
        SourceCode candidate = iter.next();
        if (candidate.fileName().equals(fileName)) {
          code = candidate;
          iter.remove();
          break;
        }
      }
      if (code == null) {
        BufferedReader reader = sourceReader(location);
        if (reader == null) {
          throw new FileNotFoundException(fileName);
        }
        code = new SourceCode(fileName, reader);
        if (sourceCache.size() == SOURCE_CACHE_SIZE) {
          sourceCache.remove(sourceCache.size() - 1);
        }
      }
      sourceCache.add(0, code);
      return code.sourceLine(lineNumber);
    } catch (AbsentInformationException e) {
      throw new IllegalArgumentException();
    }
  }
 /**
  * Notifies the listeners to refresh the screen
  *
  * @param ne the edge that has been removed
  */
 protected void notifyListenersOfRemove(NamedEdge ne) {
   Iterator i = listeners.iterator();
   while (i.hasNext()) {
     WorkingMemoryListener wml = (WorkingMemoryListener) i.next();
     wml.WMERemoved(new WorkingMemoryEvent(ne));
   }
 }
    @Override
    public void reduce(Text key, Iterable<HMapStIW> values, Context context)
        throws IOException, InterruptedException {
      Iterator<HMapStIW> iter = values.iterator();
      HMapStIW map = new HMapStIW();

      while (iter.hasNext()) {
        map.plus(iter.next());
      }

      HMapStFW writeMap = new HMapStFW();

      double pmi = 0.0;
      for (MapKI.Entry<String> entry : map.entrySet()) {
        String k = entry.getKey();

        if (map.get(k) >= 10) {
          if (wordCounts.containsKey(key.toString()) && wordCounts.containsKey(k)) {
            int px = wordCounts.get(key.toString());
            int py = wordCounts.get(k);
            pmi = Math.log10(((double) (map.get(k)) / (px * py)) * wordCounts.get("numLines*"));
            writeMap.put(k, (float) pmi);
          }
        }
      }
      if (writeMap.size() > 0) {
        context.write(key, writeMap);
      }
    }
Exemple #25
0
  /**
   * This function prints a parsed TCRL refinement law. Only for debug purposes
   *
   * @param r The AST object
   */
  public static void printRefFunction(TCRL_AST r) {

    System.out.println();
    System.out.println("**************************************************");
    System.out.println("RefFunction");
    System.out.println("**************************************************");
    System.out.println("Nombre: " + r.getName());
    System.out.println("Preambulo: " + r.getPreamble());
    System.out.println("Reglas: ");

    NodeRules rules = r.getRules();
    NodeRule rule;

    Set<String> keys = rules.getKeys();
    Iterator<String> iter = keys.iterator();

    while (iter.hasNext()) {
      rule = rules.getRule(iter.next());

      if (rule instanceof RuleSynonym) {
        printRuleSynonym((RuleSynonym) rule);
      } else {
        printRuleRefinement((RuleRefinement) rule);
      }
    }
  }
  /**
   * Reload properties. This clears out the existing entries, loads the main properties file and
   * then adds any additional properties there may be (usually from zip files). This is used
   * internally by addProps() and removeProps().
   */
  private synchronized void reload() {
    // clear out old entries
    clear();

    // read from the primary file
    if (file != null && file.exists()) {
      FileInputStream bpin = null;

      try {
        bpin = new FileInputStream(file);
        load(bpin);
      } catch (Exception x) {
        System.err.println("Error reading properties from file " + file + ": " + x);
      } finally {
        try {
          bpin.close();
        } catch (Exception ignore) {
          // ignored
        }
      }
    }

    // read additional properties from zip files, if available
    if (additionalProps != null) {
      for (Iterator i = additionalProps.values().iterator(); i.hasNext(); )
        putAll((Properties) i.next());
    }

    lastread = System.currentTimeMillis();
  }
  private String getSingleLineOfChildren(final List children) {
    final StringBuilder result = new StringBuilder();
    final Iterator childrenIt = children.iterator();
    boolean isFirst = true;

    while (childrenIt.hasNext()) {
      final Object child = childrenIt.next();

      if (!(child instanceof ContentNode)) {
        return null;
      } else {
        String content = child.toString();

        // if first item trims it from left
        if (isFirst) {
          content = Utils.ltrim(content);
        }

        // if last item trims it from right
        if (!childrenIt.hasNext()) {
          content = Utils.rtrim(content);
        }

        if (content.indexOf('\n') >= 0 || content.indexOf('\r') >= 0) {
          return null;
        }
        result.append(content);
      }

      isFirst = false;
    }

    return result.toString();
  }
Exemple #28
0
 // ----------------------------------------------------------------------
 // for "SrvTypeRqst"
 // get the list of service types for specified scope & naming authority
 // ----------------------------------------------------------------------
 public synchronized String getServiceTypeList(String na, String scope) {
   Vector typelist = new Vector(5);
   Iterator values = table.values().iterator();
   while (values.hasNext()) {
     Entry e = (Entry) values.next();
     if (!e.getDeleted()
         && // nor deleted
         scope.equalsIgnoreCase(e.getScope())
         && // match scope
         (na.equals("*")
             || // NA wildcard
             na.equalsIgnoreCase(e.getNA()))
         && // match NA
         !typelist.contains(e.getType())) {
       typelist.addElement(e.getType());
     }
   }
   StringBuffer tl = new StringBuffer();
   for (int i = 0; i < typelist.size(); i++) {
     String s = (String) typelist.elementAt(i);
     if (tl.length() > 0) tl.append(",");
     tl.append(s);
   }
   return tl.toString();
 }
Exemple #29
0
  static void itTest4(Map s, int size, int pos) {
    IdentityHashMap seen = new IdentityHashMap(size);
    reallyAssert(s.size() == size);
    int sum = 0;
    timer.start("Iter XEntry            ", size);
    Iterator it = s.entrySet().iterator();
    Object k = null;
    Object v = null;
    for (int i = 0; i < size - pos; ++i) {
      Map.Entry x = (Map.Entry) (it.next());
      k = x.getKey();
      v = x.getValue();
      seen.put(k, k);
      if (x != MISSING) ++sum;
    }
    reallyAssert(s.containsKey(k));
    it.remove();
    reallyAssert(!s.containsKey(k));
    while (it.hasNext()) {
      Map.Entry x = (Map.Entry) (it.next());
      Object k2 = x.getKey();
      seen.put(k2, k2);
      if (x != MISSING) ++sum;
    }

    reallyAssert(s.size() == size - 1);
    s.put(k, v);
    reallyAssert(seen.size() == size);
    timer.finish();
    reallyAssert(sum == size);
    reallyAssert(s.size() == size);
  }
  /**
   * Prints the given map with nice line breaks.
   *
   * @param out the stream to print to
   * @param key the key that maps to the map in some other map
   * @param map the map to print
   */
  public static synchronized void debugPrint(PrintStream out, Object key, Map map) {
    debugPrintIndent(out);
    out.println(key + " = ");

    debugPrintIndent(out);
    out.println("{");
    ++debugIndent;

    for (Iterator iter = map.entrySet().iterator(); iter.hasNext(); ) {
      Map.Entry entry = (Map.Entry) iter.next();
      String childKey = (String) entry.getKey();
      Object childValue = entry.getValue();
      if (childValue instanceof Map) {
        verbosePrint(out, childKey, (Map) childValue);
      } else {
        debugPrintIndent(out);

        String typeName = (childValue != null) ? childValue.getClass().getName() : null;

        out.println(childKey + " = " + childValue + " class: " + typeName);
      }
    }
    --debugIndent;
    debugPrintIndent(out);
    out.println("}");
  }