Example usage for java.util HashSet toArray

List of usage examples for java.util HashSet toArray

Introduction

In this page you can find the example usage for java.util HashSet toArray.

Prototype

<T> T[] toArray(T[] a);

Source Link

Document

Returns an array containing all of the elements in this set; the runtime type of the returned array is that of the specified array.

Usage

From source file:controller.VisLP.java

private static Point2D[] getFeasibleIntersections(FieldMatrix<BigFraction> cons) {
    FieldMatrix<BigFraction> N = cons.getSubMatrix(0, cons.getRowDimension() - 1, 0,
            cons.getColumnDimension() - 2);
    FieldVector<BigFraction> b = cons.getColumnVector(cons.getColumnDimension() - 1);

    HashSet<Point2D> points = new HashSet<Point2D>();
    unb = new ArrayList<Point2D>();

    /* Find all intersections */
    for (int i = 0; i < N.getRowDimension(); i++) {
        for (int j = 0; j < N.getRowDimension(); j++) {
            if (i == j)
                continue;

            FieldMatrix<BigFraction> line1 = N.getRowMatrix(i);
            FieldMatrix<BigFraction> line2 = N.getRowMatrix(j);

            BigFraction[] bval = new BigFraction[] { b.getEntry(i), b.getEntry(j) };
            FieldVector<BigFraction> bsys = new ArrayFieldVector<BigFraction>(bval);
            FieldMatrix<BigFraction> sys = LP.addBlock(line1, line2, LP.UNDER);

            try {
                FieldVector<BigFraction> point = new FieldLUDecomposition<BigFraction>(sys).getSolver()
                        .getInverse().operate(bsys);
                double x = point.getEntry(0).doubleValue();
                double y = point.getEntry(1).doubleValue();
                Point2D p2d = new Point2D.Double(x, y);

                /* Only add feasible points */
                if (feasible(p2d, N, b)) {
                    if (i >= N.getRowDimension() - 1)
                        unb.add(p2d);/*from www  .j a  va  2s  .  com*/
                    points.add(p2d);
                }
            } catch (IllegalArgumentException e) {
                /* 
                 * Two lines that don't intersect forms an invertible
                 * matrix. Skip these points.
                 */
            }
        }
    }
    return points.toArray(new Point2D[0]);
}

From source file:com.ryan.ryanreader.fragments.CommentListingFragment.java

