Example #1
1
  /**
   * ***************************************************************** Find all terms which do not
   * appear in any implication (rule).
   */
  public static ArrayList<String> termsWithoutRules(KB kb) {

    boolean isNaN = true;
    ArrayList<String> result = new ArrayList<String>();
    Iterator<String> it = kb.getTerms().iterator();
    synchronized (kb.getTerms()) {
      while (it.hasNext()) {
        String term = (String) it.next();
        isNaN = true;
        try {
          double dval = Double.parseDouble(term);
          isNaN = Double.isNaN(dval);
        } catch (Exception nex) {
        }
        if (isNaN) {
          ArrayList<Formula> forms = kb.ask("ant", 0, term);
          ArrayList<Formula> forms2 = kb.ask("cons", 0, term);
          if (((forms == null) || forms.isEmpty()) && ((forms2 == null) || forms2.isEmpty()))
            result.add(term);
        }
        if (result.size() > 99) {
          result.add("limited to 100 results");
          break;
        }
      }
    }
    return result;
  }
  /**
   * Returns a list of descriptions corresponding to every item matching the search.
   *
   * @return a list of descriptions
   * @throws SQLException thrown if an SQLException occurs
   * @throws ClassNotFoundException thrown if a ClassNotFoundException occurs
   * @throws IOException thrown if an IOException occurs
   * @throws InterruptedException thrown if an InterruptedException occurs
   */
  public ArrayList<String> getPossibilitiesDescriptions()
      throws SQLException, ClassNotFoundException, IOException, InterruptedException {

    Identification identification = peptideShakerGUI.getIdentification();

    // Some necessary pre-caching
    ArrayList<Type> typeList = types.get(jumpType);
    ArrayList<String> keys = possibilities.get(jumpType),
        proteinKeys = new ArrayList<String>(),
        peptideKeys = new ArrayList<String>();
    for (int i = 0; i < keys.size(); i++) {
      String key = keys.get(i);
      if (typeList.get(i) == Type.PROTEIN) {
        proteinKeys.add(key);
      } else if (typeList.get(i) == Type.PEPTIDE) {
        peptideKeys.add(key);
      }
    }
    if (!proteinKeys.isEmpty()) {
      identification.loadProteinMatches(proteinKeys, null, false);
    }
    if (!peptideKeys.isEmpty()) {
      identification.loadPeptideMatches(peptideKeys, null, false);
    }

    ArrayList<String> descriptions = new ArrayList<String>();
    for (int i = 0; i < keys.size(); i++) {
      String key = keys.get(i);
      Type type = typeList.get(i);
      String description = getItemDescription(key, type);
      descriptions.add(description);
    }
    return descriptions;
  }
Example #3
1
 public boolean checkCyclicDependency() {
   ArrayList<ScheduledWorkflowEntities> temp =
       workflow; // I don't need workFlow so destroying it while checking
   while (!temp.isEmpty()) {
     ArrayList<String> runRow = new ArrayList<String>();
     ArrayList<String> blockRow = new ArrayList<String>();
     ArrayList<ScheduledWorkflowEntities> reqRow = new ArrayList<ScheduledWorkflowEntities>();
     for (ScheduledWorkflowEntities req : temp) {
       if (req.getDependsOn().isEmpty()) {
         runRow.add(req.getRunName());
         blockRow.add(req.getBlockName());
         reqRow.add(req);
       }
     }
     temp.removeAll(reqRow);
     for (String blockName : blockRow) {
       for (ScheduledWorkflowEntities req : temp) {
         if (req.getDependsOn().contains(blockName)) req.getDependsOn().remove(blockName);
       }
     }
     if (runRow.isEmpty()) return true;
     runMap.add(runRow);
   }
   //        for(ArrayList<String> wf: runMap){
   //            for(String runName: wf){
   //                System.out.print(runName + " ->");
   //            }
   //            System.out.println();
   //        }
   return false;
 }
 public void comer(int id) {
   accessLock.lock(); // bloqueia a mesa
   int x = 0, contador = 0;
   boolean teste = false;
   try {
     do {
       for (int i = 0; i < feitos.size(); i++) {
         if (feitos.get(i).getId_cliente() == id) {
           x = i;
           teste = true;
         }
       }
       if (!produtos.isEmpty() && !teste) { // se não tiver itens feitos
         System.out.printf("Cliente[%d] aguardando\n", id);
         comer.await(); // bloqueia alguem comer
       }
       for (int i = 0; i < feitos.size(); i++) {
         if (feitos.get(i).getId_cliente() == id) {
           x = i;
           teste = true;
         }
       }
     } while (!teste && !produtos.isEmpty());
     if (teste) {
       feitos.get(x).setStatus("CONSUMIDO");
       System.out.printf("O Cliente[%d] consumiu o item[%d]\n", id, feitos.get(x).getId_pedido());
       feitos.remove(x);
       cozinhar.signalAll(); // libera a producao de mais itens
     }
   } catch (InterruptedException e) {
     e.printStackTrace();
   } finally {
     accessLock.unlock(); // libera  a mesa
   }
 }
