@SuppressWarnings({"ConstantConditions"})
  public Element getState() {
    if (myBundledDisabledDictionariesPaths.isEmpty()
        && myDictionaryFoldersPaths.isEmpty()
        && myDisabledDictionariesPaths.isEmpty()) {
      return null;
    }

    final Element element = new Element(SPELLCHECKER_MANAGER_SETTINGS_TAG);
    // bundled
    element.setAttribute(
        BUNDLED_DICTIONARIES_ATTR_NAME, String.valueOf(myBundledDisabledDictionariesPaths.size()));
    Iterator<String> iterator = myBundledDisabledDictionariesPaths.iterator();
    int i = 0;
    while (iterator.hasNext()) {
      element.setAttribute(BUNDLED_DICTIONARY_ATTR_NAME + i, iterator.next());
      i++;
    }
    // user
    element.setAttribute(FOLDERS_ATTR_NAME, String.valueOf(myDictionaryFoldersPaths.size()));
    for (int j = 0; j < myDictionaryFoldersPaths.size(); j++) {
      element.setAttribute(FOLDER_ATTR_NAME + j, myDictionaryFoldersPaths.get(j));
    }
    element.setAttribute(
        DICTIONARIES_ATTR_NAME, String.valueOf(myDisabledDictionariesPaths.size()));
    iterator = myDisabledDictionariesPaths.iterator();
    i = 0;
    while (iterator.hasNext()) {
      element.setAttribute(DICTIONARY_ATTR_NAME + i, iterator.next());
      i++;
    }

    return element;
  }
Esempio n. 2
1
  /** @param config */
  public DecorateHandler(TagConfig config) {
    super(config);
    this.template = this.getRequiredAttribute("template");
    this.handlers = new HashMap();

    Iterator itr = this.findNextByType(DefineHandler.class);
    DefineHandler d = null;
    while (itr.hasNext()) {
      d = (DefineHandler) itr.next();
      this.handlers.put(d.getName(), d);
      if (log.isLoggable(Level.FINE)) {
        log.fine(tag + " found Define[" + d.getName() + "]");
      }
    }
    List paramC = new ArrayList();
    itr = this.findNextByType(ParamHandler.class);
    while (itr.hasNext()) {
      paramC.add(itr.next());
    }
    if (paramC.size() > 0) {
      this.params = new ParamHandler[paramC.size()];
      for (int i = 0; i < this.params.length; i++) {
        this.params[i] = (ParamHandler) paramC.get(i);
      }
    } else {
      this.params = null;
    }
  }
Esempio n. 3
1
  /** Compile a file. If you want a dump then give -out somefile. */
  public static int compilerPhases(List<String> args, Option<String> out, String phase)
      throws UserError, InterruptedException, IOException, RepositoryError {
    int return_code = 0;
    if (args.size() == 0) {
      throw new UserError("The " + phase + " command must be given a file.");
    }
    String s = args.get(0);
    List<String> rest = args.subList(1, args.size());

    if (s.startsWith("-")) {
      if (s.equals("-debug")) {
        rest = Debug.parseOptions(rest);
      } else if (s.equals("-out") && !rest.isEmpty()) {
        out = Option.<String>some(rest.get(0));
        rest = rest.subList(1, rest.size());
      } else if (s.equals("-compiler-lib")) {
        WellKnownNames.useCompilerLibraries();
        Types.useCompilerLibraries();
      } else if (s.equals("-typecheck-java")) {
        setScala(false);
      } else if (s.equals("-coercion")) {
        setTestCoercion(true);
      } else invalidFlag(s, phase);
      return_code = compilerPhases(rest, out, phase);
    } else {
      return_code = compileWithErrorHandling(s, out, false);
    }
    return return_code;
  }
