Java Examples for android.util.Pair

The following java examples will help you to understand the usage of android.util.Pair. These source code samples are taken from different open source projects.

Example 1
Project: Android-Device-Compatibility-master  File: DateStringCompatTest.java View source code
public void testFormat() {
    Date date = new Date("2013/1/9 08:04:05");
    Pair[] array = new Pair[] { //  new Pair<String, String>(format, expected),
    new Pair<String, String>("yyyy-MM-dd HH:mm:ss", "2013-01-09 08:04:05"), new Pair<String, String>("yyyy/MM/dd HH:mm:ss", "2013/01/09 08:04:05"), new Pair<String, String>("MM月dd日", "01月09日") };
    for (Pair<String, String> p : array) {
        assertEquals(p.second, DateStringCompat.format(p.first, date));
    }
}
Example 2
Project: appaloosa-android-tools-master  File: AnalyticsServices.java View source code
public static void sendBatchToServer() {
    sending = true;
    final AnalyticsDb db = AppaloosaAnalytics.getAnalyticsDb();
    new Thread(new Runnable() {

        @Override
        public void run() {
            Pair<List<Integer>, JsonArray> idsAndOldestEvents = db.getOldestEvents();
            if (idsAndOldestEvents.first.size() > 0) {
                JsonObject data = buildJson(idsAndOldestEvents.second);
                send(idsAndOldestEvents.first, data, 1);
            }
        }
    }).start();
}
Example 3
Project: Fontster-master  File: FontFamily.java View source code
public static List<Pair<String, Typeface>> getSystemTypefaces() {
    List<Pair<String, Typeface>> typefaces = new ArrayList<>();
    for (FontFamily family : values()) {
        for (int style : family.styles) {
            typefaces.add(Pair.create(family.familyName + " " + styleToString(style), Typeface.create(family.familyName, style)));
        }
    }
    return typefaces;
}
Example 4
Project: jerrymouse-master  File: TypeMapperHelperTest.java View source code
@Test
public void test() throws Throwable {
    Pair<Type, Type> pair = TypeMapperHelper.getMapperGenericType(BooleanTypeMapper.class);
    if (pair == null) {
        Log.d(LOG_TAG, "pair is null");
        return;
    }
    Log.d(LOG_TAG, "first: " + pair.first + "\t" + pair.first.equals(Boolean.class));
    Log.d(LOG_TAG, "second: " + pair.second + "\t" + pair.second.equals(Integer.class));
}
Example 5
Project: masterpassword-master  File: MPUtils.java View source code
public static Pair<MPSiteType, MPSiteVariant> extractMPSiteParameters(String passwordTypeValue) {
    String[] typeAndVariant = passwordTypeValue.split(":");
    MPSiteType type = MPSiteType.GeneratedMaximum;
    MPSiteVariant variant = MPSiteVariant.Password;
    if (typeAndVariant.length >= 1) {
        try {
            type = MPSiteType.valueOf(typeAndVariant[0]);
        } catch (Exception ex) {
        }
    }
    if (typeAndVariant.length >= 2) {
        try {
            variant = MPSiteVariant.valueOf(typeAndVariant[1]);
        } catch (Exception ex) {
        }
    }
    return new Pair<>(type, variant);
}
Example 6
Project: testdroid-samples-master  File: AB_About.java View source code
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.ab_layout);
    // set dialog activity size
    {
        int margin = Helpers.getDimenDp(getApplicationContext(), R.dimen.margin_activity_dialog_narrow);
        Pair<Integer, Integer> dialogDimensions = Helpers.getWindowDimensionsWithoutMargin(getApplicationContext(), getWindowManager(), margin, margin);
        getWindow().setLayout(dialogDimensions.first, dialogDimensions.second);
    }
}
Example 7
Project: analytics-android-master  File: Stats.java View source code
void performIntegrationOperation(Pair<String, Long> durationForIntegration) {
    integrationOperationCount++;
    integrationOperationDuration += durationForIntegration.second;
    Long duration = integrationOperationDurationByIntegration.get(durationForIntegration.first);
    if (duration == null) {
        integrationOperationDurationByIntegration.put(durationForIntegration.first, durationForIntegration.second);
    } else {
        integrationOperationDurationByIntegration.put(durationForIntegration.first, duration + durationForIntegration.second);
    }
}
Example 8
Project: Android-Material-Examples-master  File: TransitionFirstActivity.java View source code
public void onFabPressed(View view) {
    Intent i = new Intent(TransitionFirstActivity.this, TransitionSecondActivity.class);
    ActivityOptions transitionActivityOptions = ActivityOptions.makeSceneTransitionAnimation(TransitionFirstActivity.this, Pair.create(mFabButton, "fab"), Pair.create(mHeader, "holder1"));
    startActivity(i, transitionActivityOptions.toBundle());
}
Example 9
Project: FreeFlow-master  File: NoAnimationLayoutAnimator.java View source code
@Override
public void animateChanges(LayoutChangeset changes, FreeFlowContainer callback) {
    this.changes = changes;
    for (Pair<FreeFlowItem, Rect> item : changes.getMoved()) {
        Rect r = item.first.frame;
        View v = item.first.view;
        int wms = MeasureSpec.makeMeasureSpec(r.right - r.left, MeasureSpec.EXACTLY);
        int hms = MeasureSpec.makeMeasureSpec(r.bottom - r.top, MeasureSpec.EXACTLY);
        v.measure(wms, hms);
        v.layout(r.left, r.top, r.right, r.bottom);
    }
    callback.onLayoutChangeAnimationsCompleted(this);
}
Example 10
Project: quran_android-master  File: AudioManagerUtils.java View source code
@NonNull
private static Single<QariDownloadInfo> getGappedSheikhObservable(final File basePath, final QariItem qariItem) {
    return Observable.range(1, 114).map( sura -> new SuraFileName(sura, new File(basePath, String.valueOf(sura)))).filter( suraFile -> suraFile.file.exists()).map( sf -> new Pair<>(sf.sura, sf.file.listFiles().length >= QuranInfo.SURA_NUM_AYAHS[sf.sura - 1])).toList().map( downloaded -> QariDownloadInfo.withPartials(qariItem, downloaded));
}
Example 11
Project: Securecom-Text-master  File: RootKey.java View source code
public Pair<RootKey, ChainKey> createChain(ECPublicKey theirEphemeral, ECKeyPair ourEphemeral) throws InvalidKeyException {
    HKDF kdf = new HKDF();
    byte[] sharedSecret = Curve.calculateAgreement(theirEphemeral, ourEphemeral.getPrivateKey());
    DerivedSecrets keys = kdf.deriveSecrets(sharedSecret, key, "WhisperRatchet".getBytes());
    RootKey newRootKey = new RootKey(keys.getCipherKey().getEncoded());
    ChainKey newChainKey = new ChainKey(keys.getMacKey().getEncoded(), 0);
    return new Pair<RootKey, ChainKey>(newRootKey, newChainKey);
}
Example 12
Project: stetho-master  File: Util.java View source code
public static ArrayList<Pair<String, String>> convertHeaders(Map<String, List<String>> map) {
    ArrayList<Pair<String, String>> array = new ArrayList<Pair<String, String>>();
    for (Map.Entry<String, List<String>> mapEntry : map.entrySet()) {
        for (String mapEntryValue : mapEntry.getValue()) {
            // the HTTP response line (for instance, HTTP/1.1 200 OK).  Ignore that weirdness...
            if (mapEntry.getKey() != null) {
                array.add(Pair.create(mapEntry.getKey(), mapEntryValue));
            }
        }
    }
    return array;
}
Example 13
Project: TransitionPlayer-master  File: MultiTimeInterpolator.java View source code
@Override
public float getInterpolation(float input) {
    float weightSum = 0;
    for (Pair<TimeInterpolator, Float> pair : pairs) {
        float weight = pair.second;
        float weightStart = weightSum;
        float weightEnd = weightStart + weight;
        float inputWeight = input * totalWeight;
        if (inputWeight > weightStart && inputWeight <= weightEnd) {
            float convertInput = (inputWeight - weightStart) / weight;
            return pair.first.getInterpolation(convertInput);
        }
        weightSum = weightEnd;
    }
    return 0;
}
Example 14
Project: ulti-master  File: NoAnimationLayoutAnimator.java View source code
@Override
public void animateChanges(LayoutChangeset changes, FreeFlowContainer callback) {
    this.changes = changes;
    for (Pair<FreeFlowItem, Rect> item : changes.getMoved()) {
        Rect r = item.first.frame;
        View v = item.first.view;
        int wms = MeasureSpec.makeMeasureSpec(r.right - r.left, MeasureSpec.EXACTLY);
        int hms = MeasureSpec.makeMeasureSpec(r.bottom - r.top, MeasureSpec.EXACTLY);
        v.measure(wms, hms);
        v.layout(r.left, r.top, r.right, r.bottom);
    }
    callback.onLayoutChangeAnimationsCompleted(this);
}
Example 15
Project: UltimateAndroid-master  File: NoAnimationLayoutAnimator.java View source code
@Override
public void animateChanges(LayoutChangeset changes, FreeFlowContainer callback) {
    this.changes = changes;
    for (Pair<FreeFlowItem, Rect> item : changes.getMoved()) {
        Rect r = item.first.frame;
        View v = item.first.view;
        int wms = MeasureSpec.makeMeasureSpec(r.right - r.left, MeasureSpec.EXACTLY);
        int hms = MeasureSpec.makeMeasureSpec(r.bottom - r.top, MeasureSpec.EXACTLY);
        v.measure(wms, hms);
        v.layout(r.left, r.top, r.right, r.bottom);
    }
    callback.onLayoutChangeAnimationsCompleted(this);
}
Example 16
Project: XDA-One-master  File: PostUtils.java View source code
public static Pair<String, String> parseQuoteUsernamePostid(final String usernamePostId) {
    if (TextUtils.isEmpty(usernamePostId)) {
        return null;
    }
    final String[] split = usernamePostId.split(";");
    if (split.length == 0) {
        return null;
    } else if (split.length == 1) {
        return new Pair<>(split[0], null);
    }
    return new Pair<>(split[0], split[1]);
}
Example 17
Project: Yhb-2.0-master  File: NoAnimationLayoutAnimator.java View source code
@Override
public void animateChanges(LayoutChangeset changes, FreeFlowContainer callback) {
    this.changes = changes;
    for (Pair<FreeFlowItem, Rect> item : changes.getMoved()) {
        Rect r = item.first.frame;
        View v = item.first.view;
        int wms = MeasureSpec.makeMeasureSpec(r.right - r.left, MeasureSpec.EXACTLY);
        int hms = MeasureSpec.makeMeasureSpec(r.bottom - r.top, MeasureSpec.EXACTLY);
        v.measure(wms, hms);
        v.layout(r.left, r.top, r.right, r.bottom);
    }
    callback.onLayoutChangeAnimationsCompleted(this);
}
Example 18
Project: 4pdaClient-plus-master  File: Note.java View source code
public ArrayList<Pair> getLinks() {
    ArrayList<Pair> links = new ArrayList<Pair>();
    if (!TextUtils.isEmpty(Topic)) {
        links.add(new Pair(Topic, getTopicUrl()));
    }
    if (!TextUtils.isEmpty(User)) {
        links.add(new Pair(User, getUserUrl()));
    }
    if (!TextUtils.isEmpty(Url)) {
        links.add(new Pair(App.getContext().getString(R.string.link_to_post), Url));
    }
    return links;
}
Example 19
Project: Android--Event-Triggered-Skype-Caller-master  File: AdapterUtils.java View source code
public List<Pair<String, String>> queryContacts(final ContentResolver cr) {
    Logger.i(TAG, "Generating Contact DataList");
    final Cursor skypeCursor = cr.query(ContactsContract.Data.CONTENT_URI, null, null, null, ContactsContract.Data.DISPLAY_NAME + " collate localized");
    final List<Pair<String, String>> dataList = new ArrayList<Pair<String, String>>();
    final Set<String> addedSkypeNames = new HashSet<String>();
    while (skypeCursor.moveToNext()) {
        final int type = skypeCursor.getInt(skypeCursor.getColumnIndex(ContactsContract.CommonDataKinds.Im.PROTOCOL));
        final String contactName = skypeCursor.getString(skypeCursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
        final String imName = skypeCursor.getString(skypeCursor.getColumnIndex(ContactsContract.CommonDataKinds.Im.DATA));
        if (type == ContactsContract.CommonDataKinds.Im.PROTOCOL_SKYPE) {
            if (imName != null && imName.trim().length() > 0) {
                final String skypeName = imName.trim();
                if (!addedSkypeNames.contains(skypeName)) {
                    dataList.add(new Pair<String, String>(contactName, skypeName));
                    addedSkypeNames.add(skypeName);
                }
            }
        }
    }
    skypeCursor.close();
    return dataList;
}
Example 20
Project: android-oss-master  File: ProjectSearchResultHolderViewModelTest.java View source code
@Test
public void testEmitsProjectImage() {
    final Project project = ProjectFactory.project().toBuilder().photo(PhotoFactory.photo().toBuilder().med("http://www.kickstarter.com/med.jpg").build()).build();
    setUpEnvironment(environment());
    this.vm.inputs.configureWith(Pair.create(project, false));
    this.projectPhotoUrl.assertValues("http://www.kickstarter.com/med.jpg");
}
Example 21
Project: android-sdk-sources-for-api-level-23-master  File: ActivityOptionsCompat21.java View source code
public static ActivityOptionsCompat21 makeSceneTransitionAnimation(Activity activity, View[] sharedElements, String[] sharedElementNames) {
    Pair[] pairs = null;
    if (sharedElements != null) {
        pairs = new Pair[sharedElements.length];
        for (int i = 0; i < pairs.length; i++) {
            pairs[i] = Pair.create(sharedElements[i], sharedElementNames[i]);
        }
    }
    return new ActivityOptionsCompat21(ActivityOptions.makeSceneTransitionAnimation(activity, pairs));
}
Example 22
Project: android-sotm-master  File: StatsFragment.java View source code
public void bind(GameSetup gameSetup) {
    String str;
    if (!gameSetup.canRandomize()) {
        str = getString(NotEnoughCardsDialogFragment.getErrorResId(gameSetup.getFirstLackingType()));
    } else {
        if (gameSetup.hasRandomCards()) {
            Pair<Integer, Integer> winPointRange = gameSetup.getPointRange();
            int low = Db.getWinPercent(winPointRange.second);
            int high = Db.getWinPercent(winPointRange.first);
            str = getString(R.string.template_win_range, low, high);
        } else {
            str = getString(R.string.template_win_chance, gameSetup.getWinPercent());
        }
    }
    mStatsTextView.setText(Html.fromHtml(str));
}
Example 23
Project: android-support-v4-master  File: ActivityOptionsCompat21.java View source code
public static ActivityOptionsCompat21 makeSceneTransitionAnimation(Activity activity, View[] sharedElements, String[] sharedElementNames) {
    Pair[] pairs = null;
    if (sharedElements != null) {
        pairs = new Pair[sharedElements.length];
        for (int i = 0; i < pairs.length; i++) {
            pairs[i] = Pair.create(sharedElements[i], sharedElementNames[i]);
        }
    }
    return new ActivityOptionsCompat21(ActivityOptions.makeSceneTransitionAnimation(activity, pairs));
}
Example 24
Project: android-vts-master  File: ApplicationVulnerabilityTester.java View source code
@Override
protected List<ApplicationVulnTestResult> doInBackground(Void... params) {
    PackageManager pm = mCtx.getPackageManager();
    List<ApplicationInfo> apps = pm.getInstalledApplications(PackageManager.GET_SHARED_LIBRARY_FILES | PackageManager.GET_META_DATA);
    List<ApplicationVulnTestResult> applicationVulnerabilityTestResults = new ArrayList<>();
    List<Pair<ApplicationInfo, Exception>> untestedApps = new ArrayList<>();
    for (int i = 0; i < apps.size(); i++) {
        ApplicationInfo ai = apps.get(i);
        String sourceApk = ai.publicSourceDir;
        boolean apkExploitedBug13678484 = false;
        try {
            apkExploitedBug13678484 = JarFileHelper.isExploitingBug13678484(sourceApk);
        } catch (Exception e) {
            untestedApps.add(Pair.create(ai, e));
        }
        if (apkExploitedBug13678484) {
            applicationVulnerabilityTestResults.add(ApplicationVulnTestResult.build(ai, null));
        }
    }
    return applicationVulnerabilityTestResults;
}
Example 25
Project: AndroidHeroes-master  File: MainActivity.java View source code
// 设置��动画效果
public void share(View view) {
    View fab = findViewById(R.id.fab_button);
    intent = new Intent(this, Transitions.class);
    intent.putExtra("flag", 3);
    // 创建�个共享元素
    //        startActivity(intent,
    //                ActivityOptions.makeSceneTransitionAnimation(
    //                        this, view, "share").toBundle());
    startActivity(intent, ActivityOptions.makeSceneTransitionAnimation(this, // 创建多个共享元素
    Pair.create(view, "share"), Pair.create(fab, "fab")).toBundle());
}
Example 26
Project: ChipsLayoutManager-master  File: RTLUpLayouter.java View source code
@Override
void onPreLayout() {
    int leftOffsetOfRow = -(getCanvasRightBorder() - viewLeft);
    viewLeft = rowViews.size() > 0 ? Integer.MAX_VALUE : 0;
    for (Pair<Rect, View> rowViewRectPair : rowViews) {
        Rect viewRect = rowViewRectPair.first;
        viewRect.left = viewRect.left - leftOffsetOfRow;
        viewRect.right = viewRect.right - leftOffsetOfRow;
        viewLeft = Math.min(viewLeft, viewRect.left);
        viewTop = Math.min(viewTop, viewRect.top);
        viewBottom = Math.max(viewBottom, viewRect.bottom);
    }
}
Example 27
Project: client-master  File: FakeAsyncTaskRunner.java View source code
/** Blocks until all queued and running {@link AsyncTask}s are complete. */
public void runUntilEmpty() {
    while (!mQueuedTasks.isEmpty()) {
        Pair<AsyncTask<Object, Object, Object>, Object[]> queuedTask = mQueuedTasks.pop();
        if (!queuedTask.first.isCancelled()) {
            queuedTask.first.executeOnExecutor(EXECUTOR, queuedTask.second);
        }
        mInstrumentation.waitForIdleSync();
    }
}
Example 28
Project: cloudrail-si-android-sdk-master  File: POIAdapter.java View source code
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // assign the view we are converting to a local variable
    View v = convertView;
    // to inflate it basically means to render, or show, the view.
    if (v == null) {
        LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        v = inflater.inflate(R.layout.list_poi, null);
    }
    Pair<POI, Long> poi = data.get(position);
    TextView name = (TextView) v.findViewById(R.id.poi_name);
    name.setText(poi.first.getName());
    TextView distance = (TextView) v.findViewById(R.id.poi_distance);
    distance.setText(poi.second.toString() + "m");
    return v;
}
Example 29
Project: download-manager-master  File: ContentLengthFetcher.java View source code
private void addRequestHeaders(FileDownloadInfo info, HttpURLConnection conn) {
    for (Pair<String, String> header : info.getHeaders()) {
        conn.addRequestProperty(header.first, header.second);
    }
    // Only splice in user agent when not already defined
    if (conn.getRequestProperty(HEADER_USER_AGENT) == null) {
        conn.addRequestProperty(HEADER_USER_AGENT, userAgent(info));
    }
}
Example 30
Project: DroidBeard-master  File: EpisodeSearchTask.java View source code
@Override
protected Boolean doInBackground(Void... voids) {
    List<Pair<String, Object>> params = new ArrayList<Pair<String, Object>>();
    params.add(new Pair<String, Object>("tvdbid", mTvDBId));
    params.add(new Pair<String, Object>("season", mSeason));
    params.add(new Pair<String, Object>("episode", mEpisode));
    String json = getJson("episode.search", params);
    try {
        return json != null && json.contains("success");
    } catch (Exception e) {
        setLastException(json, e);
        e.printStackTrace();
        return false;
    }
}
Example 31
Project: droidparts-master  File: Update.java View source code
public int execute() {
    Pair<String, String[]> selection = getSelection();
    L.d(toString());
    int rowCount = 0;
    try {
        rowCount = db.update(tableName, contentValues, selection.first, selection.second);
    } catch (SQLException e) {
        L.e(e.getMessage());
        L.d(e);
    }
    return rowCount;
}
Example 32
Project: EhViewer-master  File: TorrentParser.java View source code
@SuppressWarnings("unchecked")
public static Pair<String, String>[] parse(String body) {
    List<Pair<String, String>> torrentList = new ArrayList<>();
    Matcher m = PATTERN_TORRENT.matcher(body);
    while (m.find()) {
        // Remove ?p= to make torrent redistributable
        String url = ParserUtils.trim(m.group(1));
        int index = url.indexOf("?p=");
        if (index != -1) {
            url = url.substring(0, index);
        }
        String name = ParserUtils.trim(m.group(2));
        Pair<String, String> item = new Pair<>(url, name);
        torrentList.add(item);
    }
    return torrentList.toArray(new Pair[torrentList.size()]);
}
Example 33
Project: external_jbirdvegas_mGerrit-master  File: OwnerSearch.java View source code
/**
     * Process Strings such as "John Doe <john@example.com>"
     * @return A pair in the form (username, email). For the
     *  above example it would be (John Doe, john@example.com)
     */