Example #5
1
  @Override
  public void filterTable(String filter) {

    // store list only for first time
    if (fullBackup.isEmpty() || fullBackup == null) {
      fullBackup.addAll(getList());
    }

    // always clear selected items
    selectionModel.clear();
    list.clear();

    if (filter.equalsIgnoreCase("")) {
      list.addAll(fullBackup);
    } else {
      for (ExtSource src : fullBackup) {
        // store ext source if name or type matches
        if ((src.getName().toLowerCase().startsWith(filter.toLowerCase()))
            || renameContent(src.getType()).toLowerCase().startsWith(filter.toLowerCase())) {
          list.add(src);
        }
      }
    }

    if (list.isEmpty() && !filter.isEmpty()) {
      loaderImage.setEmptyResultMessage("No external source matching '" + filter + "' found.");
    } else {
      loaderImage.setEmptyResultMessage("No external sources found in Perun.");
    }

    dataProvider.flush();
    dataProvider.refresh();
    loaderImage.loadingFinished();
  }
Example #6
1
  // Returns the nearest point of the ID
  public Point getNearestPoint(long id) {
    Point MSc = new Point(259, 220);
    ScreenModel[] find = ScreenModels.find(id);
    ArrayList<Integer> distList = new ArrayList<Integer>();
    ArrayList<Point> coordList = new ArrayList<Point>();

    if (find.length > 0) {
      for (int i = 0; i < find.length; i++) {
        distList.add(
            (int)
                Math.sqrt(
                    Math.pow(Math.abs(MSc.x - find[i].base_point.x), 2)
                        + Math.pow(Math.abs(MSc.y - find[i].base_point.y), 2)));
        coordList.add(new Point(find[i].base_point.getLocation()));
      }

      if (!distList.isEmpty() && !coordList.isEmpty()) {
        int nearest = 1000;
        int t = 0;

        for (int i = 0; i < distList.size(); i++) {
          if (distList.get(i) < nearest) {
            nearest = distList.get(i);
            t = i;
          }
        }

        return coordList.get(t);
      }
    }

    return null;
  }
  public void testCacheReadComment() {
    // this test needs Internet connectivity and assumes that there is a top level comment in
    // Elasticsearch already.
    CommentListModel listModel = new CommentListModel();
    Cache cache = Cache.getInstance();
    CommentSearch search = new CommentSearch(listModel, cache);
    CacheIO cacheIO = cache.getCacheIO();

    ArrayList<CommentModel> acm =
        new ArrayList<CommentModel>(); // this is empty and written to disk to clear the cache.

    cache.serializeAndWrite(acm, "history.sav");

    acm = cacheIO.load("history.sav");
    assertTrue(acm.isEmpty());

    Thread thread = search.pullTopLevel((BrowseActivity) unusedInAnotherTestActivity);
    try {
      thread.join();
    } catch (InterruptedException e) {
      Log.w("EsTestPullReplies", "Thread interrupt");
      Log.w("PULL", "Thread interrupt");
    }

    acm = cacheIO.load("history.sav");

    JestResult result = search.returnResult();
    assertTrue("Result is not null", result != null);
    assertTrue("Result is successful", result.isSucceeded());

    assertFalse(
        "cache is still empty",
        acm.isEmpty()); // if this fails on the first execution: re-run this test again.
  }
Example #8
0
  public void remove(int k) {
    try {
      zAxisData.remove(k);
      xAxisData.remove(k);
      yAxisData.remove(k);
    } catch (Exception e) {
      e.printStackTrace();
    }

    Platform.runLater(
        () -> {
          scatterDataGroup.getChildren().clear();
          for (int i = 0; i < zAxisData.size(); i++) {
            final Sphere dataSphere = new Sphere(scatterRadius);
            double translateX = 0.0;
            double translateY = 0.0;
            if (!xAxisData.isEmpty() && xAxisData.size() > i) translateX = xAxisData.get(i);
            if (!yAxisData.isEmpty() && yAxisData.size() > i) translateY = yAxisData.get(i);
            dataSphere.setTranslateX(translateX);
            dataSphere.setTranslateY(translateY);
            dataSphere.setTranslateZ(zAxisData.get(i));
            scatterDataGroup.getChildren().add(dataSphere);
          }
        });
  }