Esempio n. 4
1
 // Dumb brute force with memoization
 private Map.Entry<List<Integer>, List<Integer>> bestSplit(
     List<Integer> left,
     List<Integer> right,
     Map<String, Map.Entry<List<Integer>, List<Integer>>> mem) {
   if (mem.containsKey(getKey(left, right))) {
     return mem.get(getKey(left, right));
   }
   if (Math.abs(left.size() - right.size()) <= 1) {
     AbstractMap.SimpleEntry<List<Integer>, List<Integer>> entry =
         new AbstractMap.SimpleEntry<>(left, right);
     mem.put(getKey(left, right), entry);
     return entry;
   }
   int minDifference = Integer.MAX_VALUE;
   Map.Entry<List<Integer>, List<Integer>> minEntry = null;
   for (int i = 0; i < right.size(); i++) {
     ArrayList<Integer> newLeft = new ArrayList<>(left);
     newLeft.add(right.get(i));
     ArrayList<Integer> newRight = new ArrayList<>(right);
     newRight.remove(i);
     Map.Entry<List<Integer>, List<Integer>> entry = bestSplit(newLeft, newRight, mem);
     int difference = getDifference(entry);
     if (difference < minDifference) {
       minDifference = difference;
       minEntry = entry;
     }
   }
   return minEntry;
 }
  /**
   * A childless stran is a "problem" in general because they break the evenness of the tree There
   * are three types of such strands, extra nodes to the left, extra to the right, or extra in
   * between parents. This method places those strands in spot.
   *
   * @param childlessStrand - the childless node to be laid out.
   * @param parentLeft - the nearest parent on the left (or <value>null</value> if none such exists)
   * @param parentRight - the nearest parent on the right (or <value>null</value> if none such
   *     exists)
   * @param yLoc - the vertical location to lay out the nodes on.
   */
  private void placeChildless(
      List<GXMoreThanNode> childlessStrand,
      GXMoreThanNode parentLeft,
      GXMoreThanNode parentRight,
      int yLoc) {
    int startMark = 0;
    int spacing =
        (int) (childlessStrand.get(0).getNode().getLayoutEntity().getWidthInLayout() + horSpacing);

    // There's only a parent on the right
    if (parentLeft == null && parentRight != null) {
      startMark = parentRight.getX() - (spacing * childlessStrand.size());
    } // there's a parent on the left
    else if (parentLeft != null) {
      startMark = parentLeft.getX() + spacing;

      // there's a parent on the right as well meaning the childless are between two parents
      // we need to make there's enough room to place them
      if (parentRight != null) {
        int endMark = startMark + (spacing * childlessStrand.size());

        // if there isn't enough room to place the childless between the parents
        if (endMark > parentRight.getX()) {
          // shift everything on the right to the right by the missing amount of space.
          shiftTreesRightOfMark(parentRight, endMark - parentRight.getX());
        }
      }
    }

    // now the room has been assured, place strand.
    placeStrand(childlessStrand, startMark, yLoc, spacing);
  }
  public static IdeaPluginDescriptorImpl[] loadDescriptors(@Nullable StartupProgress progress) {
    if (ClassUtilCore.isLoadingOfExternalPluginsDisabled()) {
      return IdeaPluginDescriptorImpl.EMPTY_ARRAY;
    }

    final List<IdeaPluginDescriptorImpl> result = new ArrayList<IdeaPluginDescriptorImpl>();

    int pluginsCount =
        countPlugins(PathManager.getPluginsPath())
            + countPlugins(PathManager.getPreinstalledPluginsPath());
    loadDescriptors(PathManager.getPluginsPath(), result, progress, pluginsCount);
    Application application = ApplicationManager.getApplication();
    boolean fromSources = false;
    if (application == null || !application.isUnitTestMode()) {
      int size = result.size();
      loadDescriptors(PathManager.getPreinstalledPluginsPath(), result, progress, pluginsCount);
      fromSources = size == result.size();
    }

    loadDescriptorsFromProperty(result);

    loadDescriptorsFromClassPath(result, fromSources ? progress : null);

    IdeaPluginDescriptorImpl[] pluginDescriptors =
        result.toArray(new IdeaPluginDescriptorImpl[result.size()]);
    try {
      Arrays.sort(pluginDescriptors, new PluginDescriptorComparator(pluginDescriptors));
    } catch (Exception e) {
      prepareLoadingPluginsErrorMessage(
          IdeBundle.message("error.plugins.were.not.loaded", e.getMessage()));
      getLogger().info(e);
      return findCorePlugin(pluginDescriptors);
    }
    return pluginDescriptors;
  }