private Pair<String, String> processMultiPartOwner() {
    String owner = getParam();
    Pattern r_username = Pattern.compile("[^<>]+");
    Matcher m = r_username.matcher(owner);
    int i = 0;
    String[] user_email = new String[2];
    while (m.find() && i < 2) {
        user_email[i] = m.group(0).trim();
        i++;
    }
    return new Pair<>(user_email[0], user_email[1]);
}
Example 34
Project: galgs-master  File: GrahamScan.java View source code
public Pair<List<Point2D>, Integer> convexHullGrahamScan(List<Point2D> vertices) {
    Deque<Point2D> verticesOnHull = new ArrayDeque<Point2D>();
    Collections.sort(vertices, new YXOrderComparator());
    Collections.sort(vertices, new PolarOrderComparator(vertices.get(0)));
    verticesOnHull.push(vertices.get(0));
    // find index firstPointNotEqual of first point not equal to points[0]
    int firstPointNotEqual;
    for (firstPointNotEqual = 1; firstPointNotEqual < vertices.size(); firstPointNotEqual++) {
        if (!vertices.get(0).equals(vertices.get(firstPointNotEqual))) {
            break;
        }
    }
    if (firstPointNotEqual == vertices.size()) {
        // all points are equal
        return null;
    }
    // find index k2 of first point not collinear with points[0] and points[firstPointNotEqual]
    int k2;
    for (k2 = firstPointNotEqual + 1; k2 < vertices.size(); k2++) {
        if (Utils.ccw(vertices.get(0), vertices.get(firstPointNotEqual), vertices.get(k2)) != 0) {
            break;
        }
    }
    verticesOnHull.push(vertices.get(k2 - 1));
    // Graham scan; note that points[N-1] is extreme point different from points[0]
    for (int i = k2; i < vertices.size(); i++) {
        Point2D top = verticesOnHull.pop();
        while (Utils.ccw(verticesOnHull.peek(), top, vertices.get(i)) <= 0) {
            top = verticesOnHull.pop();
        }
        verticesOnHull.push(top);
        verticesOnHull.push(vertices.get(i));
    }
    return new Pair<List<Point2D>, Integer>(new ArrayList<Point2D>(verticesOnHull), GLES20.GL_LINE_LOOP);
}
Example 35
Project: google-maps-sdk-rectify-master  File: Transform.java View source code
//
// World Geodetic System ==> Mars Geodetic System
public static Pair<Double, /* Lat */
Double> transform(final double wgLat, final double wgLon) {
    if (outOfChina(wgLat, wgLon))
        return new Pair<Double, Double>(wgLat, wgLon);
    double dLat = transformLat(wgLon - 105.0, wgLat - 35.0);
    double dLon = transformLon(wgLon - 105.0, wgLat - 35.0);
    final double radLat = wgLat / 180.0 * pi;
    double magic = Math.sin(radLat);
    magic = 1 - ee * magic * magic;
    final double sqrtMagic = Math.sqrt(magic);
    dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * pi);
    dLon = (dLon * 180.0) / (a / sqrtMagic * Math.cos(radLat) * pi);
    return new Pair<Double, Double>(wgLat + dLat, wgLon + dLon);
}
Example 36
Project: IntranetEpitechV2-master  File: ActivityOptionsCompat21.java View source code
public static ActivityOptionsCompat21 makeSceneTransitionAnimation(Activity activity, View[] sharedElements, String[] sharedElementNames) {
    Pair[] pairs = null;
    if (sharedElements != null) {
        pairs = new Pair[sharedElements.length];
        for (int i = 0; i < pairs.length; i++) {
            pairs[i] = Pair.create(sharedElements[i], sharedElementNames[i]);
        }
    }
    return new ActivityOptionsCompat21(ActivityOptions.makeSceneTransitionAnimation(activity, pairs));
}
Example 37
Project: Jobmine-Plus-master  File: DataSourceBase.java View source code
// ======================
// Protected Methods
// ======================
protected long updateElseInsert(String table, ArrayList<Pair<String, Object>> where, ContentValues values) {
    // Unlike insert, update does not throw any errors and it will be faster
    String whereStr = "";
    int i = 0;
    for (i = 0; i < where.size() - 1; i++) {
        whereStr += where.get(i).first + "='" + where.get(i).second + "' AND ";
    }
    whereStr += where.get(i).first + "=?";
    if (!database.isOpen()) {
        open();
    }
    long affected = database.update(table, values, whereStr, new String[] { where.get(i).second + "" });
    if (affected == 0) {
        affected = database.insertOrThrow(table, null, values);
    }
    return affected;
}
Example 38
Project: KISS-master  File: AppPojo.java View source code
public void setTags(String tags) {
    // Set the actual user-friendly name
    this.tags = tags;
    if (this.tags != null) {
        this.tags = this.tags.replaceAll("<", "<");
        // Normalize name for faster searching
        Pair<String, int[]> normalized = StringNormalizer.normalizeWithMap(this.tags);
        this.tagsNormalized = normalized.first;
        this.tagsPositionMap = normalized.second;
    }
}
Example 39
Project: mandarin-android-master  File: HttpParamsBuilder.java View source code
/**
     * Builds Url request string from specified parameters.
     *
     * @return String - Url request parameters.
     * @throws java.io.UnsupportedEncodingException
     */
