Beispiel #1
0
  // Computes probabilities for candidates
  static void computeProbabilities(List<Candidate> candidates, int clusters) {
    // Compute max score to prevent overflow
    double max = Double.NEGATIVE_INFINITY;
    for (Candidate candidate : candidates)
      for (int j = 0; j < clusters; j++) max = Math.max(max, candidate.clusterScores[j]);

    // Exponentiate and compute sum
    double sum = 0;
    for (Candidate candidate : candidates)
      for (int j = 0; j < clusters; j++) {
        double clusterProb = Math.exp(candidate.clusterScores[j] - max);
        sum += clusterProb;
        candidate.clusterProbs[j] = clusterProb;
      }

    // Normalize and compute candidate probabilities
    for (Candidate candidate : candidates) {
      double prob = 0;
      for (int j = 0; j < clusters; j++) {
        double clusterProb = candidate.clusterProbs[j] / sum;
        prob += clusterProb;
        candidate.clusterProbs[j] = clusterProb;
      }
      candidate.prob = prob;
    }
  }
  /**
   * ****************************************************************************************************************************************
   */
  private static List<Candidate> evalCandidates(File file, BufferedImage image) {

    List<Candidate> candidatesToClassify = new ArrayList<Candidate>();

    // get candidate contours
    Collection<List<PointIndex_I32>> candidates =
        getCandidates(
            image,
            blurRadius,
            threshLow,
            threshHigh,
            toleranceDist,
            toleranceAngle,
            dynamicThreshold);

    for (List<PointIndex_I32> vertices : candidates) {
      try {
        Candidate c = new Candidate(vertices, image);
        if (c.size(minsize)) {
          c.rotate();
          candidatesToClassify.add(c);
        }
      } catch (Exception e) {
        // System.out.println("Error creating candidate from contour " +
        // e.getMessage());
      }
    }
    return candidatesToClassify;
  }
  /**
   * ****************************************************************************************************************************************
   */
  public static List<BufferedImage> findObjects(BufferedImage image) throws IOException {

    List<BufferedImage> positive = new ArrayList<BufferedImage>();

    // generate candidate contours
    Collection<List<PointIndex_I32>> candidates =
        getCandidates(
            image,
            blurRadius,
            threshLow,
            threshHigh,
            toleranceDist,
            toleranceAngle,
            dynamicThreshold);

    for (List<PointIndex_I32> vertices : candidates) {
      try {
        Candidate c = new Candidate(vertices, image);
        if (c.size(minsize)) {
          c.rotate();
          positive.add(c.getImage());
        }
      } catch (Exception e) {
        System.out.println("Error creating candidate from contour " + e.getMessage());
      }
    }

    return positive;
  }
Beispiel #4
0
 private static Candidate createCandidate(Map<String, String> beanAttr) {
   if (beanAttr == null) return null;
   Candidate candidate = new Candidate();
   candidate.setAttributes(BeansUtils.deserializeStringToMap(beanAttr.get("attributes")));
   // Parse and get ExtSource
   UserExtSource userExtSource;
   if (beanAttr.get("userExtSource").equals("\\0")) userExtSource = null;
   else {
     List<Pair<String, Map<String, String>>> userExtSourceMap =
         beansToMap(beanAttr.get("userExtSource"));
     userExtSource = createUserExtSource(userExtSourceMap.get(0).getRight());
   }
   candidate.setUserExtSource(userExtSource);
   // Parse and get list of UserExtSources
   List<UserExtSource> additionalUserExtSources = new ArrayList<UserExtSource>();
   if (beanAttr.get("additionalUserExtSources").equals("\\0")) additionalUserExtSources = null;
   else {
     List<Pair<String, Map<String, String>>> userExtSourcesList =
         beansToMap(beanAttr.get("additionalUserExtSources"));
     for (Pair<String, Map<String, String>> p : userExtSourcesList) {
       userExtSource = createUserExtSource(p.getRight());
       additionalUserExtSources.add(userExtSource);
     }
   }
   candidate.setAdditionalUserExtSources(additionalUserExtSources);
   return candidate;
 }
  public boolean better(Candidate candidate1, Candidate candidate2) {

    // LOSR.
    Losr losr1 = candidate1.losr();
    Losr losr2 = candidate2.losr();

    // Span.
    TextContext span1 = losr1.span();
    TextContext span2 = losr2.span();
    if (span1.end() > span2.end()) {
      return true;
    }

    // Events.
    if (losr1 instanceof Event && losr2 instanceof Event) {
      Event event1 = (Event) losr1;
      Event event2 = (Event) losr2;

      // Drop events.
      if (event1.action() == Actions.Drop && event2.action() == Actions.Drop) {
        if (event1.destination() != null && event2.destination() == null) {
          return true;
        }
      }
    }

    // Weight.
    return candidate1.weight() > candidate2.weight();
  }