Esempio n. 7
1
 /** Return the list of ProgramElementDoc objects as Array. */
 public static ProgramElementDoc[] toProgramElementDocArray(List list) {
   ProgramElementDoc[] pgmarr = new ProgramElementDoc[list.size()];
   for (int i = 0; i < list.size(); i++) {
     pgmarr[i] = (ProgramElementDoc) (list.get(i));
   }
   return pgmarr;
 }
  private List<TypeProjection> substituteTypeArguments(
      List<TypeParameterDescriptor> typeParameters,
      List<TypeProjection> typeArguments,
      int recursionDepth)
      throws SubstitutionException {
    List<TypeProjection> substitutedArguments =
        new ArrayList<TypeProjection>(typeParameters.size());
    for (int i = 0; i < typeParameters.size(); i++) {
      TypeParameterDescriptor typeParameter = typeParameters.get(i);
      TypeProjection typeArgument = typeArguments.get(i);

      TypeProjection substitutedTypeArgument = unsafeSubstitute(typeArgument, recursionDepth + 1);

      switch (conflictType(
          typeParameter.getVariance(), substitutedTypeArgument.getProjectionKind())) {
        case NO_CONFLICT:
          // if the corresponding type parameter is already co/contra-variant, there's not need for
          // an explicit projection
          if (typeParameter.getVariance() != Variance.INVARIANT
              && !substitutedTypeArgument.isStarProjection()) {
            substitutedTypeArgument =
                new TypeProjectionImpl(Variance.INVARIANT, substitutedTypeArgument.getType());
          }
          break;
        case OUT_IN_IN_POSITION:
        case IN_IN_OUT_POSITION:
          substitutedTypeArgument = TypeUtils.makeStarProjection(typeParameter);
          break;
      }

      substitutedArguments.add(substitutedTypeArgument);
    }
    return substitutedArguments;
  }
  /**
   * Packs a Pdu into the ByteBuffer.
   *
   * @throws java.nio.BufferOverflowException if buff is too small
   * @throws java.nio.ReadOnlyBufferException if buff is read only
   * @see java.nio.ByteBuffer
   * @param buff The ByteBuffer at the position to begin writing
   * @since ??
   */
  public void marshal(java.nio.ByteBuffer buff) {
    super.marshal(buff);
    minefieldID.marshal(buff);
    requestingEntityID.marshal(buff);
    buff.putShort((short) minefieldSequenceNumbeer);
    buff.put((byte) requestID);
    buff.put((byte) pduSequenceNumber);
    buff.put((byte) numberOfPdus);
    buff.put((byte) mineLocation.size());
    buff.put((byte) sensorTypes.size());
    buff.put((byte) pad2);
    buff.putInt((int) dataFilter);
    mineType.marshal(buff);

    for (int idx = 0; idx < sensorTypes.size(); idx++) {
      TwoByteChunk aTwoByteChunk = (TwoByteChunk) sensorTypes.get(idx);
      aTwoByteChunk.marshal(buff);
    } // end of list marshalling

    buff.put((byte) pad3);

    for (int idx = 0; idx < mineLocation.size(); idx++) {
      Vector3Float aVector3Float = (Vector3Float) mineLocation.get(idx);
      aVector3Float.marshal(buff);
    } // end of list marshalling
  } // end of marshal method
Esempio n. 10
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();
    }
  }
Esempio n. 11
0
 private void updlayout() {
   synchronized (ui.sess.glob.paginae) {
     List<Pagina> cur = new ArrayList<Pagina>();
     loading = !cons(this.cur, cur);
     Collections.sort(cur, sorter);
     int i = curoff;
     hotmap.clear();
     for (int y = 0; y < gsz.y; y++) {
       for (int x = 0; x < gsz.x; x++) {
         Pagina btn = null;
         if ((this.cur != null) && (x == gsz.x - 1) && (y == gsz.y - 1)) {
           btn = bk;
         } else if ((cur.size() > ((gsz.x * gsz.y) - 1)) && (x == gsz.x - 2) && (y == gsz.y - 1)) {
           btn = next;
         } else if (i < cur.size()) {
           Resource.AButton ad = cur.get(i).act();
           if (ad.hk != 0) hotmap.put(Character.toUpperCase(ad.hk), cur.get(i));
           btn = cur.get(i++);
         }
         layout[x][y] = btn;
       }
     }
     pagseq = ui.sess.glob.pagseq;
   }
 }
