Example usage for java.lang Float MAX_VALUE

List of usage examples for java.lang Float MAX_VALUE

Introduction

In this page you can find the example usage for java.lang Float MAX_VALUE.

Prototype

float MAX_VALUE

To view the source code for java.lang Float MAX_VALUE.

Click Source Link

Document

A constant holding the largest positive finite value of type float , (2-2-23)·2127.

Usage

From source file:edu.ku.brc.af.ui.forms.formatters.UIFieldFormatterMgr.java

/**
 * Constructs a the fields for a numeric formatter.
 * //  w w w. j  a v a 2  s  .c  o  m
 * @param formatter the formatter to be augmented
 */
protected void addFieldsForNumeric(final UIFieldFormatter formatter) {
    int len;
    Class<?> cls = formatter.getDataClass();
    if (cls == BigDecimal.class) {
        len = formatter.getPrecision() + formatter.getScale() + 1;
    } else {
        if (cls == Long.class) {
            len = Long.toString(Long.MAX_VALUE).length();
        } else if (cls == Integer.class) {
            len = Integer.toString(Integer.MAX_VALUE).length();
        } else if (cls == Short.class) {
            len = Short.toString(Short.MAX_VALUE).length();
        } else if (cls == Byte.class) {
            len = Byte.toString(Byte.MAX_VALUE).length();
        } else if (cls == Double.class) {
            len = String.format("%f", Double.MAX_VALUE).length();
        } else if (cls == Float.class) {
            len = String.format("%f", Float.MAX_VALUE).length();

        } else {
            len = formatter.getLength();
            //throw new RuntimeException("Missing case for numeric class ["+ cls.getName() + "]");
        }
        len = Math.min(len, 10);
    }
    StringBuilder sb = new StringBuilder(len);
    for (int i = 0; i < len; i++) {
        sb.append(' ');
    }
    formatter.getFields()
            .add(new UIFieldFormatterField(UIFieldFormatterField.FieldType.numeric, len, sb.toString(), false));
}

From source file:javadz.beanutils.MethodUtils.java

/**
 * <p>Find an accessible method that matches the given name and has compatible parameters.
 * Compatible parameters mean that every method parameter is assignable from 
 * the given parameters.//  www .  j av  a2  s. c o m
 * In other words, it finds a method with the given name 
 * that will take the parameters given.<p>
 *
 * <p>This method is slightly undeterminstic since it loops 
 * through methods names and return the first matching method.</p>
 * 
 * <p>This method is used by 
 * {@link 
 * #invokeMethod(Object object,String methodName,Object [] args,Class[] parameterTypes)}.
 *
 * <p>This method can match primitive parameter by passing in wrapper classes.
 * For example, a <code>Boolean</code> will match a primitive <code>boolean</code>
 * parameter.
 *
 * @param clazz find method in this class
 * @param methodName find method with this name
 * @param parameterTypes find method with compatible parameters 
 * @return The accessible method
 */
public static Method getMatchingAccessibleMethod(Class clazz, String methodName, Class[] parameterTypes) {
    // trace logging
    Log log = LogFactory.getLog(MethodUtils.class);
    if (log.isTraceEnabled()) {
        log.trace("Matching name=" + methodName + " on " + clazz);
    }
    MethodDescriptor md = new MethodDescriptor(clazz, methodName, parameterTypes, false);

    // see if we can find the method directly
    // most of the time this works and it's much faster
    try {
        // Check the cache first
        Method method = getCachedMethod(md);
        if (method != null) {
            return method;
        }

        method = clazz.getMethod(methodName, parameterTypes);
        if (log.isTraceEnabled()) {
            log.trace("Found straight match: " + method);
            log.trace("isPublic:" + Modifier.isPublic(method.getModifiers()));
        }

        setMethodAccessible(method); // Default access superclass workaround

        cacheMethod(md, method);
        return method;

    } catch (NoSuchMethodException e) {
        /* SWALLOW */ }

    // search through all methods 
    int paramSize = parameterTypes.length;
    Method bestMatch = null;
    Method[] methods = clazz.getMethods();
    float bestMatchCost = Float.MAX_VALUE;
    float myCost = Float.MAX_VALUE;
    for (int i = 0, size = methods.length; i < size; i++) {
        if (methods[i].getName().equals(methodName)) {
            // log some trace information
            if (log.isTraceEnabled()) {
                log.trace("Found matching name:");
                log.trace(methods[i]);
            }

            // compare parameters
            Class[] methodsParams = methods[i].getParameterTypes();
            int methodParamSize = methodsParams.length;
            if (methodParamSize == paramSize) {
                boolean match = true;
                for (int n = 0; n < methodParamSize; n++) {
                    if (log.isTraceEnabled()) {
                        log.trace("Param=" + parameterTypes[n].getName());
                        log.trace("Method=" + methodsParams[n].getName());
                    }
                    if (!isAssignmentCompatible(methodsParams[n], parameterTypes[n])) {
                        if (log.isTraceEnabled()) {
                            log.trace(methodsParams[n] + " is not assignable from " + parameterTypes[n]);
                        }
                        match = false;
                        break;
                    }
                }

                if (match) {
                    // get accessible version of method
                    Method method = getAccessibleMethod(clazz, methods[i]);
                    if (method != null) {
                        if (log.isTraceEnabled()) {
                            log.trace(method + " accessible version of " + methods[i]);
                        }
                        setMethodAccessible(method); // Default access superclass workaround
                        myCost = getTotalTransformationCost(parameterTypes, method.getParameterTypes());
                        if (myCost < bestMatchCost) {
                            bestMatch = method;
                            bestMatchCost = myCost;
                        }
                    }

                    log.trace("Couldn't find accessible method.");
                }
            }
        }
    }
    if (bestMatch != null) {
        cacheMethod(md, bestMatch);
    } else {
        // didn't find a match
        log.trace("No match found.");
    }

    return bestMatch;
}