@Override
public boolean onContextItemSelected(MenuItem item) {

    final AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();

    if (info.position <= 0)
        return false;

    final Action action = Action.values()[item.getItemId()];
    final RedditPreparedComment comment = (RedditPreparedComment) lv.getAdapter().getItem(info.position);

    switch (action) {

    case UPVOTE://from w  ww .j a va 2 s. c  om
        comment.action(getSupportActivity(), RedditAPI.RedditAction.UPVOTE);
        break;

    case DOWNVOTE:
        comment.action(getSupportActivity(), RedditAPI.RedditAction.DOWNVOTE);
        break;

    case UNVOTE:
        comment.action(getSupportActivity(), RedditAPI.RedditAction.UNVOTE);
        break;

    case REPORT:

        new AlertDialog.Builder(getSupportActivity()).setTitle(R.string.action_report)
                .setMessage(R.string.action_report_sure)
                .setPositiveButton(R.string.action_report, new DialogInterface.OnClickListener() {
                    public void onClick(final DialogInterface dialog, final int which) {
                        comment.action(getSupportActivity(), RedditAPI.RedditAction.REPORT);
                        // TODO update the view to show the result
                    }
                }).setNegativeButton(R.string.dialog_cancel, null).show();

        break;

    case REPLY: {
        final Intent intent = new Intent(getSupportActivity(), CommentReplyActivity.class);
        intent.putExtra("parentIdAndType", comment.idAndType);
        startActivity(intent);
        break;
    }

    case EDIT: {
        final Intent intent = new Intent(getSupportActivity(), CommentEditActivity.class);
        intent.putExtra("commentIdAndType", comment.idAndType);
        intent.putExtra("commentText", comment.src.body);
        startActivity(intent);
        break;
    }

    case COMMENT_LINKS:
        final HashSet<String> linksInComment = comment.computeAllLinks();

        if (linksInComment.isEmpty()) {
            General.quickToast(getSupportActivity(), R.string.error_toast_no_urls_in_comment);

        } else {

            final String[] linksArr = linksInComment.toArray(new String[linksInComment.size()]);

            final AlertDialog.Builder builder = new AlertDialog.Builder(getSupportActivity());
            builder.setItems(linksArr, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    LinkHandler.onLinkClicked(getSupportActivity(), linksArr[which], false);
                    dialog.dismiss();
                }
            });

            final AlertDialog alert = builder.create();
            alert.setTitle(R.string.action_comment_links);
            alert.setCanceledOnTouchOutside(true);
            alert.show();
        }

        break;

    case SHARE:

        final Intent mailer = new Intent(Intent.ACTION_SEND);
        mailer.setType("text/plain");
        mailer.putExtra(Intent.EXTRA_SUBJECT, "Comment by " + comment.src.author + " on Reddit");

        // TODO this currently just dumps the markdown
        mailer.putExtra(Intent.EXTRA_TEXT, StringEscapeUtils.unescapeHtml4(comment.src.body));
        startActivityForResult(Intent.createChooser(mailer, context.getString(R.string.action_share)), 1);

        break;

    case COPY:

        ClipboardManager manager = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
        // TODO this currently just dumps the markdown
        manager.setText(StringEscapeUtils.unescapeHtml4(comment.src.body));
        break;

    case COLLAPSE:
        if (comment.getBoundView() != null)
            handleCommentVisibilityToggle(comment.getBoundView());
        break;

    case USER_PROFILE:
        UserProfileDialog.newInstance(comment.src.author).show(getSupportActivity());
        break;

    case PROPERTIES:
        CommentPropertiesDialog.newInstance(comment.src).show(getSupportActivity());
        break;

    }

    return true;
}

From source file:org.lol.reddit.fragments.CommentListingFragment.java