public String build() throws UnsupportedEncodingException {
    StringBuilder builder = new StringBuilder();
    // Perform pair concatenation.
    for (Pair<String, String> pair : this) {
        if (builder.length() > 0) {
            builder.append(AMP);
        }
        builder.append(pair.first).append(EQUAL).append(StringUtil.urlEncode(pair.second));
    }
    return builder.toString();
}
Example 40
Project: mensaapp-master  File: WeeklyMenuTask.java View source code
@Override
protected Pair<WeeklyMenu, Exception> doInBackground(String... urls) {
    List<WeeklyMenu> menus = new ArrayList<WeeklyMenu>();
    for (String url : urls) {
        try {
            Document document = Jsoup.connect(url).get();
            WeeklyMenuParser parser = WeeklyMenuParser.create(context, document, mensa);
            menus.add(parser.parse());
        } catch (WeeklyMenuParseException wmpe) {
            Log.w(TAG, String.format(context.getString(R.string.error_menu_parse), url), wmpe);
            return new Pair<WeeklyMenu, Exception>(null, wmpe);
        } catch (Exception e) {
            Log.e(TAG, String.format(context.getString(R.string.error_menu_download), url), e);
            return new Pair<WeeklyMenu, Exception>(null, e);
        }
    }
    return new Pair<WeeklyMenu, Exception>(WeeklyMenu.merge(mensa, Utils.now(), menus), null);
}
Example 41
Project: NanoPond-master  File: ReportListAdapter.java View source code
@Override
public Pair<String, Long> getItem(int position) {
    switch(position) {
        case 0:
            return new Pair<String, Long>("Year", report.year);
        case 1:
            return new Pair<String, Long>("Energy", report.energy);
        case 2:
            return new Pair<String, Long>("Max generation", report.maxGeneration);
        case 3:
            return new Pair<String, Long>("Active cells", report.activeCells);
        case 4:
            return new Pair<String, Long>("Viable replicators", report.viableReplicators);
        case 5:
            return new Pair<String, Long>("Kills", report.kills);
        case 6:
            return new Pair<String, Long>("Replaced", report.replaced);
        case 7:
            return new Pair<String, Long>("Shares", report.shares);
    }
    return null;
}
Example 42
Project: OPFPush-master  File: ConnectivityChangeReceiver.java View source code
@Override
public void onReceive(@NonNull final Context context, @NonNull final Intent intent) {
    OPFLog.logMethod(context, OPFUtils.toString(intent));
    final Set<Pair<String, String>> retryProvidersActions = RetryManager.getInstance().getRetryProvidersActions();
    final OPFPushHelper helper = OPFPush.getHelper();
    for (Pair<String, String> retryProviderAction : retryProvidersActions) {
        final String providerName = retryProviderAction.first;
        final String action = retryProviderAction.second;
        switch(action) {
            case ACTION_RETRY_REGISTER:
                helper.register(providerName);
                break;
            case ACTION_RETRY_UNREGISTER:
                helper.unregister(providerName);
                break;
        }
    }
}
Example 43
Project: piwik_android_sdk-master  File: UrlHelper.java View source code
public static void parse(@NonNull final List<Pair<String, String>> parameters, @NonNull final Scanner scanner, @Nullable final String encoding) {
    scanner.useDelimiter(PARAMETER_SEPARATOR);
    while (scanner.hasNext()) {
        final String[] nameValue = scanner.next().split(NAME_VALUE_SEPARATOR);
        if (nameValue.length == 0 || nameValue.length > 2)
            throw new IllegalArgumentException("bad parameter");
        final String name = decode(nameValue[0], encoding);
        String value = null;
        if (nameValue.length == 2)
            value = decode(nameValue[1], encoding);
        parameters.add(new Pair<>(name, value));
    }
}
Example 44
Project: PLDroidPlayer-master  File: AspectLayout.java View source code
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    Log.d(TAG, "onMeasure" + " width=[" + MeasureSpec.toString(widthMeasureSpec) + "] height=[" + View.MeasureSpec.toString(heightMeasureSpec) + "]");
    Rect r = new Rect();
    getWindowVisibleDisplayFrame(r);
    Pair<Integer, Integer> screenSize = Util.getResolution(getContext());
    if (mRootWidth == 0 && mRootHeight == 0) {
        mRootWidth = getRootView().getWidth();
        mRootHeight = getRootView().getHeight();
    }
    int totalHeight = 0;
    if (screenSize.first > screenSize.second) {
        // land
        totalHeight = mRootWidth > mRootHeight ? mRootHeight : mRootWidth;
    } else {
        // port
        totalHeight = mRootWidth < mRootHeight ? mRootHeight : mRootWidth;
    }
    int nowHeight = r.bottom - r.top;
    if (totalHeight - nowHeight > totalHeight / 4) {
        // soft keyboard show
        super.onMeasure(mWidthMeasureSpec, MeasureSpec.makeMeasureSpec(nowHeight + totalHeight - nowHeight, MeasureSpec.EXACTLY));
        return;
    } else {
    // soft keyboard hide
    }
    mWidthMeasureSpec = widthMeasureSpec;
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
Example 45
Project: pocketDSLR-master  File: CameraSettingButton.java View source code
public void registerManualCameraSettings(ManualCameraSettings manualCameraSettings, CameraCharacteristics cameraCharacteristics) {
    this.manualCameraSettings = manualCameraSettings;
    this.manualCameraSettings.registerSetting(this.cameraSetting.getSettingKey(), this.cameraSetting);
    this.cameraSetting.setRange(cameraCharacteristics);
    int storedValue = this.manualCameraSettings.getKey(this.cameraSetting.getSettingKey());
    Pair<Integer, String> settingValue = this.cameraSetting.getSettingValue(storedValue);
    this.setText(settingValue.second);
}
Example 46
Project: safeconnect-master  File: PortFilterAttribute.java View source code
@Override
public byte[] getEncoding() {
    BufferedByteWriter writer = new BufferedByteWriter();
    for (Pair<Protocol, Short> port : mPorts) {
        /* we report open ports, so the BLOCKED flag is not set */
        writer.put((byte) 0);
        writer.put(port.first.getValue());
        writer.put16(port.second);
    }
    return writer.toByteArray();
}
Example 47
Project: sdk-support-master  File: ActivityOptionsCompat21.java View source code
public static ActivityOptionsCompat21 makeSceneTransitionAnimation(Activity activity, View[] sharedElements, String[] sharedElementNames) {
    Pair[] pairs = null;
    if (sharedElements != null) {
        pairs = new Pair[sharedElements.length];
        for (int i = 0; i < pairs.length; i++) {
            pairs[i] = Pair.create(sharedElements[i], sharedElementNames[i]);
        }
    }
    return new ActivityOptionsCompat21(ActivityOptions.makeSceneTransitionAnimation(activity, pairs));
}
Example 48
Project: SITracker-master  File: SamlibPublicationPageReader.java View source code
@NotNull
@Override
public List<Pair<String, String>> readPublicationImageUrlsAndDescriptions(String pageContent) {
    List<Pair<String, String>> result = new ArrayList<Pair<String, String>>();
    Pattern pattern = Pattern.compile(IMAGE_EXTRACTION_REGEX, Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
    Matcher matcher = pattern.matcher(pageContent);
    while (matcher.find()) {
        String imageUrl = matcher.group(1) == null ? "" : matcher.group(1);
        String imgDesc = matcher.group(2) == null ? "" : matcher.group(2);
        if (!TextUtils.isEmpty(imageUrl)) {
            result.add(new Pair<String, String>(SAMLIB_URL_PREFIX + imageUrl.trim(), imgDesc.trim()));
        }
    }
    return result;
}
Example 49
Project: ts-android-master  File: StringUtilities.java View source code
/**
     * Expands a selection to include spans
     * @param text
     * @param start
     * @param end
     * @return the pair of start and end values
     */
public static Pair<Integer, Integer> expandSelectionForSpans(Editable text, int start, int end) {
    // make sure we don't cut any spans in half
    SpannedString[] spans = text.getSpans(start, end, SpannedString.class);
    for (SpannedString s : spans) {
        int spanStart = text.getSpanStart(s);
        int spanEnd = text.getSpanEnd(s);
        if (spanStart < start) {
            start = spanStart;
        }
        if (spanEnd > end) {
            end = spanEnd;
        }
    }
    return new Pair(start, end);
}
Example 50
Project: ZwitscherA-master  File: TriggerPictureDownloadTask.java View source code
@Override
protected Pair<Bitmap, Bitmap> doInBackground(Void... aVoid) {
    // main user image
    Bitmap imageBitmap = picHelper.getBitMapForScreenNameFromFile(user.getScreenName());
    if (imageBitmap == null && downloadImages) {
        imageBitmap = picHelper.fetchUserPic(user);
    }
    if (status == null) {
        // E.g. direct message
        return new Pair<Bitmap, Bitmap>(imageBitmap, null);
    }
    // Image of the user of the retweeted status
    Bitmap rtBitmap = null;
    if (status.isRetweet()) {
        rtBitmap = picHelper.getBitMapForScreenNameFromFile(status.getUser().getScreenName());
        if (rtBitmap == null && downloadImages) {
            rtBitmap = picHelper.fetchUserPic(status.getUser());
        }
    }
    return new Pair<Bitmap, Bitmap>(imageBitmap, rtBitmap);
}
Example 51
Project: yahnac-master  File: Navigator.java View source code
public void toComments(View v, Story story) {
    ActivityOptionsCompat activityOptions = ActivityOptionsCompat.makeSceneTransitionAnimation(activity, new Pair<>(v, CommentsPresenter.VIEW_NAME_HEADER_TITLE));
    Intent commentIntent = new Intent(activity, CommentsActivity.class);
    commentIntent.putExtra(CommentsActivity.ARG_STORY, story);
    ActivityCompat.startActivity(activity, commentIntent, activityOptions.toBundle());
}
Example 52
Project: android-chromium-master  File: AutoLoginDelegate.java View source code
/**
     * @return the account name of the device if any.
     */
@CalledByNative
String initializeAccount(int nativeInfoBar, String realm, String account, String args) {
    AutoLoginAccountDelegate accountHelper = new AutoLoginAccountDelegate(mActivity, mAutoLoginProcessor, realm, account, args);
    if (!accountHelper.hasAccount()) {
        return "";
    }
    mAccountHelper = new Pair<Integer, AutoLoginAccountDelegate>(nativeInfoBar, accountHelper);
    return accountHelper.getAccountName();
}
Example 53
Project: android-testing-master  File: LogHistoryAndroidUnitTest.java View source code
@Test
public void logHistory_ParcelableWriteRead() {
    // Set up the Parcelable object to send and receive.
    mLogHistory.addEntry(TEST_STRING, TEST_LONG);
    // Write the data
    Parcel parcel = Parcel.obtain();
    mLogHistory.writeToParcel(parcel, mLogHistory.describeContents());
    // After you're done with writing, you need to reset the parcel for reading.
    parcel.setDataPosition(0);
    // Read the data
    LogHistory createdFromParcel = LogHistory.CREATOR.createFromParcel(parcel);
    List<Pair<String, Long>> createdFromParcelData = createdFromParcel.getData();
    // Verify that the received data is correct.
    assertThat(createdFromParcelData.size(), is(1));
    assertThat(createdFromParcelData.get(0).first, is(TEST_STRING));
    assertThat(createdFromParcelData.get(0).second, is(TEST_LONG));
}
Example 54
Project: androidtv-codelab-app-master  File: SearchContentProviderTest.java View source code
private Pair<Long, String> getMiddleRow() {
    final Cursor cursor = getVideoCursor();
    assertNotNull(cursor);
    assertTrue(cursor.getCount() > 0);
    assertTrue(cursor.moveToPosition(cursor.getCount() / 2));
    final long id = cursor.getLong(cursor.getColumnIndexOrThrow(UniversalSearchContract.Video.ID));
    final String title = cursor.getString(cursor.getColumnIndexOrThrow(UniversalSearchContract.Video.TITLE));
    cursor.close();
    Log.d(TAG, "Sample row: " + id + " " + title);
    return new Pair<>(id, title);
}
Example 55
Project: android_frameworks_base-master  File: UserTile.java View source code
@Override
protected void handleUpdateState(State state, Object arg) {
    final Pair<String, Drawable> p = arg != null ? (Pair<String, Drawable>) arg : mLastUpdate;
    if (p != null) {
        state.label = p.first;
        // TODO: Better content description.
        state.contentDescription = p.first;
        state.icon = new Icon() {

            @Override
            public Drawable getDrawable(Context context) {
                return p.second;
            }
        };
    } else {
    // TODO: Default state.
    }
}
Example 56
Project: AppsiHomePlugins-master  File: CalendarSettingsActivity.java View source code
private void bindSelectedCalendarsPreference() {
    CalendarSelectionPreference preference = (CalendarSelectionPreference) findPreference(CalendarExtension.PREF_SELECTED_CALENDARS);
    final List<Pair<String, Boolean>> allCalendars = CalendarExtension.getAllCalendars(this);
    Set<String> allVisibleCalendarsSet = new HashSet<String>();
    for (Pair<String, Boolean> pair : allCalendars) {
        if (pair.second) {
            allVisibleCalendarsSet.add(pair.first);
        }
    }
    Preference.OnPreferenceChangeListener calendarsChangeListener = new Preference.OnPreferenceChangeListener() {

        @Override
        public boolean onPreferenceChange(Preference preference, Object value) {
            int numSelected = 0;
            int numTotal = allCalendars.size();
            try {
                //noinspection check,unchecked
                Set<String> selectedCalendars = (Set<String>) value;
                if (selectedCalendars != null) {
                    numSelected = selectedCalendars.size();
                }
            } catch (ClassCastException ignored) {
            }
            preference.setSummary(getResources().getQuantityString(R.plurals.pref_calendar_selected_summary_template, numTotal, numSelected, numTotal));
            return true;
        }
    };
    preference.setOnPreferenceChangeListener(calendarsChangeListener);
    calendarsChangeListener.onPreferenceChange(preference, PreferenceManager.getDefaultSharedPreferences(this).getStringSet(preference.getKey(), allVisibleCalendarsSet));
}
Example 57
Project: bblfr-android-master  File: CheckDataService.java View source code
private Observable<City> getFavoriteCity(Context context) {
    return Observable.fromCallable(() -> {
        mProvider.initSync(context);
        City city = null;
        Pair<String, String> latLng = mPrefs.getFavoriteCityLatLng();
        if (latLng != null) {
            Timber.d("Favorite city found");
            city = mCitiesDao.getCityByLatLng(latLng.first, latLng.second);
        }
        if (city == null) {
            Timber.d("Try to find the closest city");
            city = findClosestCity(mProvider.getLastKnownLocation(), mCitiesDao.getCities());
            if (city != null) {
                mPrefs.setFavoriteCity(city);
            }
        }
        return city;
    });
}
Example 58
Project: Benchit-master  File: Result.java View source code
public Result log() {
    List<Pair<String, String>> stats = new ArrayList<>();
    stats.add(new Pair<>("Sample Size", times.size() + ""));
    if (Benchit.STATISTICS.contains(Benchit.Stat.AVERAGE)) {
        stats.add(new Pair<>("Average", time(average) + precision.unit));
    }
    if (Benchit.STATISTICS.contains(Benchit.Stat.RANGE)) {
        stats.add(new Pair<>("Range", time(min) + precision.unit + " --> " + time(max) + precision.unit));
    }
    if (Benchit.STATISTICS.contains(Benchit.Stat.STANDARD_DEVIATION)) {
        stats.add(new Pair<>("Deviation", time(deviation) + precision.unit));
    }
    Benchit.logMany(tag, stats);
    return this;
}
Example 59
Project: BoomMenu-master  File: TextOutsideCircleButtonActivity.java View source code
private List<String> getData() {
    List<String> data = new ArrayList<>();
    for (int p = 0; p < PiecePlaceEnum.values().length - 1; p++) {
        for (int b = 0; b < ButtonPlaceEnum.values().length - 1; b++) {
            PiecePlaceEnum piecePlaceEnum = PiecePlaceEnum.getEnum(p);
            ButtonPlaceEnum buttonPlaceEnum = ButtonPlaceEnum.getEnum(b);
            if (piecePlaceEnum.pieceNumber() == buttonPlaceEnum.buttonNumber() || buttonPlaceEnum == ButtonPlaceEnum.Horizontal || buttonPlaceEnum == ButtonPlaceEnum.Vertical) {
                piecesAndButtons.add(new Pair<>(piecePlaceEnum, buttonPlaceEnum));
                data.add(piecePlaceEnum + " " + buttonPlaceEnum);
                if (piecePlaceEnum == PiecePlaceEnum.HAM_1 || piecePlaceEnum == PiecePlaceEnum.HAM_2 || piecePlaceEnum == PiecePlaceEnum.HAM_3 || piecePlaceEnum == PiecePlaceEnum.HAM_4 || piecePlaceEnum == PiecePlaceEnum.HAM_5 || piecePlaceEnum == PiecePlaceEnum.HAM_6 || piecePlaceEnum == PiecePlaceEnum.Share || buttonPlaceEnum == ButtonPlaceEnum.HAM_1 || buttonPlaceEnum == ButtonPlaceEnum.HAM_2 || buttonPlaceEnum == ButtonPlaceEnum.HAM_3 || buttonPlaceEnum == ButtonPlaceEnum.HAM_4 || buttonPlaceEnum == ButtonPlaceEnum.HAM_5 || buttonPlaceEnum == ButtonPlaceEnum.HAM_6) {
                    piecesAndButtons.remove(piecesAndButtons.size() - 1);
                    data.remove(data.size() - 1);
                }
            }
        }
    }
    return data;
}
Example 60
Project: BurnMessenger-master  File: ImageResizer.java View source code
public static Bitmap resizeImageMaintainAspectRatio(byte[] imageData, int shorterSideTarget) {
    Pair<Integer, Integer> dimensions = getDimensions(imageData);
    // Determine the aspect ratio (width/height) of the image
    int imageWidth = dimensions.first;
    int imageHeight = dimensions.second;
    float ratio = (float) dimensions.first / dimensions.second;
    int targetWidth;
    int targetHeight;
    // Determine portrait or landscape
    if (imageWidth > imageHeight) {
        // Landscape image. ratio (width/height) is > 1
        targetHeight = shorterSideTarget;
        targetWidth = Math.round(shorterSideTarget * ratio);
    } else {
        // Portrait image. ratio (width/height) is < 1
        targetWidth = shorterSideTarget;
        targetHeight = Math.round(shorterSideTarget / ratio);
    }
    return resizeImage(imageData, targetWidth, targetHeight);
}
Example 61
Project: chart-master  File: AboutActivity.java View source code
public static Pair<String, Integer> getAppVersionAndBuild(Context context) {
    try {
        PackageInfo pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
        return new Pair<String, Integer>(pInfo.versionName, pInfo.versionCode);
    } catch (Exception e) {
        Log.e(TAG, "Could not get version number");
        return new Pair<String, Integer>("", 0);
    }
}
Example 62
Project: commcare-odk-master  File: LegacyTableBuilder.java View source code
public static Pair<String, String[]> sqlList(Collection<Integer> input) {
    //I want list comprehensions so bad right now.
    String ret = "(";
    for (int i : input) {
        ret += "?" + ",";
    }
    String[] array = new String[input.size()];
    int count = 0;
    for (Integer i : input) {
        array[count++] = String.valueOf(i);
    }
    return new Pair<String, String[]>(ret.substring(0, ret.length() - 1) + ")", array);
}
Example 63
Project: conversation-master  File: MessagePacket.java View source code
public Pair<MessagePacket, Long> getForwardedMessagePacket(String name, String namespace) {
    Element wrapper = findChild(name, namespace);
    if (wrapper == null) {
        return null;
    }
    Element forwarded = wrapper.findChild("forwarded", "urn:xmpp:forward:0");
    if (forwarded == null) {
        return null;
    }
    MessagePacket packet = create(forwarded.findChild("message"));
    if (packet == null) {
        return null;
    }
    Long timestamp = AbstractParser.parseTimestamp(forwarded, null);
    return new Pair(packet, timestamp);
}
Example 64
Project: Conversations-master  File: MessagePacket.java View source code
public Pair<MessagePacket, Long> getForwardedMessagePacket(String name, String namespace) {
    Element wrapper = findChild(name, namespace);
    if (wrapper == null) {
        return null;
    }
    Element forwarded = wrapper.findChild("forwarded", "urn:xmpp:forward:0");
    if (forwarded == null) {
        return null;
    }
    MessagePacket packet = create(forwarded.findChild("message"));
    if (packet == null) {
        return null;
    }
    Long timestamp = AbstractParser.parseTimestamp(forwarded, null);
    return new Pair(packet, timestamp);
}
Example 65
Project: dashclock-master  File: CalendarSettingsActivity.java View source code
private void bindSelectedCalendarsPreference() {
    CalendarSelectionPreference preference = (CalendarSelectionPreference) mFragment.findPreference(CalendarExtension.PREF_SELECTED_CALENDARS);
    final List<Pair<String, Boolean>> allCalendars = CalendarExtension.getAllCalendars(this);
    Set<String> allVisibleCalendarsSet = new HashSet<String>();
    for (Pair<String, Boolean> pair : allCalendars) {
        if (pair.second) {
            allVisibleCalendarsSet.add(pair.first);
        }
    }
    Preference.OnPreferenceChangeListener calendarsChangeListener = new Preference.OnPreferenceChangeListener() {

        @Override
        public boolean onPreferenceChange(Preference preference, Object value) {
            int numSelected = 0;
            int numTotal = allCalendars.size();
            try {
                //noinspection check,unchecked
                Set<String> selectedCalendars = (Set<String>) value;
                if (selectedCalendars != null) {
                    numSelected = selectedCalendars.size();
                }
            } catch (ClassCastException ignored) {
            }
            preference.setSummary(getResources().getQuantityString(R.plurals.pref_calendar_selected_summary_template, numTotal, numSelected, numTotal));
            return true;
        }
    };
    preference.setOnPreferenceChangeListener(calendarsChangeListener);
    calendarsChangeListener.onPreferenceChange(preference, PreferenceManager.getDefaultSharedPreferences(this).getStringSet(preference.getKey(), allVisibleCalendarsSet));
}
Example 66
Project: Facebook-Fresco-master  File: ThrottlingProducer.java View source code
@Override
public void produceResults(final Consumer<T> consumer, final ProducerContext producerContext) {
    final ProducerListener producerListener = producerContext.getListener();
    producerListener.onProducerStart(producerContext.getId(), PRODUCER_NAME);
    boolean delayRequest;
    synchronized (this) {
        if (mNumCurrentRequests >= mMaxSimultaneousRequests) {
            mPendingRequests.add(Pair.create(consumer, producerContext));
            delayRequest = true;
        } else {
            mNumCurrentRequests++;
            delayRequest = false;
        }
    }
    if (!delayRequest) {
        produceResultsInternal(consumer, producerContext);
    }
}
Example 67
Project: FanXin2.0_IM-master  File: ThrottlingProducer.java View source code
@Override
public void produceResults(final Consumer<T> consumer, final ProducerContext producerContext) {
    final ProducerListener producerListener = producerContext.getListener();
    producerListener.onProducerStart(producerContext.getId(), PRODUCER_NAME);
    boolean delayRequest;
    synchronized (this) {
        if (mNumCurrentRequests >= mMaxSimultaneousRequests) {
            mPendingRequests.add(Pair.create(consumer, producerContext));
            delayRequest = true;
        } else {
            mNumCurrentRequests++;
            delayRequest = false;
        }
    }
    if (!delayRequest) {
        produceResultsInternal(consumer, producerContext);
    }
}
Example 68
Project: Far-On-Droid-master  File: DropboxDataSource.java View source code
@Override
public void open(final FileProxy file) {
    mHandler.sendEmptyMessage(MSG_NETWORK_SHOW_PROGRESS);
    Extensions.runAsync(new Runnable() {

        @Override
        public void run() {
            try {
                mHandler.sendMessage(mHandler.obtainMessage(MSG_NETWORK_OPEN, new Pair<FileProxy, String>(file, App.sInstance.getDropboxApi().media(file.getFullPath(), false).url)));
            } catch (Exception e) {
                mHandler.sendEmptyMessage(MSG_NETWORK_HIDE_PROGRESS);
            }
        }
    });
}
Example 69
Project: fresco-master  File: ThrottlingProducer.java View source code
@Override
public void produceResults(final Consumer<T> consumer, final ProducerContext producerContext) {
    final ProducerListener producerListener = producerContext.getListener();
    producerListener.onProducerStart(producerContext.getId(), PRODUCER_NAME);
    boolean delayRequest;
    synchronized (this) {
        if (mNumCurrentRequests >= mMaxSimultaneousRequests) {
            mPendingRequests.add(Pair.create(consumer, producerContext));
            delayRequest = true;
        } else {
            mNumCurrentRequests++;
            delayRequest = false;
        }
    }
    if (!delayRequest) {
        produceResultsInternal(consumer, producerContext);
    }
}
Example 70
Project: FxCameraApp-master  File: GlShaderGroup.java View source code
@Override
public void setup() {
    super.setup();
    if (mShaders != null) {
        final int max = mShaders.size();
        int count = 0;
        for (final GlShader shader : mShaders) {
            shader.setup();
            final GLES20FramebufferObject fbo;
            if ((count + 1) < max) {
                fbo = new GLES20FramebufferObject();
            } else {
                fbo = null;
            }
            mList.add(Pair.create(shader, fbo));
            count++;
        }
    }
}
Example 71
Project: Gadgetbridge-master  File: AppMessageHandlerMarioTime.java View source code
private byte[] encodeMarioWeatherMessage(WeatherSpec weatherSpec) {
    if (weatherSpec == null) {
        return null;
    }
    ArrayList<Pair<Integer, Object>> pairs = new ArrayList<>(2);
    pairs.add(new Pair<>(KEY_WEATHER_ICON_ID, (Object) (byte) 1));
    pairs.add(new Pair<>(KEY_WEATHER_TEMPERATURE, (Object) (byte) (weatherSpec.currentTemp - 273)));
    byte[] weatherMessage = mPebbleProtocol.encodeApplicationMessagePush(PebbleProtocol.ENDPOINT_APPLICATIONMESSAGE, mUUID, pairs);
    ByteBuffer buf = ByteBuffer.allocate(weatherMessage.length);
    buf.put(weatherMessage);
    return buf.array();
}
Example 72
Project: GeekBand-Android-1501-Homework-master  File: ThrottlingProducer.java View source code
@Override
public void produceResults(final Consumer<T> consumer, final ProducerContext producerContext) {
    final ProducerListener producerListener = producerContext.getListener();
    producerListener.onProducerStart(producerContext.getId(), PRODUCER_NAME);
    boolean delayRequest;
    synchronized (this) {
        if (mNumCurrentRequests >= mMaxSimultaneousRequests) {
            mPendingRequests.add(Pair.create(consumer, producerContext));
            delayRequest = true;
        } else {
            mNumCurrentRequests++;
            delayRequest = false;
        }
    }
    if (!delayRequest) {
        produceResultsInternal(consumer, producerContext);
    }
}
Example 73
Project: HeartBeat-master  File: LabelCloudFragment.java View source code
public void updateCloud() {
    Map<Long, Integer> allLabels = LabelUtils.getFreq(getActivity());
    List<Pair<String, Integer>> labels = new LinkedList<>();
    if (allLabels != null) {
        ArrayList<Map.Entry<Long, Integer>> list = new ArrayList<>(allLabels.entrySet());
        for (Map.Entry<Long, Integer> label : list) {
            labels.add(new Pair<String, Integer>(LabelUtils.getLabelByLabelId(getActivity(), label.getKey()).getLabel(), label.getValue()));
        }
    }
    if (!labels.isEmpty()) {
        mCloudLayout.setVisibility(View.VISIBLE);
        mEmptyLayout.setVisibility(View.GONE);
        mCloudView.addLabels(labels);
        mCloudView.setOnLabelClickListener(new CloudView.OnLabelClickListener() {

            @Override
            public void onClick(String label) {
                Intent i = new Intent();
                i.setAction(Intent.ACTION_MAIN);
                i.setClass(getActivity(), LabelDetailActivity.class);
                i.putExtra("tag_text", label);
                startActivity(i);
            }
        });
    } else {
        mCloudLayout.setVisibility(View.GONE);
        mEmptyLayout.setVisibility(View.VISIBLE);
        Glide.with(getActivity()).load(R.drawable.empty_bg1).into(mImageEmpty);
    }
}
Example 74
Project: hellocharts-android-master  File: AboutActivity.java View source code
public static Pair<String, Integer> getAppVersionAndBuild(Context context) {
    try {
        PackageInfo pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
        return new Pair<String, Integer>(pInfo.versionName, pInfo.versionCode);
    } catch (Exception e) {
        Log.e(TAG, "Could not get version number");
        return new Pair<String, Integer>("", 0);
    }
}
Example 75
Project: iview-android-tv-master  File: DurationLogger.java View source code
private void executeListeners() {
    long duration = player.getDuration() / 1000;
    long position = player.getCurrentPosition() / 1000;
    List<Pair<Long, OnTimeReached>> executed = new ArrayList<>();
    if (duration > 0 && (state == ExoPlayer.STATE_READY || state == ExoPlayer.STATE_ENDED)) {
        long remain = duration - position;
        for (Pair<Long, OnTimeReached> listener : listeners) {
            long condition = listener.first;
            if (remain <= condition) {
                Log.d(TAG, "Executing listener, duration=" + duration + ", position=" + position + ", remaining=" + remain);
                listener.second.onPositionRemainingReached(duration, position);
                executed.add(listener);
            }
        }
    }
    listeners.removeAll(executed);
}
Example 76
Project: Kv-009-master  File: SerializableUriCookiePair.java View source code
/**
     * Builds a Cookie object from this object.
     */
public Pair<URI, HttpCookie> toCookie() {
    final HttpCookie cookie = new HttpCookie(name, value);
    cookie.setComment(comment);
    //Otherwise null pointer exception
    if (domain != null) {
        cookie.setDomain(domain);
    }
    cookie.setMaxAge(maxAge);
    cookie.setPath(path);
    cookie.setSecure(secure);
    cookie.setVersion(version);
    return new Pair<>(this.uri, cookie);
}
Example 77
Project: Lemniscate-master  File: CurveUtils.java View source code
/**
     * @param start point from which line is drawn
     * @param end point to which line is drawn
     * @param path path on which line is drawn
     * @return  path with line between two points drawn on it
     */
public static Path addPointsToPath(Pair<Float, Float> start, Pair<Float, Float> end, Path path) {
    if (start != null && end != null) {
        path.moveTo(start.first, start.second);
        path.quadTo(start.first, start.second, end.first, end.second);
    } else if (start != null) {
        path.moveTo(start.first, start.second);
        path.lineTo(start.first, start.second);
    } else if (end != null) {
        path.moveTo(end.first, end.second);
    }
    return path;
}
Example 78
Project: limehd_fork-master  File: Limedbtest.java View source code
public void testQuery() {
    LimeDB db = new LimeDB(getContext());
    assertNotNull(db);
    db.setTablename("phonetic");
    buildKeyMap();
    int count = 0;
    int limit = 100;
    long timelimit = 200;
    HashSet<String> duplityCheck = new HashSet<String>();
    Random randomGenerator = new Random();
    while (count < limit) {
        int i = randomGenerator.nextInt(keyList.size());
        int j = randomGenerator.nextInt(keyList.size());
        int k = randomGenerator.nextInt(keyList.size());
        int l = randomGenerator.nextInt(keyList.size());
        String code = keyList.get(i) + keyList.get(j) + keyList.get(k) + keyList.get(l);
        //Log.i(TAG,"code=" + code);
        for (int m = 1; m < 4; m++) {
            String query_code = code.substring(0, m);
            if (duplityCheck.add(query_code)) {
                long begin = System.currentTimeMillis();
                //Log.i(TAG,"query_code="+ query_code);
                Pair<List<Mapping>, List<Mapping>> temp = db.getMapping(query_code, true, true);
                long elapsed = System.currentTimeMillis() - begin;
                int resultsize = 0, relatedsize = 0;
                if (temp.first != null)
                    resultsize = temp.first.size();
                if (temp.second != null)
                    relatedsize = temp.second.size();
                Log.i(TAG, "testQuery(" + count + "):query_code=" + query_code + ", resultlist.size=" + resultsize + ", realtedList.size=" + relatedsize + ", query time=" + elapsed + "ms");
                assertTrue("Qery time longer than " + timelimit + " ms", elapsed < timelimit);
                count++;
            }
        }
    }
}
Example 79
Project: MapAttack-Android-master  File: Installation.java View source code
public static synchronized byte[] getIDAsBytes(Context context) {
    try {
        Pair<Long, Long> uuid = getUUID(context);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DataOutputStream dos = new DataOutputStream(baos);
        dos.writeLong(uuid.first);
        dos.writeLong(uuid.second);
        return baos.toByteArray();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
Example 80
Project: mobilib-master  File: MblPendingCacheMaster.java View source code
@Override
public Runnable get(final List<String> ids, MblGetManyCallback<T> callback) {
    if (MblUtils.isEmpty(ids)) {
        return super.get(ids, callback);
    }
    mPendingRequests.add(new Pair<List<String>, MblGetManyCallback>(ids, callback));
    return new Runnable() {

        @Override
        public void run() {
            mPendingRequests.remove(ids);
        }
    };
}
Example 81
Project: ohmagePhone-master  File: CampaignFilterActivity.java View source code
@Override
public void onContentChanged() {
    super.onContentChanged();
    setLoadingVisibility(true);
    mCampaignFilter = (FilterControl) findViewById(R.id.campaign_filter);
    if (mCampaignFilter == null)
        throw new RuntimeException("Your activity must have a FilterControl with the id campaign_filter");
    mCampaignFilter.setOnChangeListener(new FilterControl.FilterChangeListener() {

        @Override
        public void onFilterChanged(boolean selfChange, String curValue) {
            if (!selfChange)
                onCampaignFilterChanged(curValue);
        }
    });
    mDefaultCampaign = getIntent().getStringExtra(CampaignFilter.EXTRA_CAMPAIGN_URN);
    if (mDefaultCampaign == null)
        mCampaignFilter.add(0, new Pair<String, String>(getString(R.string.filter_all_campaigns), null));
    if (!ConfigHelper.isSingleCampaignMode())
        getSupportLoaderManager().initLoader(CAMPAIGN_LOADER, null, this);
    else {
        setLoadingVisibility(false);
        mCampaignFilter.setVisibility(View.GONE);
    }
}
Example 82
Project: OpenCamera-master  File: NFCHandler.java View source code
public static Pair<String, String> parseIntent(Intent intent) throws Exception {
    Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
    Parcelable[] messages = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
    if (tagFromIntent != null && messages != null) {
        return getCameraWifiSettingsFromTag(tagFromIntent, messages);
    }
    return null;
}
Example 83
Project: Pedometer-master  File: Dialog_Statistics.java View source code
public static Dialog getDialog(final Context c, int since_boot) {
    final Dialog d = new Dialog(c);
    d.requestWindowFeature(Window.FEATURE_NO_TITLE);
    d.setContentView(R.layout.statistics);
    d.findViewById(R.id.close).setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            d.dismiss();
        }
    });
    Database db = Database.getInstance(c);
    Pair<Date, Integer> record = db.getRecordData();
    Calendar date = Calendar.getInstance();
    date.setTimeInMillis(Util.getToday());
    int daysThisMonth = date.get(Calendar.DAY_OF_MONTH);
    date.add(Calendar.DATE, -6);
    int thisWeek = db.getSteps(date.getTimeInMillis(), System.currentTimeMillis()) + since_boot;
    date.setTimeInMillis(Util.getToday());
    date.set(Calendar.DAY_OF_MONTH, 1);
    int thisMonth = db.getSteps(date.getTimeInMillis(), System.currentTimeMillis()) + since_boot;
    ((TextView) d.findViewById(R.id.record)).setText(Fragment_Overview.formatter.format(record.second) + " @ " + java.text.DateFormat.getDateInstance().format(record.first));
    ((TextView) d.findViewById(R.id.totalthisweek)).setText(Fragment_Overview.formatter.format(thisWeek));
    ((TextView) d.findViewById(R.id.totalthismonth)).setText(Fragment_Overview.formatter.format(thisMonth));
    ((TextView) d.findViewById(R.id.averagethisweek)).setText(Fragment_Overview.formatter.format(thisWeek / 7));
    ((TextView) d.findViewById(R.id.averagethismonth)).setText(Fragment_Overview.formatter.format(thisMonth / daysThisMonth));
    db.close();
    return d;
}
Example 84
Project: platform_frameworks_base-master  File: UserTile.java View source code
@Override
protected void handleUpdateState(State state, Object arg) {
    final Pair<String, Drawable> p = arg != null ? (Pair<String, Drawable>) arg : mLastUpdate;
    if (p != null) {
        state.label = p.first;
        // TODO: Better content description.
        state.contentDescription = p.first;
        state.icon = new Icon() {

            @Override
            public Drawable getDrawable(Context context) {
                return p.second;
            }
        };
    } else {
    // TODO: Default state.
    }
}
Example 85
Project: platform_frameworks_support-master  File: ActivityOptionsCompat21.java View source code
public static ActivityOptionsCompat21 makeSceneTransitionAnimation(Activity activity, View[] sharedElements, String[] sharedElementNames) {
    Pair[] pairs = null;
    if (sharedElements != null) {
        pairs = new Pair[sharedElements.length];
        for (int i = 0; i < pairs.length; i++) {
            pairs[i] = Pair.create(sharedElements[i], sharedElementNames[i]);
        }
    }
    return new ActivityOptionsCompat21(ActivityOptions.makeSceneTransitionAnimation(activity, pairs));
}
Example 86
Project: proteus-master  File: PerformanceTracker.java View source code
private Pair<Long, Long> getAverage(List<Long> values) {
    long n = 0;
    long total = 0;
    for (long t : values) {
        total += t;
        n++;
    }
    if (n == 0) {
        n = 1;
    }
    if (values.size() > 0) {
        total = total - values.get(0);
        n = n - 1;
    }
    if (n == 0) {
        n = 1;
    }
    return new Pair<>(total / n, n);
}
Example 87
Project: Pure-File-Manager-master  File: ShellFactory.java View source code
/**
     * Returns new shell
     *
     * @return boolean indicating whether the Shell is root shell and the shell,
     *         or null if timed-out
     * @throws IOException when an IO error occurs
     */
