Ejemplo n.º 1
1
  /**
   * If the outbound level is BINARY, convert the string field to binary, then pad to the left with
   * the appropriate number of zero bits to reach a number of bits specified by the bitLength
   * attribute of the TDT definition file.
   */
  private void binaryPadding(Map<String, String> extraparams, Field tdtfield) {
    String fieldname = tdtfield.getName();
    int reqbitlength = tdtfield.getBitLength();
    String value;

    String binaryValue = fieldToBinary(tdtfield, extraparams);
    if (binaryValue.length() < reqbitlength) {
      int extraBitLength = reqbitlength - binaryValue.length();

      StringBuilder zeroPaddedBinaryValue = new StringBuilder("");
      for (int i = 0; i < extraBitLength; i++) {
        zeroPaddedBinaryValue.append("0");
      }
      zeroPaddedBinaryValue.append(binaryValue);
      value = zeroPaddedBinaryValue.toString();
    } else {
      if (binaryValue.length() > reqbitlength)
        throw new TDTException(
            "Binary value ["
                + binaryValue
                + "] for field "
                + fieldname
                + " exceeds maximum allowed "
                + reqbitlength
                + " bits.  Decimal value was "
                + extraparams.get(fieldname));

      value = binaryValue;
    }
    extraparams.put(fieldname, value);
  }
Ejemplo n.º 2
1
  /** {@inheritDoc} */
  protected void getNewMonitors(Map<String, Monitor> map) throws MonitorException {
    assert Thread.holdsLock(this);

    int used = prologue.getUsed();
    long modificationTime = prologue.getModificationTimeStamp();

    if ((used > lastUsed) || (lastModificationTime > modificationTime)) {

      lastUsed = used;
      lastModificationTime = modificationTime;

      Monitor monitor = getNextMonitorEntry();
      while (monitor != null) {
        String name = monitor.getName();

        // guard against duplicate entries
        if (!map.containsKey(name)) {
          map.put(name, monitor);

          /*
           * insertedMonitors is null when called from pollFor()
           * via buildMonitorMap(). Since we update insertedMonitors
           * at the end of buildMonitorMap(), it's ok to skip the
           * add here.
           */
          if (insertedMonitors != null) {
            insertedMonitors.add(monitor);
          }
        }
        monitor = getNextMonitorEntry();
      }
    }
  }
Ejemplo n.º 3
0
 /**
  * Import an XQuery library module from the given document. The namespace and preferred prefix of
  * the module are extracted from the module itself. The MIME type of the document is set to
  * "application/xquery" as a side-effect.
  *
  * @param module the non-XML document that holds the library module's source
  * @return this service, to chain calls
  * @throws DatabaseException if the module is an XML document, or the module declaration cannot be
  *     found at the top of the document
  */
 public QueryService importModule(Document module) {
   if (module instanceof XMLDocument)
     throw new DatabaseException("module cannot be an XML document: " + module);
   Matcher matcher = MODULE_DECLARATION_DQUOTE.matcher(module.contentsAsString());
   if (!matcher.find()) {
     matcher = MODULE_DECLARATION_SQUOTE.matcher(module.contentsAsString());
     if (!matcher.find())
       throw new DatabaseException("couldn't find a module declaration at the top of " + module);
   }
   module.metadata().setMimeType("application/xquery");
   String moduleNamespace = matcher.group(1);
   // TODO: should do URILiteral processing here to replace entity and character references and
   // normalize
   // whitespace, but since it seems that eXist doesn't do it either (bug?) there's no reason to
   // rush.
   Document prevModule = moduleMap.get(moduleNamespace);
   if (prevModule != null && !prevModule.equals(module))
     throw new DatabaseException(
         "module "
             + moduleNamespace
             + " already bound to "
             + prevModule
             + ", can't rebind to "
             + module);
   moduleMap.put(moduleNamespace, module);
   return this;
 }