@Override
public boolean onContextItemSelected(MenuItem item) {

    final AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();

    if (info.position <= 0) {
        return false;
    }/*from ww  w .  j a  v  a  2s  . c o m*/

    final Object selectedObject = lv.getAdapter().getItem(info.position);

    if (!(selectedObject instanceof RedditCommentListItem)
            || !((RedditCommentListItem) selectedObject).isComment()) {
        return false;
    }

    final Action action = Action.values()[item.getItemId()];
    final RedditPreparedComment comment = ((RedditCommentListItem) selectedObject).asComment();

    switch (action) {

    case UPVOTE:
        comment.action(getSupportActivity(), RedditAPI.RedditAction.UPVOTE);
        break;

    case DOWNVOTE:
        comment.action(getSupportActivity(), RedditAPI.RedditAction.DOWNVOTE);
        break;

    case UNVOTE:
        comment.action(getSupportActivity(), RedditAPI.RedditAction.UNVOTE);
        break;

    case SAVE:
        comment.action(getSupportActivity(), RedditAPI.RedditAction.SAVE);
        break;

    case UNSAVE:
        comment.action(getSupportActivity(), RedditAPI.RedditAction.UNSAVE);
        break;

    case REPORT:

        new AlertDialog.Builder(getSupportActivity()).setTitle(R.string.action_report)
                .setMessage(R.string.action_report_sure)
                .setPositiveButton(R.string.action_report, new DialogInterface.OnClickListener() {
                    public void onClick(final DialogInterface dialog, final int which) {
                        comment.action(getSupportActivity(), RedditAPI.RedditAction.REPORT);
                    }
                }).setNegativeButton(R.string.dialog_cancel, null).show();

        break;

    case REPLY: {
        final Intent intent = new Intent(getSupportActivity(), CommentReplyActivity.class);
        intent.putExtra("parentIdAndType", comment.idAndType);
        startActivity(intent);
        break;
    }

    case EDIT: {
        final Intent intent = new Intent(getSupportActivity(), CommentEditActivity.class);
        intent.putExtra("commentIdAndType", comment.idAndType);
        intent.putExtra("commentText", StringEscapeUtils.unescapeHtml4(comment.src.body));
        startActivity(intent);
        break;
    }

    case COMMENT_LINKS:
        final HashSet<String> linksInComment = comment.computeAllLinks();

        if (linksInComment.isEmpty()) {
            General.quickToast(getSupportActivity(), R.string.error_toast_no_urls_in_comment);

        } else {

            final String[] linksArr = linksInComment.toArray(new String[linksInComment.size()]);

            final AlertDialog.Builder builder = new AlertDialog.Builder(getSupportActivity());
            builder.setItems(linksArr, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    LinkHandler.onLinkClicked(getSupportActivity(), linksArr[which], false);
                    dialog.dismiss();
                }
            });

            final AlertDialog alert = builder.create();
            alert.setTitle(R.string.action_comment_links);
            alert.setCanceledOnTouchOutside(true);
            alert.show();
        }

        break;

    case SHARE:

        final Intent mailer = new Intent(Intent.ACTION_SEND);
        mailer.setType("text/plain");
        mailer.putExtra(Intent.EXTRA_SUBJECT, "Comment by " + comment.src.author + " on Reddit");

        // TODO this currently just dumps the markdown
        mailer.putExtra(Intent.EXTRA_TEXT, StringEscapeUtils.unescapeHtml4(comment.src.body));
        startActivityForResult(
                Intent.createChooser(mailer, getSupportActivity().getString(R.string.action_share)), 1);

        break;

    case COPY:

        ClipboardManager manager = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
        // TODO this currently just dumps the markdown
        manager.setText(StringEscapeUtils.unescapeHtml4(comment.src.body));
        break;

    case COLLAPSE:
        if (comment.getBoundView() != null) {
            handleCommentVisibilityToggle(comment.getBoundView());
        } else {
            General.quickToast(getSupportActivity(), "Error: Comment is no longer visible.");
        }
        break;

    case USER_PROFILE:
        LinkHandler.onLinkClicked(getSupportActivity(), new UserProfileURL(comment.src.author).toString());
        break;

    case PROPERTIES:
        CommentPropertiesDialog.newInstance(comment.src).show(getSupportActivity());
        break;

    case GO_TO_COMMENT: {
        PostCommentListingURL url = new PostCommentListingURL(null, comment.src.link_id, comment.idAlone, null,
                null, null);
        LinkHandler.onLinkClicked(getSupportActivity(), url.toString());
        break;
    }

    case CONTEXT: {
        PostCommentListingURL url = new PostCommentListingURL(null, comment.src.link_id, comment.idAlone, 3,
                null, null);
        LinkHandler.onLinkClicked(getSupportActivity(), url.toString());
        break;
    }
    }

    return true;
}

From source file:de.uni_koblenz.jgralab.utilities.csv2tg.Csv2Tg.java

private String[] getFilesInFolder(String[] filenames) {
    HashSet<String> fileList = new HashSet<>();
    for (String filename : filenames) {

        File file = new File(filename).getAbsoluteFile();
        if (!file.exists()) {
            throw new RuntimeException("File or folder \"" + filename + "\" does not exist!");
        }//from   www . ja v a  2s .c  o m
        if (file.isDirectory()) {
            for (File foundFile : file.listFiles(this)) {
                fileList.add(foundFile.getAbsolutePath());
            }
        } else {
            fileList.add(file.getAbsolutePath());
        }
    }

    if (fileList.isEmpty()) {
        throw new RuntimeException("No csv-files to convert to a tg-file.");
    }

    String[] result = new String[fileList.size()];
    return fileList.toArray(result);
}

From source file:org.owasp.jbrofuzz.core.Database.java

/**
 * <p>Return all the unique categories found across prototypes that are loaded
 * into the database.</p>//from  w  ww  .  j a v a 2s.  co  m
 * 
 * <p>Category examples include: "Replacive Fuzzers", "Exploits", etc.</p>
 * 
 * @return String[] uniqueCategories
 * 
 * @author subere@uncon.org
 * @version 1.5
 * @since 1.2
 */