@Nullable
public static Pair<Boolean, Shell> getShell() throws IOException {
    final boolean suEnabled = Settings.getInstance().isSuEnabled();
    try {
        return new Pair<>(suEnabled, RootTools.getShell(suEnabled));
    } catch (RootDeniedExceptionTimeoutException |  e) {
        try {
            return new Pair<>(false, RootTools.getShell(false));
        } catch (RootDeniedException e1) {
            throw new RuntimeException("Access denied for non-superuser shell?", e);
        } catch (TimeoutException e1) {
            return null;
        }
    }
}
Example 88
Project: Qmusic-master  File: QMusicFileRequest.java View source code
private final void writeToFile(QMusicNetworkResponse qResponse) {
    if (qResponse.entity != null) {
        InputStream instream = null;
        try {
            instream = qResponse.entity.getContent();
            if (instream != null) {
                long contentLength = qResponse.entity.getContentLength();
                FileOutputStream buffer = new FileOutputStream(targetFile);
                try {
                    byte[] tmp = new byte[BUFFER_SIZE];
                    int l, count = 0;
                    // do not send messages if request has been cancelled
                    while ((l = instream.read(tmp)) != -1 && !Thread.currentThread().isInterrupted()) {
                        count += l;
                        buffer.write(tmp, 0, l);
                        Pair<Integer, Integer> data = new Pair<Integer, Integer>(count, (int) contentLength);
                        listener.onResponse(data);
                    }
                } finally {
                    AsyncHttpClient.silentCloseInputStream(instream);
                    buffer.flush();
                    AsyncHttpClient.silentCloseOutputStream(buffer);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (instream != null) {
                try {
                    instream.close();
                } catch (Exception ignoreErr) {
                }
            }
        }
    }
}
Example 89
Project: Robin-Client-master  File: CalendarSettingsActivity.java View source code
private void bindSelectedCalendarsPreference() {
    CalendarSelectionPreference preference = (CalendarSelectionPreference) findPreference(CalendarExtension.PREF_SELECTED_CALENDARS);
    final List<Pair<String, Boolean>> allCalendars = CalendarExtension.getAllCalendars(this);
    Set<String> allVisibleCalendarsSet = new HashSet<String>();
    for (Pair<String, Boolean> pair : allCalendars) {
        if (pair.second) {
            allVisibleCalendarsSet.add(pair.first);
        }
    }
    Preference.OnPreferenceChangeListener calendarsChangeListener = new Preference.OnPreferenceChangeListener() {

        @Override
        public boolean onPreferenceChange(Preference preference, Object value) {
            int numSelected = 0;
            int numTotal = allCalendars.size();
            try {
                //noinspection check,unchecked
                Set<String> selectedCalendars = (Set<String>) value;
                if (selectedCalendars != null) {
                    numSelected = selectedCalendars.size();
                }
            } catch (ClassCastException ignored) {
            }
            preference.setSummary(getResources().getQuantityString(R.plurals.pref_calendar_selected_summary_template, numTotal, numSelected, numTotal));
            return true;
        }
    };
    preference.setOnPreferenceChangeListener(calendarsChangeListener);
    calendarsChangeListener.onPreferenceChange(preference, PreferenceManager.getDefaultSharedPreferences(this).getStringSet(preference.getKey(), allVisibleCalendarsSet));
}
Example 90
Project: runner-master  File: HRZonesListAdapter.java View source code
@Override
public Object getItem(int position) {
    if (position == lastPosition)
        return lastString;
    if (position < hrZones.getCount()) {
        Pair<Integer, Integer> val = hrZones.getHRValues(position + 1);
        String str = "Zone " + (position + 1) + " (" + val.first + " - " + val.second + ")";
        lastPosition = position;
        lastString = str;
        return str;
    }
    return null;
}
Example 91
Project: runnerup-master  File: HRZonesListAdapter.java View source code
@Override
public Object getItem(int position) {
    if (position == lastPosition)
        return lastString;
    if (position < hrZones.getCount()) {
        Pair<Integer, Integer> val = hrZones.getHRValues(position + 1);
        String str = "Zone " + (position + 1) + " (" + val.first + " - " + val.second + ")";
        lastPosition = position;
        lastString = str;
        return str;
    }
    return null;
}
Example 92
Project: schnitzeljagd-master  File: EntryActivity.java View source code
@Override
@TargetApi(Build.VERSION_CODES.M)
public void onRequestPermissionsResult(int requestCode, String[] permissionStrings, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissionStrings, grantResults);
    List<Pair<String, Integer>> permissions = ArrayUtil.mapArrayToPairList(permissionStrings, IntStreams.of(grantResults).boxed().toArray(Integer[]::new));
    List<String> denied = new ArrayList<>();
    for (Pair<String, Integer> permission : permissions) {
        if (permission.second == PackageManager.PERMISSION_DENIED) {
            denied.add(permission.first);
        }
    }
    if (denied.size() >= 1) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Please grant this app all needed permissions").setCancelable(false).setNeutralButton("Ok", ( dialog,  which) -> {
            requestPermissions(denied.toArray(new String[denied.size()]), PERMISSION_REQUEST_CODE);
        });
        AlertDialog error = builder.create();
        error.show();
    } else {
        accessGranted();
    }
}
Example 93
Project: servos-master  File: CalendarUtilsTest.java View source code
@Test
public void itShouldReturnOrdinalDayOfMonth() {
    Calendar cal = Calendar.getInstance();
    cal.setTime(new Date());
    Pair<Integer, String>[] ordinalTests = new Pair[] { Pair.create(1, "1st"), Pair.create(2, "2nd"), Pair.create(3, "3rd"), Pair.create(4, "4th"), Pair.create(11, "11th"), Pair.create(21, "21st"), Pair.create(22, "22nd"), Pair.create(23, "23rd"), Pair.create(24, "24th") };
    for (Pair<Integer, String> ordinalTest : ordinalTests) {
        cal.set(Calendar.DAY_OF_MONTH, ordinalTest.first);
        assertThat(CalendarUtils.getOrdinalDayOfMonth(cal)).isEqualTo(ordinalTest.second);
        assertThat(CalendarUtils.getOrdinalDayOfMonth(cal.getTime())).isEqualTo(ordinalTest.second);
    }
}
Example 94
Project: Signal-Android-master  File: MmsReceiveJob.java View source code
@Override
public void onRun() {
    if (data == null) {
        Log.w(TAG, "Received NULL pdu, ignoring...");
        return;
    }
    PduParser parser = new PduParser(data);
    GenericPdu pdu = null;
    try {
        pdu = parser.parse();
    } catch (RuntimeException e) {
        Log.w(TAG, e);
    }
    if (isNotification(pdu) && !isBlocked(pdu)) {
        MmsDatabase database = DatabaseFactory.getMmsDatabase(context);
        Pair<Long, Long> messageAndThreadId = database.insertMessageInbox((NotificationInd) pdu, subscriptionId);
        Log.w(TAG, "Inserted received MMS notification...");
        ApplicationContext.getInstance(context).getJobManager().add(new MmsDownloadJob(context, messageAndThreadId.first, messageAndThreadId.second, true));
    } else if (isNotification(pdu)) {
        Log.w(TAG, "*** Received blocked MMS, ignoring...");
    }
}
Example 95
Project: Silence-master  File: MmsReceiveJob.java View source code
@Override
public void onRun() {
    if (data == null) {
        Log.w(TAG, "Received NULL pdu, ignoring...");
        return;
    }
    PduParser parser = new PduParser(data);
    GenericPdu pdu = null;
    try {
        pdu = parser.parse();
    } catch (RuntimeException e) {
        Log.w(TAG, e);
    }
    if (isNotification(pdu) && !isBlocked(pdu)) {
        MmsDatabase database = DatabaseFactory.getMmsDatabase(context);
        Pair<Long, Long> messageAndThreadId = database.insertMessageInbox((NotificationInd) pdu, subscriptionId);
        MasterSecret masterSecret = KeyCachingService.getMasterSecret(context);
        Log.w(TAG, "Inserted received MMS notification...");
        database.markIncomingNotificationReceived(messageAndThreadId.second);
        if (!SilencePreferences.isMediaDownloadAllowed(context))
            MessageNotifier.updateNotification(context, masterSecret, messageAndThreadId.second);
        ApplicationContext.getInstance(context).getJobManager().add(new MmsDownloadJob(context, messageAndThreadId.first, messageAndThreadId.second, true));
    } else if (isNotification(pdu)) {
        Log.w(TAG, "*** Received blocked MMS, ignoring...");
    }
}
Example 96
Project: SketchView-master  File: SketchManager.java View source code
public static HashMap<Pair<Integer, Integer>, Paint> createBrushes(Resources r) {
    HashMap<Pair<Integer, Integer>, Paint> brushes = new HashMap<Pair<Integer, Integer>, Paint>();
    ArrayList<SkColor> colors = SkColor.getColors(r);
    ArrayList<SkSize> sizes = SkSize.getSizes(r);
    for (int i = 0, len = sizes.size(); i < len; i++) {
        for (int j = 0, max = colors.size(); j < max; j++) {
            int color = r.getColor(colors.get(j).getColorResourceId());
            int size = sizes.get(i).getSize();
            Paint paint = createBrush(color, size);
            brushes.put(new Pair<Integer, Integer>(color, size), paint);
        }
    }
    return brushes;
}
Example 97
Project: slide-master  File: HttpPostTask.java View source code
/**
	 * params come in pairs: key/value
	 */