Beispiel #6
0
 private Candidate pop() {
   Candidate n = queue;
   if (n != null) {
     queue = n.queueNext;
     n.queueNext = null;
   }
   return n;
 }
Beispiel #7
0
 private boolean reverseResult(Candidate parent, Candidate source) throws IOException {
   // On a reverse blame present the application the parent
   // (as this is what did the removals), however the region
   // list to enumerate is the source's surviving list.
   Candidate res = parent.copy(parent.sourceCommit);
   res.regionList = source.regionList;
   return result(res);
 }
Beispiel #8
0
 private void push(BlobCandidate toInsert) {
   Candidate c = queue;
   if (c != null) {
     c.remove(SEEN); // will be pushed by toInsert
     c.regionList = null;
     toInsert.parent = c;
   }
   queue = toInsert;
 }
Beispiel #9
0
  private boolean processOne(Candidate n) throws IOException {
    RevCommit parent = n.getParent(0);
    if (parent == null) return split(n.getNextCandidate(0), n);
    revPool.parseHeaders(parent);

    if (find(parent, n.sourcePath)) {
      if (idBuf.equals(n.sourceBlob)) return blameEntireRegionOnParent(n, parent);
      return splitBlameWithParent(n, parent);
    }

    if (n.sourceCommit == null) return result(n);

    DiffEntry r = findRename(parent, n.sourceCommit, n.sourcePath);
    if (r == null) return result(n);

    if (0 == r.getOldId().prefixCompare(n.sourceBlob)) {
      // A 100% rename without any content change can also
      // skip directly to the parent.
      n.sourceCommit = parent;
      n.sourcePath = PathFilter.create(r.getOldPath());
      push(n);
      return false;
    }

    Candidate next = n.create(parent, PathFilter.create(r.getOldPath()));
    next.sourceBlob = r.getOldId().toObjectId();
    next.renameScore = r.getScore();
    next.loadText(reader);
    return split(next, n);
  }
 /**
  * Determines which DropController represents the deepest DOM descendant drop target located at
  * the provided location <code>(x, y)</code>.
  *
  * @param x offset left relative to document body
  * @param y offset top relative to document body
  * @return a drop controller for the intersecting drop target or <code>null</code> if none are
  *     applicable
  */
 DropController getIntersectDropController(int x, int y) {
   Location location = new CoordinateLocation(x, y);
   for (int i = sortedCandidates.length - 1; i >= 0; i--) {
     Candidate candidate = sortedCandidates[i];
     Area targetArea = candidate.getTargetArea();
     if (targetArea.intersects(location)) {
       return candidate.getDropController();
     }
   }
   return null;
 }