public String[] getAllCategories() {

    final HashSet<String> o = new HashSet<String>();

    final String[] ids = getAllPrototypeIDs();
    for (final String id : ids) {

        final List<String> catArrayList = prototypes.get(id).getCategories();
        final String[] categoriesArray = new String[catArrayList.size()];
        catArrayList.toArray(categoriesArray);

        for (final String cCategory : categoriesArray) {

            o.add(cCategory);

        }

    }

    final String[] uCategoriesArray = new String[o.size()];
    o.toArray(uCategoriesArray);

    return uCategoriesArray;

}

From source file:tilt.image.page.Page.java

/**
 * Work out the median word-gap and median line-depth
 * @param wr the raster of the twotone or cleaned image
 *///  w  w  w. ja v a  2  s  .  c  o m
public void finalise(WritableRaster wr) {
    // compute median line depth
    HashSet<Integer> vGaps = new HashSet<>();
    int totalWidth = (lines.size() > 0) ? lines.get(0).getWidth() : 0;
    int totalLineDepth = 0;
    for (int i = 0; i < lines.size() - 1; i++) {
        Line l1 = lines.get(i);
        Line l2 = lines.get(i + 1);
        vGaps.add(Math.abs(l2.getAverageY() - l1.getAverageY()));
        totalWidth += l2.getWidth();
        totalLineDepth += l2.getMedianY() - l1.getMedianY();
    }
    Integer[] vArray = new Integer[vGaps.size()];
    vGaps.toArray(vArray);
    Arrays.sort(vArray);
    medianLineDepth = (vArray.length <= 1) ? 0 : vArray[vArray.length / 2].intValue();
    averageLineWidth = totalWidth / lines.size();
    averageLineDepth = totalLineDepth / (lines.size() - 1);
    joinBrokenLines();
}

From source file:org.strasa.middleware.manager.CreateFieldBookManagerImpl.java

/**
 * Generate variate.//from  ww w .ja v a2  s .  c  o  m
 * 
 * @param sheet
 *            the sheet
 * @param lstSiteInfo
 *            the lst site info
 * @throws CreateFieldBookException
 *             the create field book exception
 * @throws Exception
 *             the exception
 */
public void generateVariate(Sheet sheet, List<SiteInformationModel> lstSiteInfo)
        throws CreateFieldBookException, Exception {

    HashSet<String> lstSet = new HashSet<String>();
    for (SiteInformationModel siteInfo : lstSiteInfo) {
        for (StudyVariable var : siteInfo.lstStudyVariable) {
            lstSet.add(var.getVariablecode());
        }
    }

    List<StudyVariable> lstVar = new StudyVariableManagerImpl()
            .getVariateVariable(Arrays.asList(lstSet.toArray(new String[lstSet.size()])));

    int col = sheet.getLastRowNum() + 2;
    writeRowFromList(
            new ArrayList<String>(Arrays.asList("VARIATE", "DESCRIPTION", "PROPERTY", "SCALE", "METHOD",
                    "DATATYPE", "       ")),
            sheet, col++,
            formatCell(IndexedColors.VIOLET.getIndex(), IndexedColors.WHITE.getIndex(), (short) 200, true));
    for (StudyVariable variable : lstVar) {
        writeRowFromList(new ArrayList<String>(
                Arrays.asList(variable.getVariablecode(), variable.getDescription(), variable.getProperty(),
                        variable.getScale(), variable.getMethod(), variable.getDatatype(), "    ")),
                sheet, col++, null);

    }
}

From source file:org.apache.accumulo.server.init.Initialize.java