@Override
protected Result doInBackground(String... params) {
    List<Pair<String, String>> nvps = getPostArgs(params);
    MultipartBody.Builder formBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM);
    for (Pair<String, String> p : nvps) {
        formBuilder.addFormDataPart(p.first, p.second);
    }
    Request request = new Request.Builder().url(mUrl).header("User-Agent", getUserAgent()).addHeader("Content-Encoding", "gzip").post(formBuilder.build()).build();
    try {
        Response res = mClient.newCall(request).execute();
        if (!res.isSuccessful()) {
            throw new IOException("Unexpected code " + res);
        }
        return onInput(res.body().string());
    } catch (Exception ex) {
        Log.e(TAG, "Error during POST", ex);
    }
    return null;
}
Example 98
Project: tangiblexml-master  File: TangibleNode.java View source code
@Override
public void parse(@NonNull XmlPullParser xml, @NonNull T target) throws InputException, InvalidFieldException, ValueCountException, ConversionException, NotSupportedException, ReflectionException {
    if (Parser.debug) {
        Log.d(TAG, "trying to parse " + what.getSimpleName() + " from " + xml.getName());
    }
    final V result;
    try {
        result = what.newInstance();
    } catch (InstantiationException e) {
        throw new ReflectionException("Failed to create instance of " + what.getName(), e);
    } catch (IllegalAccessException e) {
        throw new ReflectionException("Failed to create instance of " + what.getName(), e);
    }
    valueRoot.parse(xml, result);
    TangibleFieldCache cache = TangibleFieldCache.getInstance();
    try {
        for (Pair<Field, TangibleField> pair : cache.get(result.getClass())) {
            Field f = pair.first;
            TangibleField a = pair.second;
            if (a.required() && f.get(result) == null) {
                String msg = "Required field '" + f + "' missing";
                throw new ValueCountException(msg);
            }
        }
    } catch (IllegalAccessException e) {
        throw new ReflectionException(e);
    }
    putter.put(target, result);
}
Example 99
Project: TextSecureSMP-master  File: MediaConstraints.java View source code
public boolean isWithinBounds(Context context, MasterSecret masterSecret, Uri uri) throws IOException {
    InputStream is = PartAuthority.getPartStream(context, masterSecret, uri);
    Pair<Integer, Integer> dimensions = BitmapUtil.getDimensions(is);
    return dimensions.first > 0 && dimensions.first <= getImageMaxWidth(context) && dimensions.second > 0 && dimensions.second <= getImageMaxHeight(context);
}
Example 100
Project: timelapse-sony-master  File: NFCHandler.java View source code
public static Pair<String, String> parseIntent(Intent intent) throws Exception {
    Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
    Parcelable[] messages = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
    if (tagFromIntent != null && messages != null) {
        return getCameraWifiSettingsFromTag(tagFromIntent, messages);
    }
    return null;
}
Example 101
Project: understand-plugin-framework-master  File: IActivityManagerHandler.java View source code
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    if ("startService".equals(method.getName())) {
        // �拦截这个方法
        // API 23:
        // public ComponentName startService(IApplicationThread caller, Intent service,
        //        String resolvedType, int userId) throws RemoteException
        // 找到�数里�的第一个Intent 对象
        Pair<Integer, Intent> integerIntentPair = foundFirstIntentOfArgs(args);
        Intent newIntent = new Intent();
        // 代ç?†Service的包å??, 也就是我们自己的包å??
        String stubPackage = UPFApplication.getContext().getPackageName();
        // 这里我们把�动的Service替�为ProxyService, 让ProxyService接收生命周期回调
        ComponentName componentName = new ComponentName(stubPackage, ProxyService.class.getName());
        newIntent.setComponent(componentName);
        // 把我们原始��动的TargetService先存起�
        newIntent.putExtra(AMSHookHelper.EXTRA_TARGET_INTENT, integerIntentPair.second);
        // 替�掉Intent, 达到欺骗AMS的目的
        args[integerIntentPair.first] = newIntent;
        Log.v(TAG, "hook method startService success");
        return method.invoke(mBase, args);
    }
    // String resolvedType, int userId) throws RemoteException
    if ("stopService".equals(method.getName())) {
        Intent raw = foundFirstIntentOfArgs(args).second;
        if (!TextUtils.equals(UPFApplication.getContext().getPackageName(), raw.getComponent().getPackageName())) {
            // �件的intent��hook
            Log.v(TAG, "hook method stopService success");
            return ServiceManager.getInstance().stopService(raw);
        }
    }
    return method.invoke(mBase, args);
}