From source file:org.apache.poi.util.MethodUtils.java

public static <T> Constructor<T> getMatchingAccessibleConstructor(Class<T> clazz, Class[] parameterTypes) {
    // trace logging
    Log log = LogFactory.getLog(MethodUtils.class);
    MethodDescriptor md = new MethodDescriptor(clazz, "dummy", parameterTypes, false);

    // see if we can find the method directly
    // most of the time this works and it's much faster
    try {//from  w  w w  . j  a v  a  2s .c om
        Constructor<T> constructor = clazz.getConstructor(parameterTypes);
        if (log.isTraceEnabled()) {
            log.trace("Found straight match: " + constructor);
            log.trace("isPublic:" + Modifier.isPublic(constructor.getModifiers()));
        }

        setMethodAccessible(constructor); // Default access superclass workaround

        return constructor;

    } catch (NoSuchMethodException e) {
        /* SWALLOW */ }

    // search through all methods 
    int paramSize = parameterTypes.length;
    Constructor<T> bestMatch = null;
    Constructor<?>[] constructors = clazz.getConstructors();
    float bestMatchCost = Float.MAX_VALUE;
    float myCost = Float.MAX_VALUE;
    for (int i = 0, size = constructors.length; i < size; i++) {
        // compare parameters
        Class[] methodsParams = constructors[i].getParameterTypes();
        int methodParamSize = methodsParams.length;
        if (methodParamSize == paramSize) {
            boolean match = true;
            for (int n = 0; n < methodParamSize; n++) {
                if (log.isTraceEnabled()) {
                    log.trace("Param=" + parameterTypes[n].getName());
                    log.trace("Method=" + methodsParams[n].getName());
                }
                if (!isAssignmentCompatible(methodsParams[n], parameterTypes[n])) {
                    if (log.isTraceEnabled()) {
                        log.trace(methodsParams[n] + " is not assignable from " + parameterTypes[n]);
                    }
                    match = false;
                    break;
                }
            }

            if (match) {
                // get accessible version of method
                Constructor<T> cons = (Constructor<T>) constructors[i];
                myCost = getTotalTransformationCost(parameterTypes, cons.getParameterTypes());
                if (myCost < bestMatchCost) {
                    bestMatch = cons;
                    bestMatchCost = myCost;
                }
            }
        }
    }
    if (bestMatch == null) {
        // didn't find a match
        log.trace("No match found.");
    }

    return bestMatch;
}

From source file:SIFT_Volume_Stitching.java

/**
  Compute the best 2D model between two substacks
  @param front substack/*from   w  ww .  j a  va  2 s  .  c o  m*/
  @param back substack
  @param sift object with parameters set as detailled in run method
  @param MIP size
  @return computed model
 */