Ejemplo n.º 4
0
 PCNode insertFullName(String full_name, boolean cl, boolean weavable) {
   int dotpos = full_name.indexOf('.');
   String head;
   String rest;
   if (dotpos == -1) {
     head = full_name;
     rest = null;
   } else {
     head = full_name.substring(0, dotpos);
     rest = full_name.substring(dotpos + 1);
   }
   PCNode child;
   if (!inners.containsKey(head)) {
     child = new PCNode(head, this, root);
     inners.put(head, child);
   } else {
     child = (PCNode) inners.get(head);
   }
   if (rest != null) {
     return child.insertFullName(rest, cl, weavable);
   } else {
     child.is_class |= cl;
     child.is_weavable |= weavable;
     return child;
   }
 }
Ejemplo n.º 5
0
  /** @return matching bloc B bloc -> A bloc */
  public static Map<Integer, Integer> diff(FileDesc a, FileDesc b) {
    Map<Integer, List<IndexedHash>> blocA = new HashMap<Integer, List<IndexedHash>>();
    int i = 0;
    for (Bloc bloc : a.blocs) {
      List<IndexedHash> l = blocA.get(bloc.roll);
      if (l == null) {
        l = new ArrayList<IndexedHash>();
        blocA.put(bloc.roll, l);
      }
      l.add(new IndexedHash(i++, bloc.hash));
    }

    Map<Integer, Integer> map = new HashMap<Integer, Integer>();
    loop:
    for (i = 0; i < b.blocs.length; i++) {
      Bloc blocB = b.blocs[i];
      List<IndexedHash> list = blocA.get(blocB.roll);
      if (list != null) {
        for (IndexedHash bloc : list) {
          if (blocB.hash.equals(bloc.h)) {
            map.put(i, bloc.i);
            continue loop;
          }
        }
      }
    }
    return map;
  }
Ejemplo n.º 6
0
 protected RichText.Part text(PState s, String text, Map<? extends Attribute, ?> attrs)
     throws IOException {
   RichText.Part ret = null;
   int p = 0;
   while (true) {
     Matcher m = urlpat.matcher(text);
     if (!m.find(p)) break;
     URL url;
     try {
       String su = text.substring(m.start(), m.end());
       if (su.indexOf(':') < 0) su = "http://" + su;
       url = new URL(su);
     } catch (java.net.MalformedURLException e) {
       p = m.end();
       continue;
     }
     RichText.Part lead = new RichText.TextPart(text.substring(0, m.start()), attrs);
     if (ret == null) ret = lead;
     else ret.append(lead);
     Map<Attribute, Object> na = new HashMap<Attribute, Object>(attrs);
     na.putAll(urlstyle);
     na.put(ChatAttribute.HYPERLINK, new FuckMeGentlyWithAChainsaw(url));
     ret.append(new RichText.TextPart(text.substring(m.start(), m.end()), na));
     p = m.end();
   }
   if (ret == null) ret = new RichText.TextPart(text, attrs);
   else ret.append(new RichText.TextPart(text.substring(p), attrs));
   return (ret);
 }
Ejemplo n.º 7
0
  /** Parse the given string, return resulting data if appropriate. */
  ParseResult internalParse(
      String s, Map<String, Integer> targetUnionDecisions, boolean mustConsumeStr) {
    //
    // If there's no target decision, then go ahead and try all branches.
    //
    if (targetUnionDecisions == null || targetUnionDecisions.get(name) == null) {
      for (InferredType subelt : unionTypes) {
        ParseResult pr = subelt.internalParse(s, targetUnionDecisions, false);
        if (pr != null
            && (!mustConsumeStr
                || (mustConsumeStr && pr.getRemainingString().trim().length() == 0))) {
          return new ParseResult(pr.getData(), pr.hasData(), pr.getRemainingString());
        }
      }
      return null;
    }

    //
    // If there is a target decision, then carry it out.
    //
    InferredType subelt = unionTypes.get(targetUnionDecisions.get(name));
    ParseResult pr = subelt.internalParse(s, targetUnionDecisions, false);
    if (pr != null
        && (!mustConsumeStr || (mustConsumeStr && pr.getRemainingString().trim().length() == 0))) {
      return new ParseResult(pr.getData(), pr.hasData(), pr.getRemainingString());
    }
    return null;
  }