Beispiel #11
0
  public synchronized Candidate getTopCandidate() {
    Candidate topCandidate = null;
    int topVote = Integer.MIN_VALUE;
    for (Candidate candidate : this) {
      if (candidate.getScore() > topVote) {
        topCandidate = candidate;
        topVote = candidate.getScore();
      }
    }

    return topCandidate;
  }
 public void insertCandidate(Candidate c) {
   try {
     Connection con = getConnection();
     String query = "INSERT INTO i_users (emailid, username, passwords) VALUES(?,?,?)";
     PreparedStatement stmt = con.prepareStatement(query);
     stmt.setString(1, c.getEmailid());
     stmt.setString(2, c.getUsername());
     stmt.setString(3, c.getPassword());
     stmt.executeUpdate();
   } catch (SQLException e) {
   }
 }
 /**
  * Returns the 'final candidate', i.e. the most likely candidate for the subject of the supplied
  * form response. This is determined by fetching all candidates, and selecting the ones that are
  * over 97% confidence. If there is only one over 97% confidence, then that candidate is returned.
  * Otherwise, this method returns null
  *
  * @param response
  * @return
  */
 public Person getFinalCandidate(MedicFormResponse response) {
   List<Candidate> candidates = getCandidatesForResponse(response);
   List<Candidate> finalCandidates = new ArrayList<Candidate>();
   for (Candidate c : candidates) {
     if (c.getAverageScore() >= 97F) {
       finalCandidates.add(c);
     }
   }
   if (finalCandidates.size() == 1) {
     return finalCandidates.get(0).getPatient();
   }
   return null;
 }
  public void addNewFeature(int feat, int labelId, double weight, boolean canAdd)
      throws IOException {

    if (labelToCandidate.containsKey(labelId)) {
      Candidate temp = labelToCandidate.get(labelId);
      if (temp.ifExistsFeature(feat)) {
        // Add ;
      } else temp.getFeatureList().add(new FeatureWeight(feat, weight));
    } else {
      List<FeatureWeight> newfw = new ArrayList<FeatureWeight>();
      newfw.add(new FeatureWeight(feat, weight));
      Candidate c = new Candidate(newfw, labelId);
    }
  }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

      Candidate c = clist.get(position);

      LayoutInflater linf = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
      View v = linf.inflate(R.layout.customview, null);

      TextView tvName = (TextView) v.findViewById(R.id.tvName);
      TextView tvMobileno = (TextView) v.findViewById(R.id.tvMobileno);

      tvName.setText(c.getName());
      tvMobileno.setText(c.getMobileno());

      return v;
    }
Beispiel #16
0
  private boolean split(Candidate parent, Candidate source) throws IOException {
    EditList editList = diffAlgorithm.diff(textComparator, parent.sourceText, source.sourceText);
    if (editList.isEmpty()) {
      // Ignoring whitespace (or some other special comparator) can
      // cause non-identical blobs to have an empty edit list. In
      // a case like this push the parent alone.
      parent.regionList = source.regionList;
      push(parent);
      return false;
    }

    parent.takeBlame(editList, source);
    if (parent.regionList != null) push(parent);
    if (source.regionList != null) {
      if (source instanceof ReverseCandidate) return reverseResult(parent, source);
      return result(source);
    }
    return false;
  }
  @Override
  public boolean hasNext() {
    boolean matchFound = false;
    while (ec.hasMoreElements()) {
      Candidate tempObj = (Candidate) ec.nextElement();
      if (tempObj.getCertificationType().equals(certifiedcationType)) {
        matchFound = true;
        nextCandidate = tempObj;
        break;
      }
      if (matchFound == true) {

      } else {
        nextCandidate = null;
      }
    }

    return matchFound;
  }
Beispiel #18
0
  /**
   * Step the blame algorithm one iteration.
   *
   * @return true if the generator has found a region's source. The getSource* and {@link
   *     #getResultStart()}, {@link #getResultEnd()} methods can be used to inspect the region
   *     found. False if there are no more regions to describe.
   * @throws IOException repository cannot be read.
   */
  public boolean next() throws IOException {
    // If there is a source still pending, produce the next region.
    if (outRegion != null) {
      Region r = outRegion;
      remaining -= r.length;
      if (r.next != null) {
        outRegion = r.next;
        return true;
      }

      if (outCandidate.queueNext != null) return result(outCandidate.queueNext);

      outCandidate = null;
      outRegion = null;
    }

    // If there are no lines remaining, the entire result is done,
    // even if there are revisions still available for the path.
    if (remaining == 0) return done();

    for (; ; ) {
      Candidate n = pop();
      if (n == null) return done();

      int pCnt = n.getParentCount();
      if (pCnt == 1) {
        if (processOne(n)) return true;

      } else if (1 < pCnt) {
        if (processMerge(n)) return true;

      } else if (n instanceof ReverseCandidate) {
        // Do not generate a tip of a reverse. The region
        // survives and should not appear to be deleted.

      } else /* if (pCnt == 0) */ {
        // Root commit, with at least one surviving region.
        // Assign the remaining blame here.
        return result(n);
      }
    }
  }
  /**
   * Cache a list of eligible drop controllers, sorted by relative DOM positions of their respective
   * drop targets. Called at the beginning of each drag operation, or whenever drop target
   * eligibility has changed while dragging.
   *
   * @param boundaryPanel boundary area for drop target eligibility considerations
   * @param context the current drag context
   */
  void resetCache(Panel boundaryPanel, DragContext context) {
    ArrayList<Candidate> list = new ArrayList<Candidate>();

    if (context.draggable != null) {
      WidgetArea boundaryArea = new WidgetArea(boundaryPanel, null);
      for (DropController dropController : dropControllerList) {
        Candidate candidate = new Candidate(dropController);
        if (DOM.isOrHasChild(
            context.draggable.getElement(), candidate.getDropTarget().getElement())) {
          continue;
        }
        if (candidate.getTargetArea().intersects(boundaryArea)) {
          list.add(candidate);
        }
      }
    }

    sortedCandidates = list.toArray(new Candidate[list.size()]);
    Arrays.sort(sortedCandidates);
  }
 public int compareTo(Candidate other) {
   Element myElement = getDropTarget().getElement();
   Element otherElement = other.getDropTarget().getElement();
   if (myElement == otherElement) {
     return 0;
   } else if (DOM.isOrHasChild(myElement, otherElement)) {
     return -1;
   } else if (DOM.isOrHasChild(otherElement, myElement)) {
     return 1;
   } else {
     return 0;
   }
 }