public AbstractAffineModel2D<?> CompareCrossSection(ImageStack subStack1, ImageStack subStack2, SIFT ijSIFT,
        int MIP) {
    /* Sauvegarde des Substacks */
    ImageStack frontCOPY = subStack1.duplicate();
    ImageStack backCOPY = subStack2.duplicate();

    /* Construction des MIP */
    if (MIP > 1) {
        int step = MIP;

        if (MIP > subStack1.getSize()) {
            step = subStack1.getSize();
        }
        subStack1 = createMIP(subStack1, step);
        subStack2 = createMIP(subStack2, step);
    }

    /* Parameters Initialisation */
    ImageProcessor ip2;
    ImageProcessor ip1;

    fsf.clear();
    fsb.clear();

    int taille = subStack2.getSize();
    IJ.log("taille " + taille + " and size of stacks, 1= " + subStack1.getSize() + " 2= "
            + subStack2.getSize());
    /* Comparisons of cross-section simultaneously */
    for (int i = 1; i <= taille; ++i) {
        ip1 = subStack1.getProcessor(i);
        ijSIFT.extractFeatures(ip1, fsf);

        ip2 = subStack2.getProcessor(i);
        ijSIFT.extractFeatures(ip2, fsb);
    }

    /* Candidate computation */
    System.out.print("identifying correspondences using brute force ...");
    Vector<PointMatch> candidates = FloatArray2DSIFT.createMatches(fsb, fsf, 1.5f, null, Float.MAX_VALUE,
            p.rod);

    Vector<PointMatch> inliers = new Vector<PointMatch>();

    /* Model Computation */
    AbstractAffineModel2D<?> BestModel;
    switch (p.modelIndex) {
    case 0:
        BestModel = new TranslationModel2D();
        break;
    case 1:
        BestModel = new RigidModel2D();
        break;
    case 2:
        BestModel = new SimilarityModel2D();
        break;
    case 3:
        BestModel = new AffineModel2D();
        break;
    default:
        BestModel = new RigidModel2D();
    }

    try {
        modelFound = BestModel.filterRansac(candidates, inliers, 1000, p.maxEpsilon, p.minInlierRatio);
    } catch (Exception e) {
        modelFound = false;
        System.err.println(e.getMessage());
    }

    if (modelFound) {
        double[][] data = new double[2][3];
        BestModel.toMatrix(data);
        IJ.log("Rotation : " + Math.acos(data[0][0]) * (180 / Math.PI) + "");
        IJ.log("Horizontal Translation : " + data[0][2] + "pixels");
        IJ.log("Vertical Translation : " + data[1][1] + "pixels");

        ip1 = createMIP(frontCOPY, frontCOPY.getSize()).getProcessor(1);
        ip2 = createMIP(backCOPY, backCOPY.getSize()).getProcessor(1);
        displayFeatures(ip1, ip2, candidates, inliers, modelFound);

        IJ.log("(Info) Number of Matching Features : " + inliers.size());
    }

    return BestModel;
}

From source file:pipeline.misc_util.Utils.java

private static float[] minMaxSlidingWindow(float[][] numbers, float windowLength) {
    int windowStart = 0;

    float[] result = new float[numbers.length];
    int arrayIndex = 0;
    float globalMin = Float.MAX_VALUE;

    for (float[] number : numbers) {
        if (number[1] < globalMin)
            globalMin = number[1];//from  www .j a va 2  s.co m
    }

    while (arrayIndex < numbers.length - 1) {
        int effectiveEnd = windowStart;
        while ((numbers[effectiveEnd][0] - numbers[windowStart][0] < windowLength)
                && (effectiveEnd < numbers.length - 1))
            effectiveEnd++;

        float max = -Float.MAX_VALUE;
        float min = Float.MAX_VALUE;

        for (int i = windowStart; i < effectiveEnd; i++) {
            if (numbers[i][1] > max)
                max = numbers[i][1];
            if (numbers[i][1] < min)
                min = numbers[i][1];
        }

        if (min > globalMin)
            result[arrayIndex] = (max - min) / (min - globalMin);
        else
            result[arrayIndex] = Float.NaN;

        windowStart++;
        arrayIndex++;
    }

    return result;
}

From source file:com.farmerbb.taskbar.service.TaskbarService.java