Example #9
0
  /** Compares the locations and prints the results to the specified files. */
  public boolean compareLocationSets(
      Collection refLocations, Collection newLocations, String refFile, String testFile) {
    boolean foundDifferences = false;
    try {
      if (refLocations.size() != newLocations.size()) {
        printErrorMessageForDifferentCollections();
        throw new TVLAException("Different location sets!");
      }

      LocationComparatorByLabel locComparator = new LocationComparatorByLabel();
      Iterator refLocIterator = refLocations.iterator();

      while (refLocIterator.hasNext()) {
        Location refLoc = (Location) refLocIterator.next();
        Location newLoc = (Location) tvla.util.Find.findEqual(newLocations, refLoc, locComparator);
        if (newLoc == null) {
          printErrorMessageForDifferentCollections();
          throw new TVLAException("Different location sets!");
        }
        ArrayList diffRef = new ArrayList();
        ArrayList diffNew = new ArrayList();
        StructureCollectionsDiff differentiator = new StructureCollectionsDiff();
        differentiator.diff(refLoc.structures, newLoc.structures, diffRef, diffNew);
        printDifferences(refLoc.label(), diffRef, diffNew, refFile, testFile);
        if (diffNew.isEmpty() == false || diffRef.isEmpty() == false) foundDifferences = true;
      }
      return foundDifferences;
    } finally {
      cleanup();
    }
  }
Example #10
0
 public void model_admin() {
   if (ajf != null) {
     ajf.dispose();
   }
   if (jf != null) {
     jf.dispose();
   }
   ajf = new AdminRunningFrame(this);
   ajf.startPage();
   if (DBfile.exists()) {
     try {
       cust = returnSavedData("p2.dat");
       if (cust.isEmpty()) {
         ajf.errorMessage("There are no customers in this database.");
       }
     } catch (ClassNotFoundException | IOException e) {
       e.printStackTrace();
     }
   }
   if (logFile.exists()) {
     try {
       adminLogs = returnLog("p2.log");
       if (adminLogs.isEmpty()) {
         ajf.errorMessage("No entries have been found!");
       }
     } catch (ClassNotFoundException | IOException e) {
       e.printStackTrace();
     }
   }
 }
 public void play() {
   owner.addActions(1);
   ArrayList<DomCard> theRevealedCards = owner.revealTopCards(3);
   if (theRevealedCards.isEmpty()) return;
   if (owner instanceof DomHumanPlayer) {
     DomCard c =
         ((DomHumanPlayer) owner)
             .chooseExactlyNCardsFromList(1, theRevealedCards, "Lookout - trash a card")
             .get(0);
     owner.trash(c);
     theRevealedCards.remove(c);
     if (theRevealedCards.isEmpty()) return;
     c =
         ((DomHumanPlayer) owner)
             .chooseExactlyNCardsFromList(1, theRevealedCards, "Lookout - discard a card")
             .get(0);
     owner.discard(c);
     if (!theRevealedCards.isEmpty()) owner.putOnTopOfDeck(theRevealedCards.get(0));
   } else {
     // first trash a card
     Collections.sort(theRevealedCards, SORT_FOR_TRASHING);
     owner.trash(theRevealedCards.remove(0));
     if (theRevealedCards.isEmpty()) return;
     // then discard a card
     Collections.sort(theRevealedCards, SORT_FOR_DISCARDING);
     owner.discard(theRevealedCards.remove(0));
     // and finally, put the last card back on the deck
     if (!theRevealedCards.isEmpty()) {
       owner.putOnTopOfDeck(theRevealedCards.get(0));
     }
   }
 }