Ejemplo n.º 8
0
  public List getUserListAT() {

    List<Map> list = new ArrayList<Map>();

    String[][] data = {
      {"3537255778", "Alex Chen"},
      {"2110989338", "Brian Wang"},
      {"3537640807", "David Hsieh"},
      {"5764816553", "James Yu"},
      {"3756404948", "K.C."},
      {"2110994764", "Neil Weinstock"},
      {"6797798390", "Owen Chen"},
      {"3831206627", "Randy Chen"},
      {"6312460903", "Tony Shen"},
      {"2110993498", "Yee Liaw"}
    };

    for (int i = 0; i < data.length; i++) {

      Map map = new HashMap();

      String userRef = data[i][0];
      String userName = data[i][1];

      map.put("userObjectId", userRef);
      map.put("userName", userName);

      list.add(map);
    }

    return list;
  }
Ejemplo n.º 9
0
  public void processMethodMapping(
      String className,
      int firstLineNumber,
      int lastLineNumber,
      String methodReturnType,
      String methodName,
      String methodArguments,
      String newMethodName) {
    // Original class name -> obfuscated method names.
    Map methodMap = (Map) classMethodMap.get(className);
    if (methodMap == null) {
      methodMap = new HashMap();
      classMethodMap.put(className, methodMap);
    }

    // Obfuscated method name -> methods.
    Set methodSet = (Set) methodMap.get(newMethodName);
    if (methodSet == null) {
      methodSet = new LinkedHashSet();
      methodMap.put(newMethodName, methodSet);
    }

    // Add the method information.
    methodSet.add(
        new MethodInfo(
            firstLineNumber, lastLineNumber, methodReturnType, methodArguments, methodName));
  }
Ejemplo n.º 10
0
  /**
   * Reads the file that specifies method calls that should be replaced by other method calls. The
   * file is of the form:
   *
   * <p>[regex] [orig-method-def] [new-method-name]
   *
   * <p>where the orig_method-def is of the form:
   *
   * <p>fully-qualified-method-name (args)
   *
   * <p>Blank lines and // comments are ignored. The orig-method-def is replaced by a call to
   * new-method-name with the same arguments in any classfile that matches the regular expressions.
   * All method names and argument types should be fully qualified.
   */
  public void read_map_file(File map_file) throws IOException {

    LineNumberReader lr = new LineNumberReader(new FileReader(map_file));
    MapFileError mfe = new MapFileError(lr, map_file);
    Pattern current_regex = null;
    Map<MethodDef, MethodInfo> map = new LinkedHashMap<MethodDef, MethodInfo>();
    for (String line = lr.readLine(); line != null; line = lr.readLine()) {
      line = line.replaceFirst("//.*$", "");
      if (line.trim().length() == 0) continue;
      if (line.startsWith(" ")) {
        if (current_regex == null)
          throw new IOException("No current class regex on line " + lr.getLineNumber());
        StrTok st = new StrTok(line, mfe);
        st.stok.wordChars('.', '.');
        MethodDef md = parse_method(st);
        String new_method = st.need_word();
        map.put(md, new MethodInfo(new_method));
      } else {
        if (current_regex != null) {
          MethodMapInfo mmi = new MethodMapInfo(current_regex, map);
          map_list.add(mmi);
          map = new LinkedHashMap<MethodDef, MethodInfo>();
        }
        current_regex = Pattern.compile(line);
      }
    }
    if (current_regex != null) {
      MethodMapInfo mmi = new MethodMapInfo(current_regex, map);
      map_list.add(mmi);
    }

    dump_map_list();
  }