@SuppressWarnings("Convert2streamapi")
@TargetApi(Build.VERSION_CODES.LOLLIPOP_MR1)
private void updateRecentApps(final boolean firstRefresh) {
    SharedPreferences pref = U.getSharedPreferences(this);
    final PackageManager pm = getPackageManager();
    final List<AppEntry> entries = new ArrayList<>();
    List<LauncherActivityInfo> launcherAppCache = new ArrayList<>();
    int maxNumOfEntries = U.getMaxNumOfEntries(this);
    int realNumOfPinnedApps = 0;
    boolean fullLength = pref.getBoolean("full_length", false);

    PinnedBlockedApps pba = PinnedBlockedApps.getInstance(this);
    List<AppEntry> pinnedApps = pba.getPinnedApps();
    List<AppEntry> blockedApps = pba.getBlockedApps();
    List<String> applicationIdsToRemove = new ArrayList<>();

    // Filter out anything on the pinned/blocked apps lists
    if (pinnedApps.size() > 0) {
        UserManager userManager = (UserManager) getSystemService(USER_SERVICE);
        LauncherApps launcherApps = (LauncherApps) getSystemService(LAUNCHER_APPS_SERVICE);

        for (AppEntry entry : pinnedApps) {
            boolean packageEnabled = launcherApps.isPackageEnabled(entry.getPackageName(),
                    userManager.getUserForSerialNumber(entry.getUserId(this)));

            if (packageEnabled)
                entries.add(entry);//from  w ww  .ja v  a2  s . com
            else
                realNumOfPinnedApps--;

            applicationIdsToRemove.add(entry.getPackageName());
        }

        realNumOfPinnedApps = realNumOfPinnedApps + pinnedApps.size();
    }

    if (blockedApps.size() > 0) {
        for (AppEntry entry : blockedApps) {
            applicationIdsToRemove.add(entry.getPackageName());
        }
    }

    // Get list of all recently used apps
    List<AppEntry> usageStatsList = realNumOfPinnedApps < maxNumOfEntries ? getAppEntries() : new ArrayList<>();
    if (usageStatsList.size() > 0 || realNumOfPinnedApps > 0 || fullLength) {
        if (realNumOfPinnedApps < maxNumOfEntries) {
            List<AppEntry> usageStatsList2 = new ArrayList<>();
            List<AppEntry> usageStatsList3 = new ArrayList<>();
            List<AppEntry> usageStatsList4 = new ArrayList<>();
            List<AppEntry> usageStatsList5 = new ArrayList<>();
            List<AppEntry> usageStatsList6;

            Intent homeIntent = new Intent(Intent.ACTION_MAIN);
            homeIntent.addCategory(Intent.CATEGORY_HOME);
            ResolveInfo defaultLauncher = pm.resolveActivity(homeIntent, PackageManager.MATCH_DEFAULT_ONLY);

            // Filter out apps without a launcher intent
            // Also filter out the current launcher, and Taskbar itself
            for (AppEntry packageInfo : usageStatsList) {
                if (hasLauncherIntent(packageInfo.getPackageName())
                        && !packageInfo.getPackageName().contains(BuildConfig.BASE_APPLICATION_ID)
                        && !packageInfo.getPackageName().equals(defaultLauncher.activityInfo.packageName))
                    usageStatsList2.add(packageInfo);
            }

            // Filter out apps that don't fall within our current search interval
            for (AppEntry stats : usageStatsList2) {
                if (stats.getLastTimeUsed() > searchInterval || runningAppsOnly)
                    usageStatsList3.add(stats);
            }

            // Sort apps by either most recently used, or most time used
            if (!runningAppsOnly) {
                if (sortOrder.contains("most_used")) {
                    Collections.sort(usageStatsList3, (us1, us2) -> Long.compare(us2.getTotalTimeInForeground(),
                            us1.getTotalTimeInForeground()));
                } else {
                    Collections.sort(usageStatsList3,
                            (us1, us2) -> Long.compare(us2.getLastTimeUsed(), us1.getLastTimeUsed()));
                }
            }

            // Filter out any duplicate entries
            List<String> applicationIds = new ArrayList<>();
            for (AppEntry stats : usageStatsList3) {
                if (!applicationIds.contains(stats.getPackageName())) {
                    usageStatsList4.add(stats);
                    applicationIds.add(stats.getPackageName());
                }
            }

            // Filter out the currently running foreground app, if requested by the user
            if (pref.getBoolean("hide_foreground", false)) {
                UsageStatsManager mUsageStatsManager = (UsageStatsManager) getSystemService(
                        USAGE_STATS_SERVICE);
                UsageEvents events = mUsageStatsManager.queryEvents(searchInterval, System.currentTimeMillis());
                UsageEvents.Event eventCache = new UsageEvents.Event();
                String currentForegroundApp = null;

                while (events.hasNextEvent()) {
                    events.getNextEvent(eventCache);

                    if (eventCache.getEventType() == UsageEvents.Event.MOVE_TO_FOREGROUND) {
                        if (!(eventCache.getPackageName().contains(BuildConfig.BASE_APPLICATION_ID)
                                && !eventCache.getClassName().equals(MainActivity.class.getCanonicalName())
                                && !eventCache.getClassName().equals(HomeActivity.class.getCanonicalName())
                                && !eventCache.getClassName()
                                        .equals(InvisibleActivityFreeform.class.getCanonicalName())))
                            currentForegroundApp = eventCache.getPackageName();
                    }
                }

                if (!applicationIdsToRemove.contains(currentForegroundApp))
                    applicationIdsToRemove.add(currentForegroundApp);
            }

            for (AppEntry stats : usageStatsList4) {
                if (!applicationIdsToRemove.contains(stats.getPackageName())) {
                    usageStatsList5.add(stats);
                }
            }

            // Truncate list to a maximum length
            if (usageStatsList5.size() > maxNumOfEntries)
                usageStatsList6 = usageStatsList5.subList(0, maxNumOfEntries);
            else
                usageStatsList6 = usageStatsList5;

            // Determine if we need to reverse the order
            boolean needToReverseOrder;
            switch (U.getTaskbarPosition(this)) {
            case "bottom_right":
            case "top_right":
                needToReverseOrder = sortOrder.contains("false");
                break;
            default:
                needToReverseOrder = sortOrder.contains("true");
                break;
            }

            if (needToReverseOrder) {
                Collections.reverse(usageStatsList6);
            }

            // Generate the AppEntries for TaskbarAdapter
            int number = usageStatsList6.size() == maxNumOfEntries
                    ? usageStatsList6.size() - realNumOfPinnedApps
                    : usageStatsList6.size();

            UserManager userManager = (UserManager) getSystemService(Context.USER_SERVICE);
            LauncherApps launcherApps = (LauncherApps) getSystemService(Context.LAUNCHER_APPS_SERVICE);

            final List<UserHandle> userHandles = userManager.getUserProfiles();

            for (int i = 0; i < number; i++) {
                for (UserHandle handle : userHandles) {
                    String packageName = usageStatsList6.get(i).getPackageName();
                    List<LauncherActivityInfo> list = launcherApps.getActivityList(packageName, handle);
                    if (!list.isEmpty()) {
                        // Google App workaround
                        if (!packageName.equals("com.google.android.googlequicksearchbox"))
                            launcherAppCache.add(list.get(0));
                        else {
                            boolean added = false;
                            for (LauncherActivityInfo info : list) {
                                if (info.getName()
                                        .equals("com.google.android.googlequicksearchbox.SearchActivity")) {
                                    launcherAppCache.add(info);
                                    added = true;
                                }
                            }

                            if (!added)
                                launcherAppCache.add(list.get(0));
                        }

                        AppEntry newEntry = new AppEntry(packageName, null, null, null, false);

                        newEntry.setUserId(userManager.getSerialNumberForUser(handle));
                        entries.add(newEntry);

                        break;
                    }
                }
            }
        }

        while (entries.size() > maxNumOfEntries) {
            try {
                entries.remove(entries.size() - 1);
                launcherAppCache.remove(launcherAppCache.size() - 1);
            } catch (ArrayIndexOutOfBoundsException e) {
                /* Gracefully fail */ }
        }

        // Determine if we need to reverse the order again
        if (U.getTaskbarPosition(this).contains("vertical")) {
            Collections.reverse(entries);
            Collections.reverse(launcherAppCache);
        }

        // Now that we've generated the list of apps,
        // we need to determine if we need to redraw the Taskbar or not
        boolean shouldRedrawTaskbar = firstRefresh;

        List<String> finalApplicationIds = new ArrayList<>();
        for (AppEntry entry : entries) {
            finalApplicationIds.add(entry.getPackageName());
        }

        if (finalApplicationIds.size() != currentTaskbarIds.size() || numOfPinnedApps != realNumOfPinnedApps)
            shouldRedrawTaskbar = true;
        else {
            for (int i = 0; i < finalApplicationIds.size(); i++) {
                if (!finalApplicationIds.get(i).equals(currentTaskbarIds.get(i))) {
                    shouldRedrawTaskbar = true;
                    break;
                }
            }
        }

        if (shouldRedrawTaskbar) {
            currentTaskbarIds = finalApplicationIds;
            numOfPinnedApps = realNumOfPinnedApps;

            UserManager userManager = (UserManager) getSystemService(USER_SERVICE);

            int launcherAppCachePos = -1;
            for (int i = 0; i < entries.size(); i++) {
                if (entries.get(i).getComponentName() == null) {
                    launcherAppCachePos++;
                    LauncherActivityInfo appInfo = launcherAppCache.get(launcherAppCachePos);
                    String packageName = entries.get(i).getPackageName();

                    entries.remove(i);

                    AppEntry newEntry = new AppEntry(packageName, appInfo.getComponentName().flattenToString(),
                            appInfo.getLabel().toString(), IconCache.getInstance(TaskbarService.this)
                                    .getIcon(TaskbarService.this, pm, appInfo),
                            false);

                    newEntry.setUserId(userManager.getSerialNumberForUser(appInfo.getUser()));
                    entries.add(i, newEntry);
                }
            }

            final int numOfEntries = Math.min(entries.size(), maxNumOfEntries);

            handler.post(() -> {
                if (numOfEntries > 0 || fullLength) {
                    ViewGroup.LayoutParams params = scrollView.getLayoutParams();
                    DisplayMetrics metrics = getResources().getDisplayMetrics();
                    int recentsSize = getResources().getDimensionPixelSize(R.dimen.icon_size) * numOfEntries;
                    float maxRecentsSize = fullLength ? Float.MAX_VALUE : recentsSize;

                    if (U.getTaskbarPosition(TaskbarService.this).contains("vertical")) {
                        int maxScreenSize = metrics.heightPixels - U.getStatusBarHeight(TaskbarService.this)
                                - U.getBaseTaskbarSize(TaskbarService.this);

                        params.height = (int) Math.min(maxRecentsSize, maxScreenSize)
                                + getResources().getDimensionPixelSize(R.dimen.divider_size);

                        if (fullLength && U.getTaskbarPosition(this).contains("bottom")) {
                            try {
                                Space whitespace = (Space) layout.findViewById(R.id.whitespace);
                                ViewGroup.LayoutParams params2 = whitespace.getLayoutParams();
                                params2.height = maxScreenSize - recentsSize;
                                whitespace.setLayoutParams(params2);
                            } catch (NullPointerException e) {
                                /* Gracefully fail */ }
                        }
                    } else {
                        int maxScreenSize = metrics.widthPixels - U.getBaseTaskbarSize(TaskbarService.this);

                        params.width = (int) Math.min(maxRecentsSize, maxScreenSize)
                                + getResources().getDimensionPixelSize(R.dimen.divider_size);

                        if (fullLength && U.getTaskbarPosition(this).contains("right")) {
                            try {
                                Space whitespace = (Space) layout.findViewById(R.id.whitespace);
                                ViewGroup.LayoutParams params2 = whitespace.getLayoutParams();
                                params2.width = maxScreenSize - recentsSize;
                                whitespace.setLayoutParams(params2);
                            } catch (NullPointerException e) {
                                /* Gracefully fail */ }
                        }
                    }

                    scrollView.setLayoutParams(params);

                    taskbar.removeAllViews();
                    for (int i = 0; i < entries.size(); i++) {
                        taskbar.addView(getView(entries, i));
                    }

                    isShowingRecents = true;
                    if (shouldRefreshRecents && scrollView.getVisibility() != View.VISIBLE) {
                        if (firstRefresh)
                            scrollView.setVisibility(View.INVISIBLE);
                        else
                            scrollView.setVisibility(View.VISIBLE);
                    }

                    if (firstRefresh && scrollView.getVisibility() != View.VISIBLE)
                        new Handler().post(() -> {
                            switch (U.getTaskbarPosition(TaskbarService.this)) {
                            case "bottom_left":
                            case "bottom_right":
                            case "top_left":
                            case "top_right":
                                if (sortOrder.contains("false"))
                                    scrollView.scrollTo(0, 0);
                                else if (sortOrder.contains("true"))
                                    scrollView.scrollTo(taskbar.getWidth(), taskbar.getHeight());
                                break;
                            case "bottom_vertical_left":
                            case "bottom_vertical_right":
                            case "top_vertical_left":
                            case "top_vertical_right":
                                if (sortOrder.contains("false"))
                                    scrollView.scrollTo(taskbar.getWidth(), taskbar.getHeight());
                                else if (sortOrder.contains("true"))
                                    scrollView.scrollTo(0, 0);
                                break;
                            }

                            if (shouldRefreshRecents) {
                                scrollView.setVisibility(View.VISIBLE);
                            }
                        });
                } else {
                    isShowingRecents = false;
                    scrollView.setVisibility(View.GONE);
                }
            });
        }
    } else if (firstRefresh || currentTaskbarIds.size() > 0) {
        currentTaskbarIds.clear();
        handler.post(() -> {
            isShowingRecents = false;
            scrollView.setVisibility(View.GONE);
        });
    }
}