Example #12
0
  private void computeContents() {
    ButtonGroup bgroup = new ButtonGroup();
    bgroup.add(nullItem);

    removeAll();
    add(minimize);
    add(zoom);
    add(close);

    if (!persistentItems.isEmpty()) {
      addSeparator();
      for (JRadioButtonMenuItem item : persistentItems) {
        bgroup.add(item);
        add(item);
      }
    }

    if (!transientItems.isEmpty()) {
      addSeparator();
      for (JRadioButtonMenuItem item : transientItems) {
        bgroup.add(item);
        add(item);
      }
    }

    WindowMenuItemManager currentManager = WindowMenuManager.getCurrentManager();
    if (currentManager != null) {
      JRadioButtonMenuItem item = currentManager.getMenuItem(this);
      if (item != null) {
        item.setSelected(true);
      }
    }
  }
  private ArrayList<TaskSet> getNextPotentialTaskSets(
      ArrayList<TaskSet> taskList, TaskSet checkSet, int clusters_size) {
    int dis = Integer.MAX_VALUE;

    HashMap map = new HashMap<Integer, ArrayList>();
    for (TaskSet set : taskList) {
      int distance = calDistance(checkSet, set);
      if (distance < dis) {
        dis = distance;
      }
      if (!map.containsKey(distance)) {
        map.put(distance, new ArrayList<TaskSet>());
      }
      ArrayList<TaskSet> list = (ArrayList) map.get(distance);
      if (!list.contains(set)) {
        list.add(set);
      }
    }
    ArrayList returnList = new ArrayList<TaskSet>();
    for (TaskSet set : (ArrayList<TaskSet>) map.get(dis)) {
      if (set.getTaskList().size() < clusters_size) {
        returnList.add(set);
      }
    }

    if (returnList.isEmpty()) {
      returnList.clear();
      for (TaskSet set : taskList) {
        if (set.getTaskList().isEmpty()) {
          returnList.add(set);
          return returnList;
        }
      }

      // no empty available
      while (returnList.isEmpty()) {
        map.remove(dis);
        ArrayList<Integer> keys = new ArrayList(map.keySet());
        int min = Integer.MAX_VALUE;
        for (int i : keys) {
          if (min > i) {
            min = i;
          }
        }
        dis = min;

        for (TaskSet set : (ArrayList<TaskSet>) map.get(dis)) {
          if (set.getTaskList().size() < clusters_size) {
            returnList.add(set);
          }
        }
      }

      return returnList;

    } else {

      return returnList;
    }
  }
Example #14
0
 private LanguageNode fold(LanguageNode in, EngineToken variety) {
   FunctionCall fc = (FunctionCall) in;
   ArrayList<ExpressionNode> grouped = new ArrayList<ExpressionNode>();
   ArrayList<ExpressionNode> same = new ArrayList<ExpressionNode>();
   ArrayList<ExpressionNode> others = new ArrayList<ExpressionNode>();
   for (ExpressionNode p : fc.getParameters()) {
     if (EngineConstant.FUNCTION.has(p, variety)) {
       if (p.isGrouped()) grouped.add(p);
       else same.add(p);
     } else {
       others.add(p);
     }
   }
   if (same.isEmpty() || !grouped.isEmpty()) return in;
   // if others is empty, this is op(op(a,b),op(c,d)), build op(a,b,c,d)
   // if others is not empty, this is op(a,op(b,c)) or op(op(a,b),c), build op(a,b,c)
   ArrayList<ExpressionNode> allsubs = new ArrayList<ExpressionNode>();
   for (ExpressionNode p : same) {
     FunctionCall pfc = (FunctionCall) p;
     allsubs.addAll(pfc.getParameters());
   }
   allsubs.addAll(others);
   // we're going to group this as well
   FunctionCall ofc = new FunctionCall(fc.getFunctionName(), allsubs);
   ofc.setGrouped();
   return ofc;
 }
Example #15
0
  /**
   * Execute poll on this device: create an array of messages, add them to the request queue, and
   * schedule the queue for processing.
   *
   * @param delay scheduling delay (in milliseconds)
   */
  public void doPoll(long delay) {
    long now = System.currentTimeMillis();
    ArrayList<QEntry> l = new ArrayList<QEntry>();
    synchronized (m_features) {
      int spacing = 0;
      for (DeviceFeature i : m_features.values()) {
        if (i.hasListeners()) {
          Msg m = i.makePollMsg();
          if (m != null) l.add(new QEntry(i, m, now + delay + spacing));
        }
        spacing += TIME_BETWEEN_POLL_MESSAGES;
      }
    }
    if (l.isEmpty()) return;
    synchronized (m_requestQueue) {
      for (QEntry e : l) {
        m_requestQueue.add(e);
      }
    }
    RequestQueueManager.s_instance().addQueue(this, now + delay);

    if (!l.isEmpty()) {
      synchronized (m_lastTimePolled) {
        m_lastTimePolled = now;
      }
    }
  }
 /**
  * Show the dialog if needed
  *
  * @param project the project
  * @param root the vcs root
  * @return true if showing is not needed or operation completed successfully
  */
 public static boolean showIfNeeded(final Project project, final VirtualFile root) {
   final ArrayList<String> files = new ArrayList<String>();
   try {
     scanFiles(project, root, files);
     final AtomicBoolean rc = new AtomicBoolean(true);
     if (!files.isEmpty()) {
       UIUtil.invokeAndWaitIfNeeded(
           new Runnable() {
             public void run() {
               GitUpdateLocallyModifiedDialog d =
                   new GitUpdateLocallyModifiedDialog(project, root, files);
               d.show();
               rc.set(d.isOK());
             }
           });
       if (rc.get()) {
         if (!files.isEmpty()) {
           revertFiles(project, root, files);
         }
       }
     }
     return rc.get();
   } catch (final VcsException e) {
     UIUtil.invokeAndWaitIfNeeded(
         new Runnable() {
           public void run() {
             GitUIUtil.showOperationError(project, e, "Checking for locally modified files");
           }
         });
     return false;
   }
 }