Ejemplo n.º 11
0
  /**
   * method to make adjustments for known counter problems. This method depends on the availability
   * of certain counters, which is generally guaranteed by the synchWithTarget() method.
   */
  protected void kludge(Map<String, Monitor> map) {
    if (Boolean.getBoolean("sun.jvmstat.perfdata.disableKludge")) {
      // bypass all kludges
      return;
    }

    String name = "java.vm.version";
    StringMonitor jvm_version = (StringMonitor) map.get(name);
    if (jvm_version == null) {
      jvm_version = (StringMonitor) findByAlias(name);
    }

    name = "java.vm.name";
    StringMonitor jvm_name = (StringMonitor) map.get(name);
    if (jvm_name == null) {
      jvm_name = (StringMonitor) findByAlias(name);
    }

    name = "hotspot.vm.args";
    StringMonitor args = (StringMonitor) map.get(name);
    if (args == null) {
      args = (StringMonitor) findByAlias(name);
    }

    assert ((jvm_name != null) && (jvm_version != null) && (args != null));

    if (jvm_name.stringValue().indexOf("HotSpot") >= 0) {
      if (jvm_version.stringValue().startsWith("1.4.2")) {
        kludgeMantis(map, args);
      }
    }
  }
Ejemplo n.º 12
0
  /**
   * This is called when JPM runs in the background to start jobs
   *
   * @throws Exception
   */
  public void daemon() throws Exception {
    Runtime.getRuntime()
        .addShutdownHook(
            new Thread("Daemon shutdown") {
              public void run() {

                for (Service service : startedByDaemon) {
                  try {
                    reporter.error("Stopping " + service);
                    service.stop();
                    reporter.error("Stopped " + service);
                  } catch (Exception e) {
                    // Ignore
                  }
                }
              }
            });
    List<ServiceData> services = getServices();
    Map<String, ServiceData> map = new HashMap<String, ServiceData>();
    for (ServiceData d : services) {
      map.put(d.name, d);
    }
    List<ServiceData> start = new ArrayList<ServiceData>();
    Set<ServiceData> set = new HashSet<ServiceData>();
    for (ServiceData sd : services) {
      checkStartup(map, start, sd, set);
    }

    if (start.isEmpty()) reporter.warning("No services to start");

    for (ServiceData sd : start) {
      try {
        Service service = getService(sd.name);
        reporter.trace("Starting " + service);
        String result = service.start();
        if (result != null) reporter.error("Started error " + result);
        else startedByDaemon.add(service);
        reporter.trace("Started " + service);
      } catch (Exception e) {
        reporter.error("Cannot start daemon %s, due to %s", sd.name, e);
      }
    }

    while (true) {
      for (Service sd : startedByDaemon) {
        try {
          if (!sd.isRunning()) {
            reporter.error("Starting due to failure " + sd);
            String result = sd.start();
            if (result != null) reporter.error("Started error " + result);
          }
        } catch (Exception e) {
          reporter.error("Cannot start daemon %s, due to %s", sd, e);
        }
      }
      Thread.sleep(10000);
    }
  }
Ejemplo n.º 13
0
 public static void testConfigurableForNonPrimitives() {
   Map<String, String> p = new HashMap<String, String>();
   C config = Configurable.createConfigurable(C.class, p);
   assertNull(config.port());
   p.put("port", "10");
   config = Configurable.createConfigurable(C.class, p);
   assertEquals(Integer.valueOf(10), config.port()); // property port is
   // not set
 }
Ejemplo n.º 14
0
 public Map<String, String> getFormatSpecifierDescriptions() {
   Map<String, String> m = new LinkedHashMap<String, String>();
   Iterator<String> keys = scoreBoardValues.keySet().iterator();
   while (keys.hasNext()) {
     String k = keys.next();
     m.put(k, scoreBoardValues.get(k).getDescription());
   }
   return m;
 }