Esempio n. 12
0
 public static List<AttrPack> expand(AttrPack attr) {
   char node_type_list[] = new char[4];
   List<Integer> rimo_path = getRightMostPath(attr.getPath());
   // List<Integer> rimo_path = getRightMostPath(debug);
   // List<Tuple> cand = rightMostExpand(debug);
   List<Tuple> cand = rightMostExpand(attr.getPath());
   char[] path_label = new char[rimo_path.size() + 1];
   int[] path_index = new int[rimo_path.size()];
   for (int i = 0; i < rimo_path.size(); i++) {
     path_index[i] = rimo_path.get(i);
     path_label[i] = attr.getPath().get(path_index[i]).getLabel();
   }
   path_label[rimo_path.size()] = 0;
   List<AttrPack> next_iter = new ArrayList();
   if (attr.getPathIndex() == -1) {
     for (Tuple tup : cand) {
       int d_ = tup.getDepth();
       char l_ = tup.getLabel();
       if (l_ == path_label[d_]) {
         ArrayList<Tuple> tmp_path = new ArrayList(attr.getPath());
         tmp_path.add(new Tuple(d_, l_));
         next_iter.add(new AttrPack(tmp_path, path_index[d_]));
       }
       if (l_ > path_label[d_]) {
         ArrayList<Tuple> tmp_path = new ArrayList(attr.getPath());
         tmp_path.add(new Tuple(d_, l_));
         next_iter.add(new AttrPack(tmp_path, -1));
       }
     }
   } else {
     int prefix = attr.getPathIndex() + 1;
     Tuple prf_tup = attr.getPath().get(prefix);
     {
       ArrayList<Tuple> tmp_path = new ArrayList(attr.getPath());
       tmp_path.add(prf_tup);
       next_iter.add(new AttrPack(tmp_path, prefix));
     }
     for (Tuple tup : cand) {
       int d_ = tup.getDepth();
       char l_ = tup.getLabel();
       if (d_ > prf_tup.getDepth()) {
         continue;
       }
       if (d_ == prf_tup.getDepth() && l_ >= prf_tup.getLabel()) {
         continue;
       }
       if (l_ == path_label[d_]) {
         ArrayList<Tuple> tmp_path = new ArrayList(attr.getPath());
         tmp_path.add(new Tuple(d_, l_));
         next_iter.add(new AttrPack(tmp_path, path_index[d_]));
       }
       if (l_ > path_label[d_]) {
         ArrayList<Tuple> tmp_path = new ArrayList(attr.getPath());
         tmp_path.add(new Tuple(d_, l_));
         next_iter.add(new AttrPack(tmp_path, -1));
       }
     }
   }
   return next_iter;
 }
  @Override
  public Set<Person> getSiblingsAll(Person thisPerson) {
    // return full and half siblings of thisPerson
    // exclude thisPerson from the set

    Set<Person> siblings = new HashSet<Person>();
    List<Person> parents = new ArrayList<Person>();

    em.getTransaction().begin();
    Query q =
        em.createQuery(
            "select b.parents from Birth b, IN(b.person) p WHERE p.id = :personId"
                + " or p.id = :parent2Id");
    q.setParameter("personId", thisPerson.getId());

    parents.addAll((Collection<? extends Person>) q.getResultList());

    if (!parents.isEmpty()) {
      if (parents.size() == 2) {
        siblings = getChildrenAll(parents.get(0), parents.get(1));
      } else if (parents.size() == 1) {
        siblings = getChildren(parents.get(0));
      }
    }
    em.getTransaction().commit();
    siblings.remove(thisPerson);
    return siblings;
  }
Esempio n. 14
0
  private void check() {
    if (maillist != null) System.out.println("Checking Nordstrom pages size:" + maillist.size());
    for (int i = 0; i < maillist.size(); i++) {
      NordstromPage page = maillist.get(i);
      try {

        ParserNordstromPage parserNordstromPage = new ParserNordstromPage(page);
        parserNordstromPage.checkprice();

        if (page.price == 0) {
          // 没有取得数据
          continue;
        }
        String key = page.mailaddress + page.url;
        NordstromPage oldpage = pagelist.get(key);
        if (oldpage != null) {
          checkPageChange(oldpage, page);
        }
        pagelist.put(key, page);

      } catch (Exception e) {
        // e.printStackTrace();
        System.out.println("error when get URL:" + page.url);
        SystemMail.sendSystemMail("Error when get Nordstrom page." + page.url + ";" + e.toString());
      }
    }
  }