From source file:org.fhcrc.cpl.viewer.ms2.commandline.PostProcessPepXMLCLM.java

/**
 *
 * @param featureFile/*from w ww  .j  a v a2 s.c  o  m*/
 * @param outputFile
 * @throws CommandLineModuleExecutionException
 */
protected void handleFeatureFile(File featureFile, File outputFile) throws CommandLineModuleExecutionException {
    ApplicationContext.infoMessage("Handling file " + featureFile.getAbsolutePath() + "...");

    if (maxFDR < Float.MAX_VALUE) {
        minPeptideProphet = (float) calcMinPeptideProphetForMaxFDR(featureFile);
        ApplicationContext.infoMessage("Minimum PeptideProphet for FDR " + maxFDR + ": " + minPeptideProphet);
    }

    try {
        Iterator<FeatureSet> featureSetIterator = new PepXMLFeatureFileHandler.PepXMLFeatureSetIterator(
                featureFile);

        List<File> tempFeatureFiles = new ArrayList<File>();
        int numSetsProcessed = 0;
        while (featureSetIterator.hasNext()) {
            FeatureSet featureSet = featureSetIterator.next();

            ApplicationContext.infoMessage("\tProcessing fraction " + (numSetsProcessed + 1) + "...");

            processFeatureSet(featureSet);
            String baseName = MS2ExtraInfoDef.getFeatureSetBaseName(featureSet);
            if (baseName == null) {
                baseName = featureFile.getName();
                if (numSetsProcessed > 0 || featureSetIterator.hasNext())
                    baseName = baseName + "_" + numSetsProcessed;
            }
            //if PeptideProphet was run from a directory below the directory containing the
            //mzXML files, we may have ../ in the baseName, which causes trouble in saving
            //the temporary files
            //                while (baseName.contains(".." + File.separator))
            //                    baseName.replaceFirst(".." + File.separator, "");
            if (baseName.contains(File.separator))
                baseName = baseName.substring(baseName.lastIndexOf(File.separator) + 1);

            File thisFractionFile = TempFileManager.createTempFile(baseName + ".pep.xml", this);

            featureSet.savePepXml(thisFractionFile);

            _log.debug("Saved fraction file as " + thisFractionFile.getAbsolutePath());
            tempFeatureFiles.add(thisFractionFile);

            numSetsProcessed++;
        }

        ApplicationContext.infoMessage("Saving output file " + outputFile.getAbsolutePath() + " ...");

        if (numSetsProcessed == 1) {
            FileReader in = new FileReader(tempFeatureFiles.get(0));
            FileWriter out = new FileWriter(outputFile);
            int c;

            while ((c = in.read()) != -1)
                out.write(c);

            in.close();
            out.close();
        } else {
            ApplicationContext.infoMessage(
                    "\tCombining individual fraction files... " + outputFile.getAbsolutePath() + "...");
            new PepXMLFeatureFileHandler().combinePepXmlFiles(tempFeatureFiles, outputFile);
        }
        ApplicationContext.infoMessage("Done.");
    } catch (IOException e) {
        throw new CommandLineModuleExecutionException(
                "Failed to process features from file " + featureFile.getAbsolutePath(), e);
    } finally {
        TempFileManager.deleteTempFiles(this);
    }
}