Ejemplo n.º 15
0
  /**
   * Finds the original field name(s), appending the first one to the out line, and any additional
   * alternatives to the extra lines.
   */
  private void originalFieldName(
      String className,
      String obfuscatedFieldName,
      String type,
      StringBuffer outLine,
      List extraOutLines) {
    int extraIndent = -1;

    // Class name -> obfuscated field names.
    Map fieldMap = (Map) classFieldMap.get(className);
    if (fieldMap != null) {
      // Obfuscated field names -> fields.
      Set fieldSet = (Set) fieldMap.get(obfuscatedFieldName);
      if (fieldSet != null) {
        // Find all matching fields.
        Iterator fieldInfoIterator = fieldSet.iterator();
        while (fieldInfoIterator.hasNext()) {
          FieldInfo fieldInfo = (FieldInfo) fieldInfoIterator.next();
          if (fieldInfo.matches(type)) {
            // Is this the first matching field?
            if (extraIndent < 0) {
              extraIndent = outLine.length();

              // Append the first original name.
              if (verbose) {
                outLine.append(fieldInfo.type).append(' ');
              }
              outLine.append(fieldInfo.originalName);
            } else {
              // Create an additional line with the proper
              // indentation.
              StringBuffer extraBuffer = new StringBuffer();
              for (int counter = 0; counter < extraIndent; counter++) {
                extraBuffer.append(' ');
              }

              // Append the alternative name.
              if (verbose) {
                extraBuffer.append(fieldInfo.type).append(' ');
              }
              extraBuffer.append(fieldInfo.originalName);

              // Store the additional line.
              extraOutLines.add(extraBuffer);
            }
          }
        }
      }
    }

    // Just append the obfuscated name if we haven't found any matching
    // fields.
    if (extraIndent < 0) {
      outLine.append(obfuscatedFieldName);
    }
  }
Ejemplo n.º 16
0
  private void putMap(String name, Map m) {
    _put(OBJECT, name);
    final int sizePos = _buf.position();
    _buf.putInt(0);

    for (Object key : m.keySet()) _putObjectField(key.toString(), m.get(key));

    _buf.put(EOO);
    _buf.putInt(sizePos, _buf.position() - sizePos);
  }
Ejemplo n.º 17
0
 static boolean isComposite(String name, Map<String, String[]> params) {
   for (String pName : params.keySet()) {
     if (pName.startsWith(name + ".")
         && params.get(pName) != null
         && params.get(pName).length > 0) {
       return true;
     }
   }
   return false;
 }
Ejemplo n.º 18
0
 @Override
 public Node execute(ExecutionContext ec, Template tmpl) throws IOException { // {{{
   Map<String, StartNamedBlock> blocks = tmpl.getBlocks();
   Node n = blocks.get(this.blockName);
   if (blocks.containsKey(this.blockName)) {
     return blocks.get(this.blockName).getExecuteNode();
   } else {
     return this.executeNode;
   }
   // return this.getNextNode();
 } // }}}