Esempio n. 15
0
  @Test
  public void testCaseInsensitive() {
    sql2o
        .createQuery(
            "create table testCI(id2 int primary key, value2 varchar(20), sometext varchar(20), valwithgetter varchar(20))")
        .executeUpdate();

    Query query =
        sql2o.createQuery(
            "insert into testCI(id2, value2, sometext, valwithgetter) values(:id, :value, :someText, :valwithgetter)");
    for (int i = 0; i < 20; i++) {
      query
          .addParameter("id", i)
          .addParameter("value", "some text " + i)
          .addParameter("someText", "whatever " + i)
          .addParameter("valwithgetter", "spaz" + i)
          .addToBatch();
    }
    query.executeBatch();

    List<CIEntity> ciEntities =
        sql2o
            .createQuery("select * from testCI")
            .setCaseSensitive(false)
            .executeAndFetch(CIEntity.class);

    assertTrue(ciEntities.size() == 20);

    // test defaultCaseSensitive;
    sql2o.setDefaultCaseSensitive(false);
    List<CIEntity> ciEntities2 =
        sql2o.createQuery("select * from testCI").executeAndFetch(CIEntity.class);
    assertTrue(ciEntities2.size() == 20);
  }
 /** populates a request object (pre-populated with defaults) based on a parser. */
 public static void parseRequest(TermVectorRequest termVectorRequest, XContentParser parser)
     throws IOException {
   XContentParser.Token token;
   String currentFieldName = null;
   List<String> fields = new ArrayList<>();
   while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
     if (token == XContentParser.Token.FIELD_NAME) {
       currentFieldName = parser.currentName();
     } else if (currentFieldName != null) {
       if (currentFieldName.equals("fields")) {
         if (token == XContentParser.Token.START_ARRAY) {
           while (parser.nextToken() != XContentParser.Token.END_ARRAY) {
             fields.add(parser.text());
           }
         } else {
           throw new ElasticsearchParseException(
               "The parameter fields must be given as an array! Use syntax : \"fields\" : [\"field1\", \"field2\",...]");
         }
       } else if (currentFieldName.equals("offsets")) {
         termVectorRequest.offsets(parser.booleanValue());
       } else if (currentFieldName.equals("positions")) {
         termVectorRequest.positions(parser.booleanValue());
       } else if (currentFieldName.equals("payloads")) {
         termVectorRequest.payloads(parser.booleanValue());
       } else if (currentFieldName.equals("term_statistics")
           || currentFieldName.equals("termStatistics")) {
         termVectorRequest.termStatistics(parser.booleanValue());
       } else if (currentFieldName.equals("field_statistics")
           || currentFieldName.equals("fieldStatistics")) {
         termVectorRequest.fieldStatistics(parser.booleanValue());
       } else if ("_index"
           .equals(currentFieldName)) { // the following is important for multi request parsing.
         termVectorRequest.index = parser.text();
       } else if ("_type".equals(currentFieldName)) {
         termVectorRequest.type = parser.text();
       } else if ("_id".equals(currentFieldName)) {
         if (termVectorRequest.doc != null) {
           throw new ElasticsearchParseException(
               "Either \"id\" or \"doc\" can be specified, but not both!");
         }
         termVectorRequest.id = parser.text();
       } else if ("doc".equals(currentFieldName)) {
         if (termVectorRequest.id != null) {
           throw new ElasticsearchParseException(
               "Either \"id\" or \"doc\" can be specified, but not both!");
         }
         termVectorRequest.doc(jsonBuilder().copyCurrentStructure(parser));
       } else if ("_routing".equals(currentFieldName) || "routing".equals(currentFieldName)) {
         termVectorRequest.routing = parser.text();
       } else {
         throw new ElasticsearchParseException(
             "The parameter " + currentFieldName + " is not valid for term vector request!");
       }
     }
   }
   if (fields.size() > 0) {
     String[] fieldsAsArray = new String[fields.size()];
     termVectorRequest.selectedFields(fields.toArray(fieldsAsArray));
   }
 }
    @Override
    public void map(LongWritable key, Text value, Context context)
        throws IOException, InterruptedException {
      String line = ((Text) value).toString();

      List<String> tokens = new ArrayList<String>();
      StringTokenizer itr = new StringTokenizer(line);
      int numWords = 0;
      while (itr.hasMoreTokens() && numWords < 100) {
        String w = itr.nextToken().toLowerCase().replaceAll("(^[^a-z]+|[^a-z]+$)", "");
        if (w.length() == 0) continue;
        if (!tokens.contains(w)) {
          tokens.add(w);
        }
        numWords++;
      }

      for (int i = 0; i < tokens.size(); i++) {
        MAP.clear();
        for (int j = 0; j < tokens.size(); j++) {
          if (i == j) continue;

          MAP.increment(tokens.get(j));
        }
        KEY.set(tokens.get(i));
        context.write(KEY, MAP);
      }
    }
Esempio n. 18
0
  @Override
  public boolean equalsImpl(Object obj) {
    boolean ivarsEqual = true;

    if (!(obj instanceof MinefieldDataPdu)) return false;

    final MinefieldDataPdu rhs = (MinefieldDataPdu) obj;

    if (!(minefieldID.equals(rhs.minefieldID))) ivarsEqual = false;
    if (!(requestingEntityID.equals(rhs.requestingEntityID))) ivarsEqual = false;
    if (!(minefieldSequenceNumbeer == rhs.minefieldSequenceNumbeer)) ivarsEqual = false;
    if (!(requestID == rhs.requestID)) ivarsEqual = false;
    if (!(pduSequenceNumber == rhs.pduSequenceNumber)) ivarsEqual = false;
    if (!(numberOfPdus == rhs.numberOfPdus)) ivarsEqual = false;
    if (!(numberOfMinesInThisPdu == rhs.numberOfMinesInThisPdu)) ivarsEqual = false;
    if (!(numberOfSensorTypes == rhs.numberOfSensorTypes)) ivarsEqual = false;
    if (!(pad2 == rhs.pad2)) ivarsEqual = false;
    if (!(dataFilter == rhs.dataFilter)) ivarsEqual = false;
    if (!(mineType.equals(rhs.mineType))) ivarsEqual = false;

    for (int idx = 0; idx < sensorTypes.size(); idx++) {
      if (!(sensorTypes.get(idx).equals(rhs.sensorTypes.get(idx)))) ivarsEqual = false;
    }

    if (!(pad3 == rhs.pad3)) ivarsEqual = false;

    for (int idx = 0; idx < mineLocation.size(); idx++) {
      if (!(mineLocation.get(idx).equals(rhs.mineLocation.get(idx)))) ivarsEqual = false;
    }

    return ivarsEqual && super.equalsImpl(rhs);
  }