From source file:com.magnet.android.mms.controller.RequestPrimitiveTest.java

@SmallTest
public void testSingleListFloatPostParam() throws JSONException {
    ControllerHandler handler = new ControllerHandler();
    String methodName = "postFloats";
    JMethod method = new JMethod();
    JMeta metaInfo = new JMeta(methodName, API_METHOD_POST + methodName, POST);
    method.setMetaInfo(metaInfo);//  ww  w. ja  v a2s.  c o  m

    // int
    method.addParam("param0", PLAIN, List.class, Float.class, "", false);

    List<Float> values = new ArrayList<Float>();
    values.add(Float.MAX_VALUE);
    values.add(Float.MIN_NORMAL);

    String uriString = handler.buildUri(method, new Object[] { values });
    String bodyString = handler.buildRequestBodyString(method, new Object[] { values });

    String expected = API_METHOD_POST + methodName;
    logger.log(Level.INFO, "uriString=" + uriString);
    logger.log(Level.INFO, "bodyString=" + bodyString);
    assertEquals(expected, uriString);

    JSONArray jarray = new JSONArray(bodyString);
    int idx = 0;
    for (Float value : values) {
        String sf = jarray.getString(idx);
        float f = Float.parseFloat(sf);
        assertEquals(value, f);
        idx++;
    }
}