private static void addVolumes(VolumeManager fs) throws IOException {

    String[] volumeURIs = VolumeConfiguration.getVolumeUris(SiteConfiguration.getInstance());

    HashSet<String> initializedDirs = new HashSet<String>();
    initializedDirs.addAll(Arrays.asList(ServerConstants.checkBaseUris(volumeURIs, true)));

    HashSet<String> uinitializedDirs = new HashSet<String>();
    uinitializedDirs.addAll(Arrays.asList(volumeURIs));
    uinitializedDirs.removeAll(initializedDirs);

    Path aBasePath = new Path(initializedDirs.iterator().next());
    Path iidPath = new Path(aBasePath, ServerConstants.INSTANCE_ID_DIR);
    Path versionPath = new Path(aBasePath, ServerConstants.VERSION_DIR);

    UUID uuid = UUID.fromString(ZooUtil.getInstanceIDFromHdfs(iidPath, SiteConfiguration.getInstance()));
    for (Pair<Path, Path> replacementVolume : ServerConstants.getVolumeReplacements()) {
        if (aBasePath.equals(replacementVolume.getFirst()))
            log.error(aBasePath + " is set to be replaced in " + Property.INSTANCE_VOLUMES_REPLACEMENTS
                    + " and should not appear in " + Property.INSTANCE_VOLUMES
                    + ". It is highly recommended that this property be removed as data could still be written to this volume.");
    }/* w ww.java  2s.  c  o m*/

    if (ServerConstants.DATA_VERSION != Accumulo.getAccumuloPersistentVersion(
            versionPath.getFileSystem(CachedConfiguration.getInstance()), versionPath)) {
        throw new IOException("Accumulo " + Constants.VERSION + " cannot initialize data version "
                + Accumulo.getAccumuloPersistentVersion(fs));
    }

    initDirs(fs, uuid, uinitializedDirs.toArray(new String[uinitializedDirs.size()]), true);
}

From source file:net.lightbody.bmp.proxy.jetty.jetty.servlet.ServletHandler.java

/** Get Servlets.
 * @return Array of defined servlets/*  w  w w.ja  v a2s .com*/
 */
public ServletHolder[] getServlets() {
    // Sort and Initialize servlets
    HashSet holder_set = new HashSet(_nameMap.size());
    holder_set.addAll(_nameMap.values());
    ServletHolder holders[] = (ServletHolder[]) holder_set.toArray(new ServletHolder[holder_set.size()]);
    java.util.Arrays.sort(holders);
    return holders;
}

From source file:org.wso2.carbon.device.mgt.jaxrs.service.impl.RoleManagementServiceImpl.java

@POST
@Path("/create-combined-role/{roleName}")
@Override/*from www  . j a v  a2s . c  om*/
public Response addCombinedRole(List<String> roles, @PathParam("roleName") String roleName,
        @QueryParam("user-store") String userStoreName) {
    if (userStoreName != null && !userStoreName.isEmpty()) {
        roleName = userStoreName + "/" + roleName;
    }
    if (roles.size() < 2) {
        return Response.status(400).entity(new ErrorResponse.ErrorResponseBuilder()
                .setMessage("Combining Roles requires at least two roles.").build()).build();
    }
    for (String role : roles) {
        RequestValidationUtil.validateRoleName(role);
    }
    try {
        UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
        if (log.isDebugEnabled()) {
            log.debug("Persisting the role in the underlying user store");
        }

        HashSet<Permission> permsSet = new HashSet<>();
        try {
            for (String role : roles) {
                mergePermissions(new UIPermissionNode[] { getRolePermissions(role) }, permsSet);
            }
        } catch (IllegalArgumentException e) {
            return Response.status(404)
                    .entity(new ErrorResponse.ErrorResponseBuilder().setMessage(e.getMessage()).build())
                    .build();
        }

        Permission[] permissions = permsSet.toArray(new Permission[permsSet.size()]);
        userStoreManager.addRole(roleName, new String[0], permissions);

        //TODO fix what's returned in the entity
        return Response.created(new URI(API_BASE_PATH + "/" + URLEncoder.encode(roleName, "UTF-8")))
                .entity("Role '" + roleName + "' has " + "successfully been" + " added").build();
    } catch (UserAdminException e) {
        String msg = "Error occurred while retrieving the permissions of role '" + roleName + "'";
        log.error(msg, e);
        return Response.serverError().entity(new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build())
                .build();
    } catch (UserStoreException e) {
        String msg = "Error occurred while adding role '" + roleName + "'";
        log.error(msg, e);
        return Response.serverError().entity(new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build())
                .build();
    } catch (URISyntaxException e) {
        String msg = "Error occurred while composing the URI at which the information of the newly created role "
                + "can be retrieved";
        log.error(msg, e);
        return Response.serverError().entity(new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build())
                .build();
    } catch (UnsupportedEncodingException e) {
        String msg = "Error occurred while encoding role name";
        log.error(msg, e);
        return Response.serverError().entity(new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build())
                .build();
    }
}