Esempio n. 19
0
  public int getMarshalledSize() {
    int marshalSize = 0;

    marshalSize = super.getMarshalledSize();
    marshalSize = marshalSize + minefieldID.getMarshalledSize(); // minefieldID
    marshalSize = marshalSize + requestingEntityID.getMarshalledSize(); // requestingEntityID
    marshalSize = marshalSize + 2; // minefieldSequenceNumbeer
    marshalSize = marshalSize + 1; // requestID
    marshalSize = marshalSize + 1; // pduSequenceNumber
    marshalSize = marshalSize + 1; // numberOfPdus
    marshalSize = marshalSize + 1; // numberOfMinesInThisPdu
    marshalSize = marshalSize + 1; // numberOfSensorTypes
    marshalSize = marshalSize + 1; // pad2
    marshalSize = marshalSize + 4; // dataFilter
    marshalSize = marshalSize + mineType.getMarshalledSize(); // mineType
    for (int idx = 0; idx < sensorTypes.size(); idx++) {
      TwoByteChunk listElement = sensorTypes.get(idx);
      marshalSize = marshalSize + listElement.getMarshalledSize();
    }
    marshalSize = marshalSize + 1; // pad3
    for (int idx = 0; idx < mineLocation.size(); idx++) {
      Vector3Float listElement = mineLocation.get(idx);
      marshalSize = marshalSize + listElement.getMarshalledSize();
    }

    return marshalSize;
  }