Example #17
0
  private Block getBlockWithMinimumCounter(Address address) {

    ArrayList<Block> tempBlockArray = new ArrayList<Block>();

    for (int n = 0; n < associativity; n++) {
      Block[] blocks = setAssociativeArray.get(n);
      if (blocks[address.getIndex()].getHitCounter() == 0)
        tempBlockArray.add(blocks[address.getIndex()]);
    }

    if (tempBlockArray.isEmpty()) {
      for (int n = 0; n < associativity; n++) {
        Block[] blocks = setAssociativeArray.get(n);
        if (blocks[address.getIndex()].getHitCounter() == 1)
          tempBlockArray.add(blocks[address.getIndex()]);
      }
    }

    if (tempBlockArray.isEmpty()) {
      for (int n = 0; n < associativity; n++) {
        Block[] blocks = setAssociativeArray.get(n);
        if (blocks[address.getIndex()].getHitCounter() == 2)
          tempBlockArray.add(blocks[address.getIndex()]);
      }
    }

    return tempBlockArray.get((new Random()).nextInt(tempBlockArray.size()));
  }
 @Override
 public Boolean existeMatricula(Alumno alumno) throws Exception {
   Boolean resultado = false;
   Alumno alumnoEjemplo = new Alumno();
   alumnoEjemplo.setMatricula(alumno.getMatricula());
   try {
     ArrayList<Alumno> listaAlumnos = this.getByExample(alumnoEjemplo);
     if (alumno.getIdUsuario() == null) {
       resultado = (listaAlumnos.isEmpty() ? false : true);
     } else {
       if (!listaAlumnos.isEmpty()) {
         Alumno alumnoTemp = new Alumno();
         for (Alumno a : listaAlumnos) {
           alumnoTemp = a;
         }
         if (alumnoTemp.getIdUsuario().equals(alumno.getIdUsuario())) {
           resultado = false;
         } else {
           resultado = true;
         }
       }
     }
   } catch (Exception ex) {
     throw ex;
   }
   return resultado;
 }
Example #19
0
  // 본문이 입력되지 않으면 글이 등록되지 않음.
  private boolean validCheck() {
    if (content.getText().toString().equals("")) {
      Toast.makeText(WriteDiary.this, "일기 내용이 없습니다.", 0).show();
      return false;
    }
    if (title.getText().toString().equals("")) {
      Toast.makeText(WriteDiary.this, "일기 제목이 없습니다.", 0).show();
      return false;
    }

    // 사진경로가 있는거 까지만 값 옮기고 null인 인덱스는 null로 넣음ㅋ 무슨말이냐
    if (picturePathLists.isEmpty() == false) {
      int j = 0;
      for (int i = 0; i < picturePathLists.size(); i++) {
        if (picturePathLists.get(i).toString().equals("") == false) {
          picPath[j] = picturePathLists.get(i).toString();
          j++;
        }
      }
      for (int i = j; i < picPath.length; i++) {
        picPath[i] = null;
      }
    } else if (picturePathLists.isEmpty()) {
      for (int i = 0; i < picPath.length; i++) {
        picPath[i] = null;
      }
    }

    return true;
  }