Beispiel #21
0
 private static String createJSON(ResultSet rs, String party, String area) {
   List<Candidate> candidates = new ArrayList<Candidate>();
   try {
     while (rs.next()) {
       Candidate candidate = new Candidate();
       candidate.setFName(rs.getString("FirstName"));
       candidate.setLName(rs.getString("LastName"));
       if (party.equals("") || party == null) {
         candidate.setParty(rs.getString("PartyName"));
       }
       if (area.equals("") || area == null) {
         candidate.setArea(rs.getString("AreaName"));
       }
       candidates.add(candidate);
     }
   } catch (SQLException e) {
     e.printStackTrace();
   }
   Gson gson = new GsonBuilder().create();
   String candidatesJson = gson.toJson(candidates);
   return candidatesJson;
 }
 public String deleteCandidate() {
   this.candidate = nominatingSessionBean.getCandidate(candidateLogin);
   this.eventId = getEventId();
   try {
     nominatingSessionBean.deleteCandidateFromEvent(candidate, eventId);
     FacesMessage m =
         new FacesMessage("Candidate " + candidate.getLogin() + " was successfully removed");
     FacesContext.getCurrentInstance().addMessage("nic", m);
   } catch (ControllerException ex) {
     Logger.getLogger(VotingManagedBean.class.getName()).log(Level.SEVERE, null, ex);
     return "";
   }
   return "";
 }
Beispiel #23
0
 /** Returns a list of software skills for the specified candidate */
 public static List getAllSoftwareSkillsFor(Candidate candidate) {
   List result = new ArrayList();
   try {
     SoftwareCandidateQuery query = new SoftwareCandidateQuery();
     query.setQueryCandidate(candidate.getDO());
     SoftwareCandidateDO element = query.getNextDO();
     while (element != null) {
       result.add(new SoftwareSkill(element));
       element = query.getNextDO();
     }
   } catch (Exception qe) {
     System.err.println(qe);
   }
   return result;
 }
 public static void adminReport() {
   /**
    * A logged in User should not be able to access this page inadvertently by knowing the URL. In
    * Administrator Controller, when an admin signs in, I wrote a key of "logged_in_adminid" to the
    * session. Check here to be safe
    */
   if (session.contains("logged_in_adminid") == false) {
     Administrator.login();
   } else {
     /** get lists of all Users and Candidates in the system and pass to html to create tables */
     List<User> users = User.findAll();
     List<Candidate> candidates = Candidate.findAll();
     render(users, candidates);
   }
 }