Esempio n. 20
0
 /**
  * 删除用户
  *
  * @param request
  * @param response
  */
 @RequestMapping("/user_del")
 public void delUser(HttpServletRequest request, HttpServletResponse response) {
   Map<String, Object> resMap = new HashMap<String, Object>();
   String ids = request.getParameter("ids");
   logger.debug("ids:" + ids);
   List<Integer> paramList = new ArrayList<Integer>();
   if (StringUtils.isNoneBlank(ids)) {
     String[] s_array = ids.split(",", -1);
     if (s_array != null && s_array.length > 0) {
       for (String item : s_array) {
         paramList.add(new Integer(item));
       }
       Integer[] i_array = new Integer[paramList.size()];
       for (int i = 0; i < paramList.size(); i++) {
         i_array[i] = paramList.get(i);
       }
       userService.delUserById(i_array);
       resMap.put("msg", "ok");
     } else {
       resMap.put("msg", "error");
     }
   }
   try {
     response.setCharacterEncoding("utf-8");
     response.setHeader("Content-type", "text/html;charset=UTF-8");
     PrintWriter out = response.getWriter();
     Gson gson = new Gson();
     logger.debug("json输出:" + gson.toJson(resMap));
     out.println(gson.toJson(resMap));
     out.flush();
     out.close();
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
Esempio n. 21
0
  /**
   * This method receives a normalized list of non-dominated solutions and return the inverted one.
   * This operation is needed for minimization problem
   *
   * @param solutionList The front to invert
   * @return The inverted front
   */
  public static <S extends Solution<?>> List<S> selectNRandomDifferentSolutions(
      int numberOfSolutionsToBeReturned, List<S> solutionList) {
    if (null == solutionList) {
      throw new JMetalException("The solution list is null");
    } else if (solutionList.size() == 0) {
      throw new JMetalException("The solution list is empty");
    } else if (solutionList.size() < numberOfSolutionsToBeReturned) {
      throw new JMetalException(
          "The solution list size ("
              + solutionList.size()
              + ") is less than "
              + "the number of requested solutions ("
              + numberOfSolutionsToBeReturned
              + ")");
    }

    JMetalRandom randomGenerator = JMetalRandom.getInstance();
    List<S> resultList = new ArrayList<>(numberOfSolutionsToBeReturned);

    if (solutionList.size() == 1) {
      resultList.add(solutionList.get(0));
    } else {
      Collection<Integer> positions = new HashSet<>(numberOfSolutionsToBeReturned);
      while (positions.size() < numberOfSolutionsToBeReturned) {
        int nextPosition = randomGenerator.nextInt(0, solutionList.size() - 1);
        if (!positions.contains(nextPosition)) {
          positions.add(nextPosition);
          resultList.add(solutionList.get(nextPosition));
        }
      }
    }

    return resultList;
  }
  /**
   * Returns paths constructed by rewriting pathInfo using rules from the hosted site's mappings.
   * Paths are ordered from most to least specific match.
   *
   * @param site The hosted site.
   * @param pathInfo Path to be rewritten.
   * @param queryString
   * @return The rewritten path. May be either:
   *     <ul>
   *       <li>A path to a file in the Orion workspace, eg. <code>/ProjectA/foo/bar.txt</code>
   *       <li>An absolute URL pointing to another site, eg. <code>http://foo.com/bar.txt</code>
   *     </ul>
   *
   * @return The rewritten paths.
   * @throws URISyntaxException
   */
  private URI[] getMapped(IHostedSite site, IPath pathInfo, String queryString)
      throws URISyntaxException {
    final Map<String, List<String>> map = site.getMappings();
    final IPath originalPath = pathInfo;
    IPath path = originalPath.removeTrailingSeparator();

    List<URI> uris = new ArrayList<URI>();
    String rest = null;
    final int count = path.segmentCount();
    for (int i = 0; i <= count; i++) {
      List<String> base = map.get(path.toString());
      if (base != null) {
        rest = originalPath.removeFirstSegments(count - i).toString();
        for (int j = 0; j < base.size(); j++) {
          URI uri =
              rest.equals("") ? new URI(base.get(j)) : URIUtil.append(new URI(base.get(j)), rest);
          uris.add(
              new URI(
                  uri.getScheme(),
                  uri.getUserInfo(),
                  uri.getHost(),
                  uri.getPort(),
                  uri.getPath(),
                  queryString,
                  uri.getFragment()));
        }
      }
      path = path.removeLastSegments(1);
    }
    if (uris.size() == 0)
      // No mapping for /
      return null;
    else return uris.toArray(new URI[uris.size()]);
  }
Esempio n. 23
0
  /* hack TODO do not know how to get int status back from Windows
   * Stick in code that handles particular commands that we can figure out
   * the status.
   */
  private int determineStatus(List<String> args) {
    if (args == null) throw new NullPointerException();

    if (args.size() < 2) return 0;

    String instanceName = args.get(args.size() - 1);

    if (isCommand(args, "_delete-instance-filesystem")) {
      try {
        String dir = Paths.getInstanceDirPath(node, instanceName);
        WindowsRemoteFile instanceDir = new WindowsRemoteFile(dcomInfo.getCredentials(), dir);
        return instanceDir.exists() ? 1 : 0;
      } catch (WindowsException ex) {
        return 0;
      }
    } else if (isCommand(args, "_create-instance-filesystem")) {
      try {
        String dir = Paths.getDasPropsPath(node);
        WindowsRemoteFile dasProps = new WindowsRemoteFile(dcomInfo.getCredentials(), dir);

        if (dasProps.exists()) return 0;

        // uh-oh.  Wipe out the instance directory that was created
        dir = Paths.getInstanceDirPath(node, instanceName);
        WindowsRemoteFile instanceDir = new WindowsRemoteFile(dcomInfo.getCredentials(), dir);
        instanceDir.delete();
        return 1;
      } catch (WindowsException ex) {
        return 1;
      }
    }
    return 0;
  }
Esempio n. 24
0
 private Anchor getLastAnchor() {
   if (sections == null || sections.size() == 0) {
     return initialAnchor;
   } else {
     return sections.get(sections.size() - 1).getFinalAnchor();
   }
 }
Esempio n. 25
0
  public static void main(String[] args) throws IOException {
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

    String line;
    StringBuilder sb = new StringBuilder();
    while ((line = in.readLine()) != null) {
      int k = Integer.parseInt(line);
      List<Integer> xd = new ArrayList<Integer>();
      List<Integer> yd = new ArrayList<Integer>();

      for (int y = k + 1; y <= 2 * k; ++y) {
        if (k * y % (y - k) == 0) {
          int x = k * y / (y - k);
          xd.add(x);
          yd.add(y);
        }
      }

      sb.append(xd.size() + "\n");
      for (int i = 0; i < xd.size(); ++i)
        sb.append(String.format("1/%d = 1/%d + 1/%d\n", k, xd.get(i), yd.get(i)));
    }

    System.out.print(sb);

    in.close();
    System.exit(0);
  }
Esempio n. 26
0
  /**
   * Build the encodings against each categorical feature.
   *
   * @return a list of encodings - last value of the list represent the encodings for the response
   *     variable. index - index of the feature value - Map<String, Integer> - map of unique values
   *     of this feature and there encoded values. key - unique value value - encoded value
   */
  private static List<Map<String, Integer>> buildEncodings(
      List<Feature> features,
      Map<String, String> summaryStats,
      List<Integer> newToOldIndicesList,
      int responseIndex) {
    List<Map<String, Integer>> encodings = new ArrayList<Map<String, Integer>>();
    for (int i = 0; i < newToOldIndicesList.size() + 1; i++) {
      encodings.add(new HashMap<String, Integer>());
    }
    for (Feature feature : features) {
      Map<String, Integer> encodingMap = new HashMap<String, Integer>();
      if (feature.getType().equals(FeatureType.CATEGORICAL)) {
        List<String> uniqueVals =
            getUniqueValues(feature.getIndex(), summaryStats.get(feature.getName()));
        Collections.sort(uniqueVals);
        for (int i = 0; i < uniqueVals.size(); i++) {
          encodingMap.put(uniqueVals.get(i), i);
        }
        int newIndex = newToOldIndicesList.indexOf(feature.getIndex());
        if (newIndex != -1) {
          encodings.set(newIndex, encodingMap);
        } else if (feature.getIndex() == responseIndex) {
          // response encoding at the end
          encodings.set(encodings.size() - 1, encodingMap);
        }
      }
    }

    return encodings;
  }
Esempio n. 27
0
  /**
   * Utility method used in the construction of {@link UnitGraph}s, to be called only after the
   * unitToPreds and unitToSuccs maps have been built.
   *
   * <p><code>UnitGraph</code> provides an implementation of <code>buildHeadsAndTails()</code> which
   * defines the graph's set of heads to include the first {@link Unit} in the graph's body,
   * together with any other <tt>Unit</tt> which has no predecessors. It defines the graph's set of
   * tails to include all <tt>Unit</tt>s with no successors. Subclasses of <code>UnitGraph</code>
   * may override this method to change the criteria for classifying a node as a head or tail.
   */
  protected void buildHeadsAndTails() {
    List tailList = new ArrayList();
    List headList = new ArrayList();

    for (Iterator unitIt = unitChain.iterator(); unitIt.hasNext(); ) {
      Unit s = (Unit) unitIt.next();
      List succs = (List) unitToSuccs.get(s);
      if (succs.size() == 0) {
        tailList.add(s);
      }
      List preds = (List) unitToPreds.get(s);
      if (preds.size() == 0) {
        headList.add(s);
      }
    }

    // Add the first Unit, even if it is the target of
    // a branch.
    Unit entryPoint = (Unit) unitChain.getFirst();
    if (!headList.contains(entryPoint)) {
      headList.add(entryPoint);
    }

    tails = Collections.unmodifiableList(tailList);
    heads = Collections.unmodifiableList(headList);
  }
Esempio n. 28
0
  public void marshal(DataOutputStream dos) {
    super.marshal(dos);
    try {
      minefieldID.marshal(dos);
      requestingEntityID.marshal(dos);
      dos.writeShort((short) minefieldSequenceNumbeer);
      dos.writeByte((byte) requestID);
      dos.writeByte((byte) pduSequenceNumber);
      dos.writeByte((byte) numberOfPdus);
      dos.writeByte((byte) mineLocation.size());
      dos.writeByte((byte) sensorTypes.size());
      dos.writeByte((byte) pad2);
      dos.writeInt((int) dataFilter);
      mineType.marshal(dos);

      for (int idx = 0; idx < sensorTypes.size(); idx++) {
        TwoByteChunk aTwoByteChunk = sensorTypes.get(idx);
        aTwoByteChunk.marshal(dos);
      } // end of list marshalling

      dos.writeByte((byte) pad3);

      for (int idx = 0; idx < mineLocation.size(); idx++) {
        Vector3Float aVector3Float = mineLocation.get(idx);
        aVector3Float.marshal(dos);
      } // end of list marshalling

    } // end try
    catch (Exception e) {
      System.out.println(e);
    }
  } // end of marshal method
Esempio n. 29
0
  public void drawOn(Page page) throws Exception {
    if (fill_shape) {
      page.setBrushColor(color[0], color[1], color[2]);
    } else {
      page.setPenColor(color[0], color[1], color[2]);
    }
    page.setPenWidth(width);
    page.setLinePattern(pattern);

    for (int i = 0; i < points.size(); i++) {
      Point point = points.get(i);
      point.x += box_x;
      point.y += box_y;
    }

    if (fill_shape) {
      page.drawPath(points, 'f');
    } else {
      if (close_path) {
        page.drawPath(points, 's');
      } else {
        page.drawPath(points, 'S');
      }
    }

    for (int i = 0; i < points.size(); i++) {
      Point point = points.get(i);
      point.x -= box_x;
      point.y -= box_y;
    }
  }
Esempio n. 30
0
  static <T> List<List<T>> combinations(List<T> list, int n) {

    List<List<T>> result;

    if (list.size() <= n) {

      result = new ArrayList<List<T>>();
      result.add(new ArrayList<T>(list));

    } else if (n <= 0) {

      result = new ArrayList<List<T>>();
      result.add(new ArrayList<T>());

    } else {

      List<T> sublist = list.subList(1, list.size());

      result = combinations(sublist, n);

      for (List<T> alist : combinations(sublist, n - 1)) {
        List<T> thelist = new ArrayList<T>(alist);
        thelist.add(list.get(0));
        result.add(thelist);
      }
    }

    return result;
  }