Example #20
0
  @Override
  public DataUsuario obtenerDatosUsuario() {
    ArrayList<DataProducto> dataProductos = new ArrayList<>();
    ArrayList<DataPedido> dataPedidos = new ArrayList<>();

    if (!productos.isEmpty()) {
      for (Producto p : productos) {
        dataProductos.add(p.obtenerDatosProducto());
      }
    }
    ArrayList<Pedido> lp = getPedidos();
    if (!lp.isEmpty()) {
      for (Pedido pe : lp) {
        dataPedidos.add(pe.obtenerDatosPedido());
      }
    }
    DataUsuario dataUsuario =
        new DataRestaurante(
            rutaImagen,
            dataProductos,
            getPuntajePromedio(),
            cantidadPuntuaciones,
            this.getNickname(),
            this.getMail(),
            this.getNombre(),
            this.getPass(),
            this.getDireccion(),
            dataPedidos);
    return dataUsuario;
  }
  /**
   * M: Imap partial download implementation. If MIME contain html parts, we only download html
   * part, otherwise we use text parts.
   *
   * @param message
   * @param remoteFolder
   * @return if partial download success.
   */
  public static boolean imapPartialFetchMessage(Message message, Folder remoteFolder)
      throws MessagingException {
    boolean isPartialDownload = false;
    // We have a structure to deal with, from which
    // we can pull down the parts we want to actually store.
    // Build a list of parts we are interested in. Text parts
    // will be downloaded right now, attachments will be left for later.
    ArrayList<Part> viewables = new ArrayList<Part>();
    ArrayList<Part> attachments = new ArrayList<Part>();

    MimeUtility.collectParts(message, viewables, attachments);

    // Separate plain & html viewable parts
    ArrayList<Part> plainTexts = new ArrayList<Part>();
    ArrayList<Part> htmlTexts = new ArrayList<Part>();
    int plainTextsSize = 0;
    int htmlTextsSize = 0;
    for (Part part : viewables) {
      if (PLAINTEXT_MIMETYPE.equalsIgnoreCase(part.getMimeType())) {
        plainTexts.add(part);
        plainTextsSize += part.getSize();
      }
      if (HTMLTEXT_MIMETYPE.equalsIgnoreCase(part.getMimeType())) {
        htmlTexts.add(part);
        htmlTextsSize += part.getSize();
      }
    }

    if (!htmlTexts.isEmpty()) {
      isPartialDownload = fetchTextParts(htmlTexts, htmlTextsSize, remoteFolder, message);
    } else if (!plainTexts.isEmpty()) {
      isPartialDownload = fetchTextParts(plainTexts, plainTextsSize, remoteFolder, message);
    }
    return isPartialDownload;
  }
 private ForgeDirection getMovementDirection(
     int x, int y, int z, ForgeDirection last, Random rand) {
   // if (rand.nextInt(3) == 0 && this.canMove(x, y, z, last) && !this.hasCellFrom(x, y, z, last))
   // //bias towards continuing direction
   //	return last;
   last = pathCache.getLast().getOpposite();
   // ReikaJavaLibrary.pConsole("Data at "+x+", "+y+", "+z+"; last is "+last);
   ArrayList<ForgeDirection> li =
       ReikaJavaLibrary.makeListFromArray(ForgeDirection.VALID_DIRECTIONS);
   int idx = rand.nextInt(li.size());
   while (li.get(idx) == last
       || !this.canMove(x, y, z, li.get(idx))
       || this.hasCellFrom(x, y, z, li.get(idx))) {
     li.remove(idx);
     // dir = ForgeDirection.VALID_DIRECTIONS[rand.nextInt(6)];
     if (li.isEmpty()) {
       for (int i = 0; i < 6; i++) {
         ForgeDirection dir = ForgeDirection.VALID_DIRECTIONS[i];
         // ReikaJavaLibrary.pConsole(dir+": LAST="+(dir == last)+"| CANMOVE="+!this.canMove(x, y,
         // z, dir)+"| HAS="+this.hasCellFrom(x, y, z, dir));
       }
       // ReikaJavaLibrary.pConsole("UNVISIT="+this.hasUnvisitedNeighbors(x, y, z));
       // ReikaJavaLibrary.pConsole("Had no paths yet has an unvisited neighbor?!!");
     }
     idx = rand.nextInt(li.size());
     // ReikaJavaLibrary.pConsole("Random testing "+idx+" of "+li.size());
   }
   if (li.isEmpty()) {
     // ReikaJavaLibrary.pConsole("Had no paths yet has an unvisited neighbor?!!");
   }
   return li.get(idx);
 }
  public static IFix createCleanUp(
      JavaScriptUnit compilationUnit,
      boolean addParanoicParentesis,
      boolean removeUnnecessaryParenthesis) {

    if (addParanoicParentesis) {
      final ArrayList changedNodes = new ArrayList();
      compilationUnit.accept(new MissingParenthesisVisitor(changedNodes));

      if (changedNodes.isEmpty()) return null;

      IFixRewriteOperation op =
          new AddParenthesisOperation(
              (Expression[]) changedNodes.toArray(new Expression[changedNodes.size()]));
      return new ExpressionsFix(
          FixMessages.ExpressionsFix_add_parenthesis_change_name,
          compilationUnit,
          new IFixRewriteOperation[] {op});
    } else if (removeUnnecessaryParenthesis) {
      final ArrayList changedNodes = new ArrayList();
      compilationUnit.accept(new UnnecessaryParenthesisVisitor(changedNodes));

      if (changedNodes.isEmpty()) return null;

      HashSet expressions = new HashSet(changedNodes);
      IFixRewriteOperation op = new RemoveParenthesisOperation(expressions);
      return new ExpressionsFix(
          FixMessages.ExpressionsFix_remove_parenthesis_change_name,
          compilationUnit,
          new IFixRewriteOperation[] {op});
    }
    return null;
  }