Ejemplo n.º 19
0
  public List getUserList() {
    List<Map> list = new ArrayList<Map>();

    try {

      /*
      String apiUrl=rallyApiHost+"/user?query="+
      	"((TeamMemberships%20%3D%20https%3A%2F%2Frally1.rallydev.com%2Fslm%2Fwebservice%2F1.34%2Fproject%2F6169133135)%20or%20"+
      	"(TeamMemberships%20%3D%20https%3A%2F%2Frally1.rallydev.com%2Fslm%2Fwebservice%2F1.34%2Fproject%2F6083311244))"+
      	"&fetch=true&order=Name&start=1&pagesize=100";
      */

      String apiUrl =
          rallyApiHost
              + "/user?query=(Disabled%20=%20false)"
              + "&fetch=true&order=Name&start=1&pagesize=100";

      log.info("apiUrl=" + apiUrl);

      String responseXML = getRallyXML(apiUrl);

      org.jdom.input.SAXBuilder bSAX = new org.jdom.input.SAXBuilder();
      org.jdom.Document doc = bSAX.build(new StringReader(responseXML));
      Element root = doc.getRootElement();

      XPath xpath = XPath.newInstance("//Object");
      List xlist = xpath.selectNodes(root);

      Iterator iter = xlist.iterator();
      while (iter.hasNext()) {

        Map map = new HashMap();

        Element item = (Element) iter.next();

        String userRef = item.getAttribute("ref").getValue();
        String userName = item.getAttribute("refObjectName").getValue();
        String userObjectId = item.getChildText("ObjectID");

        map.put("userRef", userRef);
        map.put("userObjectId", userObjectId);
        map.put("userName", userName);

        list.add(map);
      }

    } catch (Exception ex) {
      log.error("", ex);
    }

    return list;
  }
Ejemplo n.º 20
0
  public static void main(String[] args) {
    long start = System.currentTimeMillis();
    Scanner input = new Scanner(System.in);
    int numberOfTestCases = input.nextInt();
    ArrayList<Integer> order = new ArrayList<Integer>(numberOfTestCases);
    int previousKey = -1;
    int previousValue = 0;
    int cycleNumber = 0;

    Map<Integer, Integer> testCases = new TreeMap<Integer, Integer>();

    for (int i = 0; i < numberOfTestCases; i++) {
      int numberOfCycles = input.nextInt();
      testCases.put(numberOfCycles, 1);
      order.add(numberOfCycles);
    }

    for (Map.Entry<Integer, Integer> entry : testCases.entrySet()) {
      int numberOfCycles;
      int initialHeight;

      if (previousKey == -1) {
        numberOfCycles = entry.getKey();
        initialHeight = entry.getValue();
      } else {
        numberOfCycles = entry.getKey() - previousKey;
        initialHeight = previousValue;
      }

      for (int i = 0; i < numberOfCycles; i++) {
        if (cycleNumber % 2 == 0) {
          initialHeight *= 2;
        } else {
          initialHeight += 1;
        }
        cycleNumber++;
      }

      entry.setValue(initialHeight);
      previousKey = entry.getKey();
      previousValue = initialHeight;
    }

    for (Integer element : order) {
      System.out.println(testCases.get(element));
    }

    long elapsed = System.currentTimeMillis() - start;
    System.out.println("time: " + elapsed);
  }
Ejemplo n.º 21
0
  public void run() {
    Map read;
    boolean shouldRead = go_read;
    String command = null;
    long last = 0;

    try {
      /* swallow the banner if requested to do so */
      if (swallow) {
        readResponse();
      }

      while (shouldRead) {
        synchronized (listeners) {
          if (commands.size() > 0) {
            command = (String) commands.removeFirst();
          }
        }

        if (command != null) {
          _sendString(command);
          command = null;
          lastRead = System.currentTimeMillis();
        }

        long now = System.currentTimeMillis();
        if (this.window != null && !this.window.isShowing() && (now - last) < 1500) {
          /* check if our window is not showing... if not, then we're going to switch to a very reduced
          read schedule. */
        } else {
          read = readResponse();
          if (read == null || "failure".equals(read.get("result") + "")) {
            break;
          }

          processRead(read);
          last = System.currentTimeMillis();
        }

        Thread.sleep(100);

        synchronized (listeners) {
          shouldRead = go_read;
        }
      }
    } catch (Exception javaSucksBecauseItMakesMeCatchEverythingFuckingThing) {
      javaSucksBecauseItMakesMeCatchEverythingFuckingThing.printStackTrace();
    }
  }