From source file:com.gome.ecmall.custom.VerticalViewPager.java

private void calculatePageOffsets(ItemInfo curItem, int curIndex, ItemInfo oldCurInfo) {
    final int N = mAdapter.getCount();
    final int height = getHeight();
    final float marginOffset = height > 0 ? (float) mPageMargin / height : 0;
    // Fix up offsets for later layout.
    if (oldCurInfo != null) {
        final int oldCurPosition = oldCurInfo.position;
        // Base offsets off of oldCurInfo.
        if (oldCurPosition < curItem.position) {
            int itemIndex = 0;
            ItemInfo ii = null;/*  w  w  w . j a v a2  s .  co  m*/
            float offset = oldCurInfo.offset + oldCurInfo.heightFactor + marginOffset;
            for (int pos = oldCurPosition + 1; pos <= curItem.position && itemIndex < mItems.size(); pos++) {
                ii = mItems.get(itemIndex);
                while (pos > ii.position && itemIndex < mItems.size() - 1) {
                    itemIndex++;
                    ii = mItems.get(itemIndex);
                }
                while (pos < ii.position) {
                    // We don't have an item populated for this,
                    // ask the adapter for an offset.
                    offset += mAdapter.getPageHeight(pos) + marginOffset;
                    pos++;
                }
                ii.offset = offset;
                offset += ii.heightFactor + marginOffset;
            }
        } else if (oldCurPosition > curItem.position) {
            int itemIndex = mItems.size() - 1;
            ItemInfo ii = null;
            float offset = oldCurInfo.offset;
            for (int pos = oldCurPosition - 1; pos >= curItem.position && itemIndex >= 0; pos--) {
                ii = mItems.get(itemIndex);
                while (pos < ii.position && itemIndex > 0) {
                    itemIndex--;
                    ii = mItems.get(itemIndex);
                }
                while (pos > ii.position) {
                    // We don't have an item populated for this,
                    // ask the adapter for an offset.
                    offset -= mAdapter.getPageHeight(pos) + marginOffset;
                    pos--;
                }
                offset -= ii.heightFactor + marginOffset;
                ii.offset = offset;
            }
        }
    }

    // Base all offsets off of curItem.
    final int itemCount = mItems.size();
    float offset = curItem.offset;
    int pos = curItem.position - 1;
    mFirstOffset = curItem.position == 0 ? curItem.offset : -Float.MAX_VALUE;
    mLastOffset = curItem.position == N - 1 ? curItem.offset + curItem.heightFactor - 1 : Float.MAX_VALUE;
    // Previous pages
    for (int i = curIndex - 1; i >= 0; i--, pos--) {
        final ItemInfo ii = mItems.get(i);
        while (pos > ii.position) {
            offset -= mAdapter.getPageHeight(pos--) + marginOffset;
        }
        offset -= ii.heightFactor + marginOffset;
        ii.offset = offset;
        if (ii.position == 0)
            mFirstOffset = offset;
    }
    offset = curItem.offset + curItem.heightFactor + marginOffset;
    pos = curItem.position + 1;
    // Next pages
    for (int i = curIndex + 1; i < itemCount; i++, pos++) {
        final ItemInfo ii = mItems.get(i);
        while (pos < ii.position) {
            offset += mAdapter.getPageHeight(pos++) + marginOffset;
        }
        if (ii.position == N - 1) {
            mLastOffset = offset + ii.heightFactor - 1;
        }
        ii.offset = offset;
        offset += ii.heightFactor + marginOffset;
    }

    mNeedCalculatePageOffsets = false;
}