Example #24
0
 public void setSelected(Collection<CanvasObject> shapes, boolean value) {
   if (value) {
     ArrayList<CanvasObject> added;
     added = new ArrayList<>(shapes.size());
     for (CanvasObject shape : shapes) {
       if (selected.add(shape)) {
         added.add(shape);
       }
     }
     if (!added.isEmpty()) {
       fireChanged(SelectionEvent.ACTION_ADDED, added);
     }
   } else {
     ArrayList<CanvasObject> removed;
     removed = new ArrayList<>(shapes.size());
     for (CanvasObject shape : shapes) {
       if (selected.remove(shape)) {
         suppressed.remove(shape);
         Handle h = selectedHandle;
         if (h != null && h.getObject() == shape) setHandleSelected(null);
         removed.add(shape);
       }
     }
     if (!removed.isEmpty()) {
       fireChanged(SelectionEvent.ACTION_REMOVED, removed);
     }
   }
 }
Example #25
0
  /**
   * Returns all summary path nodes for the specified location step or {@code null} if nodes cannot
   * be retrieved or are found on different levels.
   *
   * @param data data reference
   * @param last last step to be checked
   * @return path nodes
   */
  private ArrayList<PathNode> pathNodes(final Data data, final int last) {
    // skip request if no path index exists or might be out-of-date
    if (!data.meta.uptodate) return null;

    ArrayList<PathNode> nodes = data.paths.root();
    for (int s = 0; s <= last; s++) {
      // only follow axis steps
      final Step curr = axisStep(s);
      if (curr == null) return null;

      final boolean desc = curr.axis == DESC;
      if (!desc && curr.axis != CHILD || curr.test.kind != Kind.NAME) return null;

      final int name = data.elemNames.id(curr.test.name.local());

      final ArrayList<PathNode> tmp = new ArrayList<>();
      for (final PathNode node : PathSummary.desc(nodes, desc)) {
        if (node.kind == Data.ELEM && name == node.name) {
          // skip test if an element name occurs on different levels
          if (!tmp.isEmpty() && tmp.get(0).level() != node.level()) return null;
          tmp.add(node);
        }
      }
      if (tmp.isEmpty()) return null;
      nodes = tmp;
    }
    return nodes;
  }
Example #26
0
  // Dont use this method just jet. We need to fix the columnscoring first.
  // TODO: What this method needs is the end of the table!!! For this it also needs to know the end
  // of the row!!!
  private void checkMapForX2Columns() {
    ArrayList<String> col = new ArrayList<String>();
    ArrayList<Integer> X2Col = new ArrayList<Integer>();
    ArrayList<Integer> X1Col = new ArrayList<Integer>();

    for (int x = 0; x < tableMap.size(); x++) {

      boolean startOfTable = false;

      ArrayList<String> currentPixel = tableMap.get(x);

      if (!currentPixel.isEmpty() && !startOfTable && col.isEmpty()) {
        startOfTable = true;
        X1Col.add(x);
      }

      if (!currentPixel.isEmpty() && startOfTable) {
        col.add(tableMap.get(x).toString());
        startOfTable = false;
      }
      if (currentPixel.isEmpty() && !col.isEmpty()) {
        col = new ArrayList<String>();
        X2Col.add(x);
        startOfTable = false;
      }
    }
    System.out.println("Begin of Column: " + X1Col);
    LOGGER.info("Begin of the Column: " + X1Col);
    System.out.println("End of Column: " + X2Col);
    LOGGER.info("End of Column: " + X2Col);
    this.X2ColumnBoundaries = X2Col;
    this.X1ColumnBoundaries = X1Col;
  }