Ejemplo n.º 22
0
 public Set /*<PCNode>*/ matchSpecific(Pattern simple_name_pattern) {
   Set matches = new HashSet();
   Iterator ii = inners.keySet().iterator();
   while (ii.hasNext()) {
     String inner = (String) ii.next();
     // System.out.print("Matching "+inner+" against "+simple_name_pattern.pattern()+": ");
     if (simple_name_pattern.matcher(inner).matches()) {
       // System.out.println("true");
       matches.add(inners.get(inner));
     } else {
       // System.out.println("false");
     }
   }
   return matches;
 }
 private List<String> computeOverallSurvivalStatus(Map<String, SurvivalData> survivalData) {
   List<String> osStatus = initializeList(canonicalPatientList.size());
   for (String patientId : survivalData.keySet()) {
     int osStatusIndex = canonicalPatientList.indexOf(patientId);
     SurvivalData sd = survivalData.get(patientId);
     if (VitalStatusAlive.has(sd.vitalStatus)) {
       osStatus.set(osStatusIndex, VitalStatusAlive.LIVING.toString());
     } else if (VitalStatusDead.has(sd.vitalStatus)) {
       osStatus.set(osStatusIndex, VitalStatusDead.DECEASED.toString());
     } else {
       osStatus.set(osStatusIndex, ClinicalAttribute.NA);
     }
   }
   return osStatus;
 }
  private Map<String, DiseaseFreeData> getDiseaseFreeDataForMatrix(DataMatrix dataMatrix) {
    Map<String, DiseaseFreeData> diseaseFreeDataMap = new HashMap<String, DiseaseFreeData>();

    List<String> patientIds = getPatientIds(dataMatrix);
    for (int lc = 0; lc < patientIds.size(); lc++) {
      String patientId = patientIds.get(lc);
      DiseaseFreeData df = getDiseaseFreeDataForPatient(lc, dataMatrix);
      if (diseaseFreeDataMap.containsKey(patientId)) {
        df = mergeDiseaseFreeData(diseaseFreeDataMap.get(patientId), df);
      }
      diseaseFreeDataMap.put(patientId, df);
    }

    return diseaseFreeDataMap;
  }
Ejemplo n.º 25
0
  /**
   * The convert method translates a String input to a specified outbound level of the same coding
   * scheme. For example, the input string value may be a tag-encoding URI and the outbound level
   * specified by string outboundlevel may be BINARY, in which case the return value is a binary
   * representation expressed as a string.
   *
   * @param input the identifier to be converted.
   * @param inputParameters additional parameters which need to be provided because they cannot
   *     always be determined from the input value alone. Examples include the taglength,
   *     companyprefixlength and filter values.
   * @param outputLevel the outbound level required for the ouput. Permitted values include BINARY,
   *     TAG_ENCODING, PURE_IDENTITY, LEGACY and ONS_HOSTNAME.
   * @return the identifier converted to the output level.
   */
  public String convert(
      String input, Map<String, String> inputParameters, LevelTypeList outputLevel) {

    TagLengthList tagLength = null;
    if (inputParameters.containsKey("taglength")) {
      // in principle, the user should provide a
      // TagLengthList object in the parameter list.
      String s = inputParameters.get("taglength");
      tagLength = TagLengthList.valueOf(s);
    }

    PrefixMatch match = findPrefixMatch(input, tagLength);

    return convertLevel(match.getScheme(), match.getLevel(), input, inputParameters, outputLevel);
  }
  private Map<String, SurvivalData> getSurvivalDataForMatrix(DataMatrix dataMatrix) {
    Map<String, SurvivalData> survivalDataMap = new HashMap<String, SurvivalData>();

    List<String> patientIds = getPatientIds(dataMatrix);
    for (int lc = 0; lc < patientIds.size(); lc++) {
      String patientId = patientIds.get(lc);
      SurvivalData sd = getSurvivalDataForPatient(lc, dataMatrix);
      if (survivalDataMap.containsKey(patientId)) {
        sd = mergeSurvivalData(survivalDataMap.get(patientId), sd);
      }
      survivalDataMap.put(patientId, sd);
    }

    return survivalDataMap;
  }