From source file:eu.qualityontime.commons.MethodUtils.java

/**
 * <p>//from ww w.  j  av a2 s.co  m
 * Find an accessible method that matches the given name and has compatible
 * parameters. Compatible parameters mean that every method parameter is
 * assignable from the given parameters. In other words, it finds a method
 * with the given name that will take the parameters given.
 * </p>
 *
 * <p>
 * This method is slightly undeterministic since it loops through methods
 * names and return the first matching method.
 * </p>
 *
 * <p>
 * This method is used by
 * {@link #invokeMethod(Object object,String methodName,Object [] args,Class[] parameterTypes)}.
 *
 * <p>
 * This method can match primitive parameter by passing in wrapper classes.
 * For example, a <code>Boolean</code> will match a primitive
 * <code>boolean</code> parameter.
 *
 * @param clazz
 *            find method in this class
 * @param methodName
 *            find method with this name
 * @param parameterTypes
 *            find method with compatible parameters
 * @return The accessible method
 */
public static Method getMatchingAccessibleMethod(final Class<?> clazz, final String methodName,
        final Class<?>[] parameterTypes) {
    // trace logging
    final Log log = LogFactory.getLog(MethodUtils.class);
    if (log.isTraceEnabled()) {
        log.trace("Matching name=" + methodName + " on " + clazz);
    }
    final MethodDescriptor md = new MethodDescriptor(clazz, methodName, parameterTypes, false);

    // see if we can find the method directly
    // most of the time this works and it's much faster
    try {
        // Check the cache first
        Method method = getCachedMethod(md);
        if (method != null) {
            return method;
        }

        method = clazz.getMethod(methodName, parameterTypes);
        if (log.isTraceEnabled()) {
            log.trace("Found straight match: " + method);
            log.trace("isPublic:" + Modifier.isPublic(method.getModifiers()));
        }

        setMethodAccessible(method); // Default access superclass workaround

        cacheMethod(md, method);
        return method;

    } catch (final NoSuchMethodException e) {
        /* SWALLOW */ }

    // search through all methods
    final int paramSize = parameterTypes.length;
    Method bestMatch = null;
    final Method[] methods = clazz.getMethods();
    float bestMatchCost = Float.MAX_VALUE;
    float myCost = Float.MAX_VALUE;
    for (final Method method2 : methods) {
        if (method2.getName().equals(methodName)) {
            // log some trace information
            if (log.isTraceEnabled()) {
                log.trace("Found matching name:");
                log.trace(method2);
            }

            // compare parameters
            final Class<?>[] methodsParams = method2.getParameterTypes();
            final int methodParamSize = methodsParams.length;
            if (methodParamSize == paramSize) {
                boolean match = true;
                for (int n = 0; n < methodParamSize; n++) {
                    if (log.isTraceEnabled()) {
                        log.trace("Param=" + parameterTypes[n].getName());
                        log.trace("Method=" + methodsParams[n].getName());
                    }
                    if (!isAssignmentCompatible(methodsParams[n], parameterTypes[n])) {
                        if (log.isTraceEnabled()) {
                            log.trace(methodsParams[n] + " is not assignable from " + parameterTypes[n]);
                        }
                        match = false;
                        break;
                    }
                }

                if (match) {
                    // get accessible version of method
                    final Method method = getAccessibleMethod(clazz, method2);
                    if (method != null) {
                        if (log.isTraceEnabled()) {
                            log.trace(method + " accessible version of " + method2);
                        }
                        setMethodAccessible(method); // Default access
                        // superclass
                        // workaround
                        myCost = getTotalTransformationCost(parameterTypes, method.getParameterTypes());
                        if (myCost < bestMatchCost) {
                            bestMatch = method;
                            bestMatchCost = myCost;
                        }
                    }

                    log.trace("Couldn't find accessible method.");
                }
            }
        }
    }
    if (bestMatch != null) {
        cacheMethod(md, bestMatch);
    } else {
        // didn't find a match
        log.trace("No match found.");
    }

    return bestMatch;
}