Beispiel #25
0
  /**
   * Push a candidate object onto the generator's traversal stack.
   *
   * <p>Candidates should be pushed in history order from oldest-to-newest. Applications should push
   * the starting commit first, then the index revision (if the index is interesting), and finally
   * the working tree copy (if the working tree is interesting).
   *
   * @param description description of the blob revision, such as "Working Tree".
   * @param id may be a commit or a blob.
   * @return {@code this}
   * @throws IOException the repository cannot be read.
   */
  public BlameGenerator push(String description, AnyObjectId id) throws IOException {
    ObjectLoader ldr = reader.open(id);
    if (ldr.getType() == OBJ_BLOB) {
      if (description == null) description = JGitText.get().blameNotCommittedYet;
      BlobCandidate c = new BlobCandidate(description, resultPath);
      c.sourceBlob = id.toObjectId();
      c.sourceText = new RawText(ldr.getCachedBytes(Integer.MAX_VALUE));
      c.regionList = new Region(0, 0, c.sourceText.size());
      remaining = c.sourceText.size();
      push(c);
      return this;
    }

    RevCommit commit = revPool.parseCommit(id);
    if (!find(commit, resultPath)) return this;

    Candidate c = new Candidate(commit, resultPath);
    c.sourceBlob = idBuf.toObjectId();
    c.loadText(reader);
    c.regionList = new Region(0, 0, c.sourceText.size());
    remaining = c.sourceText.size();
    push(c);
    return this;
  }
Beispiel #26
0
  public synchronized void vote(String name, InetAddress ip) throws UserException {
    if (isClosed()) {
      throw new UserException("The votes are closed");
    }

    if (ips.contains(ip)) {
      throw new UserException("IP " + ip + " has already voted");
    }
    ips.add(ip);

    Candidate theCandidate = null;
    for (Candidate candidate : this) {
      if (candidate.getName().equals(name)) {
        theCandidate = candidate;
        break;
      }
    }

    if (theCandidate == null) {
      throw new UserException("Candidate " + name + " doesn't exist");
    }

    theCandidate.vote();
  }