Example #27
0
 private String compatibleLanguageCode(Locale language) {
   final ArrayList<Locale> compatibleLanguages = new ArrayList<Locale>();
   for (Locale supportedLanguage : supportedLanguages) {
     try {
       if (supportedLanguage.getISO3Language().equals(language.getISO3Language())) {
         compatibleLanguages.add(supportedLanguage);
       }
     } catch (MissingResourceException e) {
     } // No 3-letter language code for locale (as in cmn-Hans-CN), which can be ignored in our
       // case
   }
   if (!compatibleLanguages.isEmpty() && language.getCountry().equals(""))
     return compatibleLanguages.get(0).getLanguage(); // Not a country specific locale
   for (Locale compatibleLanguage : compatibleLanguages) {
     try {
       if (compatibleLanguage.getISO3Country().equals(language.getISO3Country())) {
         return compatibleLanguage.getLanguage()
             + "-"
             + compatibleLanguage.getCountry().toUpperCase();
       }
     } catch (MissingResourceException e) {
     } // No 3-letter country code for locale (as in cmn-Hans-CN), which can be ignored in our case
   }
   return compatibleLanguages.isEmpty() ? null : compatibleLanguages.get(0).getLanguage();
 }
 private ArrayList<StructureSkipSuggestion> getCurrentAndNextSkipSuggestions(int failureIndex) {
   ArrayList<StructureSkipSuggestion> nextRegions = new ArrayList<StructureSkipSuggestion>();
   ArrayList<StructureSkipSuggestion> currRegions = selectRegion(failureIndex);
   int fwMax = failureIndex + MAX_NR_OF_LINES;
   int lineIndex = failureIndex;
   int nrOfStructs = 0;
   int indentValueStart = -1;
   if (currRegions.size() > 0)
     indentValueStart = currRegions.get(0).getStartSkip().getIndentValue();
   do {
     nrOfStructs++;
     for (StructureSkipSuggestion r : currRegions) {
       if (r.getAdditionalTokens().length == 0) nextRegions.add(r);
     }
     if (!currRegions.isEmpty()) {
       lineIndex = currRegions.get(0).getIndexHistoryEnd();
       if (currRegions.get(0).getStartSkip().getIndentValue() >= indentValueStart) {
         // System.out.println(currRegions.get(0).getIndexHistoryStart()+" => "+
         // currRegions.get(0).getIndexHistoryEnd());
         currRegions = selectRegion(currRegions.get(0).getIndexHistoryEnd());
       } else currRegions.clear(); // no dedent allowed
     }
   } while (nrOfStructs < MAX_NR_OF_STRUCTURES && lineIndex < fwMax && !currRegions.isEmpty());
   return nextRegions;
 }
Example #29
0
  @Override
  protected void onDraw(Canvas canvas) {
    int i = 1;
    if (percentList != null && !percentList.isEmpty()) {
      for (Float f : percentList) {
        rect.set(
            BAR_SIDE_MARGIN * i + barWidth * (i - 1),
            topMargin,
            (BAR_SIDE_MARGIN + barWidth) * i,
            getHeight() - bottomTextHeight - TEXT_TOP_MARGIN);
        canvas.drawRect(rect, bgPaint);
        rect.set(
            BAR_SIDE_MARGIN * i + barWidth * (i - 1),
            topMargin + (int) ((getHeight() - topMargin) * percentList.get(i - 1)),
            (BAR_SIDE_MARGIN + barWidth) * i,
            getHeight() - bottomTextHeight - TEXT_TOP_MARGIN);
        canvas.drawRect(rect, fgPaint);
        i++;
      }
    }

    if (bottomTextList != null && !bottomTextList.isEmpty()) {
      i = 1;
      for (String s : bottomTextList) {
        canvas.drawText(
            s,
            BAR_SIDE_MARGIN * i + barWidth * (i - 1) + barWidth / 2,
            getHeight() - bottomTextDescent,
            textPaint);
        i++;
      }
    }
  }
  /**
   * @throws IOException due to {@link SocketChannel#write(ByteBuffer)} call
   * @throws CancelledKeyException
   * @see
   *     com.niffy.AndEngineLockStepEngine.threads.nio.BaseSelectorThread#write(java.nio.channels.SelectionKey)
   */
  @Override
  protected void write(SelectionKey pKey) throws IOException, CancelledKeyException {
    DatagramChannel socketChannel;
    String connectionIP;
    socketChannel = (DatagramChannel) pKey.channel();
    InetSocketAddress address = (InetSocketAddress) socketChannel.socket().getRemoteSocketAddress();
    connectionIP = address.getAddress().getHostAddress();
    InetSocketAddress target = (InetSocketAddress) pKey.attachment();

    synchronized (this.mPendingData) {
      ArrayList<ByteBuffer> queue = this.mPendingData.get(target.getAddress());

      // Write until there's not more data ...
      while (!queue.isEmpty()) {
        ByteBuffer buf = (ByteBuffer) queue.get(0);
        socketChannel.send(buf, target);
        if (buf.remaining() > 0) {
          // ... or the socket's buffer fills up
          break;
        }
        queue.remove(0);
      }

      if (queue.isEmpty()) {
        // We wrote away all data, so we're no longer interested
        // in writing on this socket. Switch back to waiting for
        // data.
        pKey.interestOps(SelectionKey.OP_READ);
      }
    }
  }