Ejemplo n.º 27
0
  /** Method to dump debugging information */
  private void dumpAll(Map map, int lvmid) {
    if (DEBUG) {
      Set keys = map.keySet();

      System.err.println("Dump for " + lvmid);
      int j = 0;
      for (Iterator i = keys.iterator(); i.hasNext(); j++) {
        Monitor monitor = (Monitor) map.get(i.next());
        System.err.println(j + "\t" + monitor.getName() + "=" + monitor.getValue());
      }
      System.err.println("nextEntry = " + nextEntry + " pollForEntry = " + pollForEntry);
      System.err.println("Buffer info:");
      System.err.println("buffer = " + buffer);
    }
  }
Ejemplo n.º 28
0
 /**
  * returns the multiple alignment as a string in a fashion identical to that in a file of
  * ALN/CLUSTALW format (except from the fact that info about residues' match is missing. Aka, the
  * 3rd line of a file of ALN/CLUSTALW ('*', '.', ':' chars) is missing).
  *
  * <p>(Note: CLUSTALW doesn't necessarily have the match characters... -Tim)
  */
 public String toString() {
   StringBuilder sb = new StringBuilder();
   int tl = maxTagLength();
   int i = 0, last = gappedAlignments.keySet().size() - 1;
   for (String tag : gappedAlignments.keySet()) {
     sb.append(StringUtils.padString(tag, tl));
     sb.append("  ");
     sb.append(gappedAlignments.get(tag).gappedString());
     if (i < last) {
       sb.append("\n");
     }
     i += 1;
   }
   return sb.toString();
 }
  private int parse() throws IOException {
    String line;
    BufferedReader reader = new BufferedReader(new FileReader(inputFile));
    int count = 0;

    line = reader.readLine(); // Quality Scores;
    String[] array = line.split("\t");
    qualityScores = new Integer[array.length - offset];
    for (int i = offset; i < array.length; i++) {
      qualityScores[i - offset] = Integer.parseInt(array[i]);
    }

    line = reader.readLine(); // Experiment Names
    array = line.split("\t");
    experiments = new String[array.length - offset];
    for (int i = offset; i < array.length; i++) {
      experiments[i - offset] = array[i];
      exptIndices.put(array[i], i - offset);
    }

    // Reads the rest of the table.
    while ((line = reader.readLine()) != null) {
      array = line.split("\t");
      String id = array[0]; // first column is the ID
      if (array.length != experiments.length + offset) {
        System.err.println(
            String.format(
                "Line %s has length %d != %d", id, array.length, experiments.length + offset));
      } else {
        // we're going to skip the second column (an index value), and
        // put the rest of the values in the array.  Any parsing exceptions
        // indicate missing (NULL) values.
        Float[] values = new Float[experiments.length];
        for (int i = 0; i < experiments.length; i++) {
          try {
            values[i] = Float.parseFloat(array[i + offset]);
            count += 1;
          } catch (NumberFormatException nfe) {
            values[i] = null;
          }
        }
        table.put(id, values);
      }
    }

    reader.close();
    return count;
  }
Ejemplo n.º 30
0
  protected Map<String, String> getAttributes() {
    if (attributes != null) {
      return attributes;
    }

    attributes = new HashMap<String, String>();

    matcher = ADDITIONAL_ATTRIBUTES_PATTERN.matcher(firstLine);
    if (matcher.find()) {
      String s;
      Matcher attributeMatcher;

      s = matcher.group(2);
      attributeMatcher = ADDITIONAL_ATTRIBUTE_PATTERN.matcher(s);
      while (attributeMatcher.find()) {
        String key;
        String value;

        key = attributeMatcher.group(1);
        value = attributeMatcher.group(2);
        attributes.put(key.toLowerCase(Locale.ENGLISH), value);
      }
    }
    return attributes;
  }