Beispiel #27
0
  /**
   * Attempts to lead the singleton service.
   *
   * @param endpoint The primary endpoint to register as a leader candidate in the service.
   * @param additionalEndpoints Additional endpoints that are available on the host.
   * @param listener Handler to call when the candidate is elected or defeated.
   * @throws Group.WatchException If there was a problem watching the ZooKeeper group.
   * @throws Group.JoinException If there was a problem joining the ZooKeeper group.
   * @throws InterruptedException If the thread watching/joining the group was interrupted.
   */
  public void lead(
      final InetSocketAddress endpoint,
      final Map<String, InetSocketAddress> additionalEndpoints,
      final LeadershipListener listener)
      throws Group.WatchException, Group.JoinException, InterruptedException {

    Preconditions.checkNotNull(listener);

    candidate.offerLeadership(
        new Leader() {
          private ServerSet.EndpointStatus endpointStatus = null;

          @Override
          public void onElected(final ExceptionalCommand<JoinException> abdicate) {
            listener.onLeading(
                new LeaderControl() {
                  ServerSet.EndpointStatus endpointStatus = null;
                  final AtomicBoolean left = new AtomicBoolean(false);

                  // Methods are synchronized to prevent simultaneous invocations.
                  @Override
                  public synchronized void advertise() throws JoinException, InterruptedException {

                    Preconditions.checkState(!left.get(), "Cannot advertise after leaving.");
                    Preconditions.checkState(
                        endpointStatus == null, "Cannot advertise more than once.");
                    endpointStatus = serverSet.join(endpoint, additionalEndpoints);
                  }

                  @Override
                  public synchronized void leave() throws ServerSet.UpdateException, JoinException {
                    Preconditions.checkState(
                        left.compareAndSet(false, true), "Cannot leave more than once.");
                    if (endpointStatus != null) {
                      endpointStatus.leave();
                    }
                    abdicate.execute();
                  }
                });
          }

          @Override
          public void onDefeated() {
            listener.onDefeated(endpointStatus);
          }
        });
  }
 public void evaluate(Candidate candidate) {
   candidate.include(((B) candidate.getObject()).a == _c._a);
 }
  public static void main(String[] args) throws IOException {

    if (args.length == 0) {
      System.out.println(
          "usage: crop-objects [OPTION]... FILE [DIR]\n"
              + "crops detected objects from image FILE and writes their subimages to files. \n"
              + "Can specify the DIR in which to create the files, otherwise subimage files are "
              + "created in the same directory as FILE is in by default. \n"
              + "-t [n] [m] 		set the high and low threshold values. n and m are values between 0 and 1.");
      System.exit(1);
    }
    // interpret options and read arguments
    if (args[0].equals("-t")) {

      threshLow = Float.parseFloat(args[1]);
      threshHigh = Float.parseFloat(args[2]);

      filename = args[3];
      if (args.length == 5) {
        dir = args[4];
      }
    } else {

      filename = args[0];
      if (args.length == 2) {
        dir = args[1];
      }
    }
    // get path to directory file is in
    String name = FilenameUtils.removeExtension(filename);

    // get image
    BufferedImage image = UtilImageIO.loadImage(new File(filename).getAbsolutePath());
    if (image == null) {
      System.out.println(
          "usage: crop-objects [OPTION]... FILE [DIR]\n"
              + "crops detected objects from image FILE and writes their subimages to files. \n"
              + "Can specify the DIR in which to create the files, otherwise subimage files are "
              + "created in the same directory as FILE is in by default. \n"
              + "-t [n] [m] 		set the high and low threshold values. n and m are values between 0 and 1.");
      System.exit(1);
    }

    minsize = (int) (0.1 * Math.min(image.getHeight(), image.getWidth()));

    // find objects in image
    // generate candidate contours

    ArrayList<List<PointIndex_I32>> objects = new ArrayList<List<PointIndex_I32>>();
    List<BufferedImage> results = new ArrayList<BufferedImage>();

    List<List<PointIndex_I32>> candidates = new ArrayList<List<PointIndex_I32>>();

    ImageFloat32 input = ConvertBufferedImage.convertFromSingle(image, null, ImageFloat32.class);

    BufferedImage bw =
        ConvertBufferedImage.convertTo(
            input, new BufferedImage(image.getWidth(), image.getHeight(), image.getType()));
    File binaryfile = new File(name + "_" + "binary.png");
    ImageIO.write(bw, "png", binaryfile);

    ImageUInt8 binary = new ImageUInt8(input.width, input.height);

    // Finds edges inside the image
    CannyEdge<ImageFloat32, ImageFloat32> canny =
        FactoryEdgeDetectors.canny(
            blurRadius, true, dynamicThreshold, ImageFloat32.class, ImageFloat32.class);

    canny.process(input, threshLow, threshHigh, binary);

    List<Contour> contours = BinaryImageOps.contour(binary, rule, null);

    BufferedImage visualBinary = VisualizeBinaryData.renderBinary(binary, null);
    File cannyfile = new File(name + "_" + "canny.png");
    ImageIO.write(visualBinary, "png", cannyfile);

    BufferedImage cannyContour =
        VisualizeBinaryData.renderExternal(contours, null, binary.width, binary.height, null);
    File cannyContourfile = new File(name + "_" + "contour.png");
    ImageIO.write(cannyContour, "png", cannyContourfile);

    for (Contour c : contours) {
      // Only the external contours are relevant.
      List<PointIndex_I32> vertices =
          ShapeFittingOps.fitPolygon(c.external, true, toleranceDist, toleranceAngle, 100);
      candidates.add(vertices);
    }

    for (List<PointIndex_I32> vertices : candidates) {
      try {
        Candidate c = new Candidate(vertices, image);
        if (c.size(minsize)) {
          c.rotate();
          results.add(c.getImage());
          objects.add(vertices);
        }
      } catch (Exception e) {
        System.out.println("Error creating candidate from contour " + e.getMessage());
      }
    }

    // write subimages of objects to files
    int i = 0;
    for (BufferedImage obj : results) {
      // print images to file
      try {
        File outputfile = new File(name + "_" + i + ".png");
        i++;
        ImageIO.write(obj, "png", outputfile);
      } catch (IOException e) {
        System.out.println("Error writing subimages" + e.getMessage());
      }
    }

    // draw objects onto original image and save
    Draw.drawPolygons(objects, image);
    File outputfile = new File(name + "_" + "annotated.png");
    ImageIO.write(image, "png", outputfile);
  }
 public void evaluate(Candidate candidate) {
   CaseInsensitiveTestCase ci = (CaseInsensitiveTestCase) candidate.getObject();
   candidate.include(ci.name.toLowerCase().equals(name.toLowerCase()));
 }