Java Code Examples for android.util.Pair

The following are top voted examples for showing how to use android.util.Pair. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: GitHub   File: RequestLoggingListener.java   View source code 6 votes vote down vote up
@Override
public synchronized void onProducerFinishWithCancellation(
    String requestId,
    String producerName,
    @Nullable Map<String, String> extraMap) {
  if (FLog.isLoggable(FLog.VERBOSE)) {
    Pair<String, String> mapKey = Pair.create(requestId, producerName);
    Long startTime = mProducerStartTimeMap.remove(mapKey);
    long currentTime = getTime();
    FLog.v(
        TAG,
        "time %d: onProducerFinishWithCancellation: " +
            "{requestId: %s, stage: %s, elapsedTime: %d ms, extraMap: %s}",
        currentTime,
        requestId,
        producerName,
        getElapsedTime(startTime, currentTime),
        extraMap);
  }
}
 
Example 2
Project: Cable-Android   File: ConversationActivity.java   View source code 6 votes vote down vote up
@Override
public void onRecorderCanceled() {
  Vibrator vibrator = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
  vibrator.vibrate(50);
  getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

  ListenableFuture<Pair<Uri, Long>> future = audioRecorder.stopRecording();
  future.addListener(new ListenableFuture.Listener<Pair<Uri, Long>>() {
    @Override
    public void onSuccess(final Pair<Uri, Long> result) {
      new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... params) {
          PersistentBlobProvider.getInstance(ConversationActivity.this).delete(result.first);
          return null;
        }
      }.execute();
    }

    @Override
    public void onFailure(ExecutionException e) {}
  });
}
 
Example 3
Project: kognitivo   File: FacebookContentProvider.java   View source code 6 votes vote down vote up
@Override
public android.os.ParcelFileDescriptor openFile(android.net.Uri uri, java.lang.String mode)
        throws java.io.FileNotFoundException {

    Pair<UUID, String> callIdAndAttachmentName = parseCallIdAndAttachmentName(uri);
    if (callIdAndAttachmentName == null) {
        throw new FileNotFoundException();
    }

    try {
        File file = NativeAppCallAttachmentStore.openAttachment(
                callIdAndAttachmentName.first,
                callIdAndAttachmentName.second);

        return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
    } catch (FileNotFoundException exception) {
        Log.e(TAG, "Got unexpected exception:" + exception);
        throw exception;
    }
}
 
Example 4
Project: revolution-irc   File: ShareTargetActivity.java   View source code 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mAdapter = new ChannelSearchDialog.SuggestionsAdapter(this);
    ListSearchView view = new ListSearchView(this, this);
    view.setBackgroundColor(StyledAttributesHelper.getColor(this, R.attr.colorBackgroundFloating, 0));
    view.setSuggestionsAdapter(mAdapter);
    setContentView(view);

    mAdapter.setItemClickListener((int index, Pair<ServerConnectionInfo, String> value) -> {
        Intent intent = new Intent(this, MainActivity.class);
        intent.putExtra(MainActivity.ARG_SERVER_UUID, value.first.getUUID().toString());
        intent.putExtra(MainActivity.ARG_CHANNEL_NAME, value.second);
        intent.putExtra(Intent.EXTRA_TEXT, getIntent().getStringExtra(Intent.EXTRA_TEXT));
        intent.setAction(Intent.ACTION_SEND);
        intent.setType("text/plain");
        startActivity(intent);
        overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
        finish();
    });
}
 
Example 5
Project: Saiy-PS   File: CustomCommandHelper.java   View source code 6 votes vote down vote up
/**
 * Insert a new {@link CustomCommand} in the {@link DBCustomCommand} synchronising with a basic
 * lock object in a vain attempt to prevent concurrency issues.
 *
 * @param ctx           the application context
 * @param customCommand to be set
 * @return true if the insertion was successful
 */
public static Pair<Boolean, Long> setCommand(@NonNull final Context ctx, @NonNull final CustomCommand customCommand,
                                             final long rowId) {

    synchronized (lock) {

        final Gson gson = new GsonBuilder().disableHtmlEscaping().create();
        final String gsonString = gson.toJson(customCommand);

        final DBCustomCommand dbCustomCommand = new DBCustomCommand(ctx);

        final Pair<Boolean, Long> duplicatePair;
        if (rowId > -1) {
            duplicatePair = new Pair<>(true, rowId);
        } else {
            duplicatePair = commandExists(dbCustomCommand, customCommand);
        }

        return dbCustomCommand.insertPopulatedRow(customCommand.getKeyphrase(),
                customCommand.getRegex(), gsonString, duplicatePair.first, duplicatePair.second);
    }
}
 
Example 6
Project: EasyFirebase   File: EasyFirebaseAuth.java   View source code 6 votes vote down vote up
public EasyFirebaseAuth(GoogleApiClient googleApiClient) {
    mAuth = FirebaseAuth.getInstance();
    this.googleApiClient = googleApiClient;

    mAuthListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            final FirebaseUser user = firebaseAuth.getCurrentUser();
            if (user != null) {
                if (firebaseUserSubscriber != null) {
                    firebaseUserSubscriber.onNext(new Pair<GoogleSignInAccount, FirebaseUser>(googleSignInAccount, user));
                    firebaseUserSubscriber.onCompleted();
                }
                if (loggedSubcriber != null) {
                    loggedSubcriber.onNext(user);
                }
                // User is signed in
                Log.d("TAG", "onAuthStateChanged:signed_in:" + user.getUid());
            } else {
                // User is signed out
                Log.d("TAG", "onAuthStateChanged:signed_out");
            }
        }
    };
}
 
Example 7
Project: GitHub   File: EncodedImage.java   View source code 6 votes vote down vote up
/**
 * We get the size from a generic image
 */
private Pair<Integer, Integer> readImageSize() {
  InputStream inputStream = null;
  Pair<Integer, Integer> dimensions = null;
  try {
    inputStream = getInputStream();
    dimensions = BitmapUtil.decodeDimensions(inputStream);
    if (dimensions != null) {
      mWidth = dimensions.first;
      mHeight = dimensions.second;
    }
  }finally {
    if (inputStream != null) {
      try {
        inputStream.close();
      } catch (IOException e) {
        // Head in the sand
      }
    }
  }
  return dimensions;
}
 
Example 8
Project: AndroidBackendlessChat   File: NativeAppCallContentProvider.java   View source code 6 votes vote down vote up
Pair<UUID, String> parseCallIdAndAttachmentName(Uri uri) {
    try {
        // We don't do explicit format checking here. Malformed URIs may generate NullPointerExceptions or
        // array bounds exceptions, which we'll catch and return null. All of these will result in a
        // FileNotFoundException being thrown in openFile.
        String callIdAndAttachmentName = uri.getPath().substring(1);
        String [] parts = callIdAndAttachmentName.split("/");

        String callIdString = parts[0];
        String attachmentName = parts[1];
        UUID callId = UUID.fromString(callIdString);

        return new Pair<UUID, String>(callId, attachmentName);
    } catch (Exception exception) {
        return null;
    }
}
 
Example 9
Project: GitHub   File: BaseDao.java   View source code 6 votes vote down vote up
public boolean deleteList(List<Pair<String, String[]>> where) {
    long start = System.currentTimeMillis();
    lock.lock();
    try {
        database.beginTransaction();
        for (Pair<String, String[]> pair : where) {
            database.delete(getTableName(), pair.first, pair.second);
        }
        database.setTransactionSuccessful();
        return true;
    } catch (Exception e) {
        OkLogger.printStackTrace(e);
    } finally {
        database.endTransaction();
        lock.unlock();
        OkLogger.v(TAG, System.currentTimeMillis() - start + " deleteList");
    }
    return false;
}
 
Example 10
Project: ucar-weex-core   File: WXAnimationBean.java   View source code 6 votes vote down vote up
private static Pair<Float, Float> parsePivot(@Nullable String transformOrigin,
                                             int width, int height,int viewportW) {
  if (!TextUtils.isEmpty(transformOrigin)) {
    int firstSpace = transformOrigin.indexOf(FunctionParser.SPACE);
    if (firstSpace != -1) {
      int i = firstSpace;
      for (; i < transformOrigin.length(); i++) {
        if (transformOrigin.charAt(i) != FunctionParser.SPACE) {
          break;
        }
      }
      if (i < transformOrigin.length() && transformOrigin.charAt(i) != FunctionParser.SPACE) {
        List<String> list = new ArrayList<>(2);
        list.add(transformOrigin.substring(0, firstSpace).trim());
        list.add(transformOrigin.substring(i, transformOrigin.length()).trim());
        return parsePivot(list, width, height,viewportW);
      }
    }
  }
  return null;
}
 
Example 11
Project: KTalk   File: EaseConversationListFragment.java   View source code 5 votes vote down vote up
/**
 * load conversation list
 * 
 * @return
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    +    */
protected List<EMConversation> loadConversationList(){
    // get all conversations
    Map<String, EMConversation> conversations = EMClient.getInstance().chatManager().getAllConversations();
    List<Pair<Long, EMConversation>> sortList = new ArrayList<Pair<Long, EMConversation>>();
    /**
     * lastMsgTime will change if there is new message during sorting
     * so use synchronized to make sure timestamp of last message won't change.
     */
    synchronized (conversations) {
        for (EMConversation conversation : conversations.values()) {
            if (conversation.getAllMessages().size() != 0) {
                sortList.add(new Pair<Long, EMConversation>(conversation.getLastMessage().getMsgTime(), conversation));
            }
        }
    }
    try {
        // Internal is TimSort algorithm, has bug
        sortConversationByLastChatTime(sortList);
    } catch (Exception e) {
        e.printStackTrace();
    }
    List<EMConversation> list = new ArrayList<EMConversation>();
    for (Pair<Long, EMConversation> sortItem : sortList) {
        list.add(sortItem.second);
    }
    return list;
}
 
Example 12
Project: tiny   File: BitmapKit.java   View source code 5 votes vote down vote up
public static Pair<Integer, Integer> decodeDimensions(FileDescriptor fd) {
    if (fd == null)
        return null;
    BitmapFactory.Options options = CompressKit.getDefaultDecodeBoundsOptions();
    BitmapFactory.decodeFileDescriptor(fd, null, options);
    return (options.outWidth == -1 || options.outHeight == -1) ?
            null : Pair.create(options.outWidth, options.outHeight);
}
 
Example 13
Project: Fatigue-Detection   File: DynamicStickerBase.java   View source code 5 votes vote down vote up
public DynamicStickerBase(DstickerDataBean parama, String paramString1, String paramString2, String paramString3) {
    super(paramString2, paramString3);
    this.cE = paramString1;
    this.cF = parama;
    this.bh = this.cF.name;

    String str = this.cE.substring("file://".length());
    Pair localPair = MResFileReaderBase.tryGetMergeFile(str);
    if (null != localPair) {
        this.cG = new MResFileIndexReader(str + "/" + (String) localPair.first, str + "/" + (String) localPair.second);
    }
}
 
Example 14
Project: https-github.com-hyb1996-NoRootScriptDroid   File: InjectableWebClient.java   View source code 5 votes vote down vote up
@Override
public void onPageFinished(WebView view, String url) {
    mWebView = view;
    setUpWebView(view);
    while (!mToInjectJavaScripts.isEmpty()) {
        Pair<String, ValueCallback<String>> pair = mToInjectJavaScripts.poll();
        inject(view, pair.first, pair.second);
    }
    super.onPageFinished(view, url);
}
 
Example 15
Project: Phial   File: HomeActivity.java   View source code 5 votes vote down vote up
private void showFragmentById(int id) {
    final Class<? extends Fragment> target = FRAGMENTS.get(id);

    final Fragment fragment = Fragment.instantiate(this, target.getName());

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        setupFragmentTransition(fragment);
    }

    final FragmentTransaction transaction = getSupportFragmentManager().beginTransaction()
            .replace(R.id.content_frame, fragment);

    for (Pair<View, String> sharedElement : sharedElements) {
        transaction.addSharedElement(sharedElement.first, sharedElement.second);
    }

    sharedElements = new ArrayList<>();

    transaction.commit();
}
 
Example 16
Project: starcor.xul   File: XulBindingSelector.java   View source code 5 votes vote down vote up
@Override
boolean apply(IXulDataSelectContext dataCtx, ArrayList<XulDataNode> ctx) {
	HashSet<Integer> keepPositions = new HashSet<Integer>();

	int orgSize = ctx.size();
	for (int i1 = 0; i1 < _ranges.size(); i1++) {
		Pair<Integer, Integer> range = _ranges.get(i1);
		int begin = range.first;
		int end = range.second;
		if (begin < 0) {
			begin += orgSize;
		}
		if (end < 0) {
			end += orgSize;
		}
		if (end < 0 || begin < 0) {
			// invalid range
			continue;
		}
		if (end > orgSize) {
			end = orgSize;
		}
		for (int i = begin; i <= end; ++i) {
			keepPositions.add(i);
		}
	}
	while (orgSize > 0) {
		--orgSize;
		if (!keepPositions.contains(orgSize)) {
			ctx.remove(orgSize);
		}
	}
	return true;
}
 
Example 17
Project: OpenYOLO-Android   File: CollectionConverter.java   View source code 5 votes vote down vote up
/**
 * Converts all the values in the provided collection, and adds them to a new map.
 */
@NonNull
public static <T, U, V> Map<U, V> toMap(
        @Nullable Collection<T> values,
        @NonNull ValueConverter<T, Pair<U, V>> valueConverter) {
    if (values == null) {
        return Collections.emptyMap();
    }

    Map<U, V> result = createMap(values.size());
    for (T value : values) {
        Pair<U, V> converted = valueConverter.convert(value);
        result.put(converted.first, converted.second);
    }

    return result;
}
 
Example 18
Project: RecyclerViewInjectorAdapter   File: RecyclerViewInjectorAdapterAndroidTest.java   View source code 5 votes vote down vote up
private List<String> getChildAdapterDataStringList(List<Pair<String, Integer>> list) {
    List<String> result = new ArrayList<>(list.size());
    for (Pair<String, Integer> item : list) {
        result.add(item.first);
    }
    return result;
}
 
Example 19
Project: Mire   File: ActivitySetWallpapers.java   View source code 5 votes vote down vote up
private void OnWallpaperLoaded(final Palette palette)
{
       progress.setVisibility(View.GONE);
	apply.startAnimation(anim);
	apply.setVisibility(View.VISIBLE);
	
	apply.setImageDrawable(DrawableHelper.getTintedDrawable(ActivitySetWallpapers.this, R.drawable.ic_more_vert_accent_24dp, MirePaletteUtils.getColor(palette, Preferences.getAttributeColor(ActivitySetWallpapers.this, R.attr.colorAccent))));
	apply.setOnClickListener(new View.OnClickListener()
	{
		@Override
		public void onClick(View view)
		{
			final int defaultColor = Preferences.getAttributeColor(ActivitySetWallpapers.this, R.attr.colorAccent);
			final int colorInt = MirePaletteUtils.getColor(palette, defaultColor);
			
			Intent intent = new Intent(ActivitySetWallpapers.this, ActivityDialogWallpaperChoiceOptions.class);
			intent.putExtra(URL, image);
			intent.putExtra(NAME, title);
			intent.putExtra(TEXT, text);
			intent.putExtra(COLOR, colorInt);

			int src = DrawableHelper.getDrawableInt(ActivitySetWallpapers.this, R.drawable.ic_more_vert_accent_24dp, MirePaletteUtils.getColor(palette, Preferences.getAttributeColor(ActivitySetWallpapers.this, R.attr.colorAccent))); // Does not Work :'(
			CircularRevealTransformEnter.addExtras(intent, src);
			
			Pair<View, String> pair = (Pair<View, String>)Pair.create((View)findViewById(R.id.id_apply), "transition_dialog");

			ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(ActivitySetWallpapers.this, pair);

			startActivity(intent, options.toBundle());
		}
	});
   }
 
Example 20
Project: Saiy-PS   File: Hotword.java   View source code 5 votes vote down vote up
/**
 * Used by the {@link Callable} in {@link Callable#call()}
 *
 * @return an array list containing {@link Pair} of {@link CC} and {@link Float} confidence scores
 */
public ArrayList<Pair<CC, Float>> detectCallable() {

    switch (sl) {

        case ENGLISH:
            return ((Hotword_en) hotword).detectCallable();
        case ENGLISH_US:
            return ((Hotword_en) hotword).detectCallable();
        default:
            return ((Hotword_en) hotword).detectCallable();
    }
}
 
Example 21
Project: atlas   File: BundleInstaller.java   View source code 5 votes vote down vote up
public static void startDelayInstall(final String location,InstallListener listener)
{
    createIdleInstallerIfNeed();
    if(location!=null){
        BundleImpl impl = (BundleImpl)Atlas.getInstance().getBundle(location);
        if(impl==null || !impl.checkValidate()){
            sDelayInstallBundles.add(new Pair<String, InstallListener>(location,listener));
        }
    }
}
 
Example 22
Project: chromium-net-for-android   File: CronetHttpURLConnection.java   View source code 5 votes vote down vote up
/**
 * Returns the index of request header in {@link #mRequestHeaders} or
 * -1 if not found.
 */
private int findRequestProperty(String key) {
    for (int i = 0; i < mRequestHeaders.size(); i++) {
        Pair<String, String> entry = mRequestHeaders.get(i);
        if (entry.first.equalsIgnoreCase(key)) {
            return i;
        }
    }
    return -1;
}
 
Example 23
Project: streaminglib   File: RtpStream.java   View source code 5 votes vote down vote up
public void configureUdp(Pair<Integer, Integer> remoteRtpPorts, InetAddress host) throws IllegalStateException {
    validateState(RtpStreamState.CONFIGURED, RtpStreamState.INITIALIZED);
    validateRtpProtocol(RtpProtocol.UDP);
    this.remoteRtpPorts = remoteRtpPorts;

    rtpPacket = new DatagramPacket(new byte[]{}, 0, host, remoteRtpPorts.first);
    rtcpPacket = new DatagramPacket(new byte[]{}, 0, host, remoteRtpPorts.second);

    state = RtpStreamState.CONFIGURED;

    startListening();
}
 
Example 24
Project: AOSP-Kayboard-7.1.2   File: EmojiCategory.java   View source code 5 votes vote down vote up
public Pair<Integer, Integer> getCategoryIdAndPageIdFromPagePosition(final int position) {
    int sum = 0;
    for (final CategoryProperties properties : mShownCategories) {
        final int temp = sum;
        sum += properties.mPageCount;
        if (sum > position) {
            return new Pair<>(properties.mCategoryId, position - temp);
        }
    }
    return null;
}
 
Example 25
Project: SimpleRssReader   File: RoundedCornersBackgroundSpan.java   View source code 5 votes vote down vote up
private RoundedCornersBackgroundSpan(@NonNull Builder builder) {
    mPaint.setAntiAlias(true);
    mRadius = builder.mRadius;
    mPadding = builder.mPadding;
    mSeparatorWidth = builder.mSeparatorWidth;
    mTextAlignment = builder.mTextAlignment;
    for (final Pair<CharSequence, BackgroundHolder> textPart : builder.mTextParts) {
        if (textPart.second != null) {
            mBackgroundHolders.add(textPart.second);
        }
    }
    final char firstChar = builder.mTextParts.get(0).first.charAt(0);
    mRtlText = firstChar >= 0x5D0 && firstChar <= 0x6ff;
}
 
Example 26
Project: Exoplayer2Radio   File: AtomParsers.java   View source code 5 votes vote down vote up
/**
 * Parses encryption data from an audio/video sample entry, populating {@code out} and returning
 * the unencrypted atom type, or 0 if no common encryption sinf atom was present.
 */
private static int parseSampleEntryEncryptionData(ParsableByteArray parent, int position,
    int size, StsdData out, int entryIndex) {
  int childPosition = parent.getPosition();
  while (childPosition - position < size) {
    parent.setPosition(childPosition);
    int childAtomSize = parent.readInt();
    Assertions.checkArgument(childAtomSize > 0, "childAtomSize should be positive");
    int childAtomType = parent.readInt();
    if (childAtomType == Atom.TYPE_sinf) {
      Pair<Integer, TrackEncryptionBox> result = parseSinfFromParent(parent, childPosition,
          childAtomSize);
      if (result != null) {
        out.trackEncryptionBoxes[entryIndex] = result.second;
        return result.first;
      }
    }
    childPosition += childAtomSize;
  }
  // This enca/encv box does not have a data format so return an invalid atom type.
  return 0;
}
 
Example 27
Project: Saiy-PS   File: BVCredentials.java   View source code 5 votes vote down vote up
/**
 * Convenience method to check if the most recent access token remains valid and automatically
 * request one if required.
 *
 * @param ctx    the application context
 * @param apiKey the API key
 * @return an {@link Pair} of which the first parameter will denote success and the second an
 * {@link BVCredentials} object, containing the token credentials. If the request was unsuccessful,
 * the second parameter may be null.
 */
public static Pair<Boolean, BVCredentials> refreshTokenIfRequired(@NonNull final Context ctx,
                                                                  @NonNull final String apiKey) {
    final BVCredentials bvCredentials = getLastToken(ctx);

    if (isTokenValid(bvCredentials)) {
        return new Pair<>(true, bvCredentials);
    } else {
        return new BVAuthRequest(ctx.getApplicationContext(), apiKey).getToken();
    }
}
 
Example 28
Project: RIBs   File: LoggedOutView.java   View source code 5 votes vote down vote up
@Override
public Observable<Pair<String, String>> playerNames() {
  return RxView.clicks(findViewById(R.id.login_button))
      .map(
          new Function<Object, Pair<String, String>>() {
            @Override
            public Pair<String, String> apply(Object irrelevant) throws Exception {
              return new Pair<>(
                  playerOneEditText.getText().toString(), playerTwoEditText.getText().toString());
            }
          });
}
 
Example 29
Project: weex-uikit   File: WXAnimationBean.java   View source code 5 votes vote down vote up
private static Pair<Float, Float> parsePivot(@Nullable String transformOrigin,
                                             int width, int height,int viewportW) {
  if (!TextUtils.isEmpty(transformOrigin)) {
    int firstSpace = transformOrigin.indexOf(FunctionParser.SPACE);
    if (firstSpace != -1) {
      int i = firstSpace;
      for (; i < transformOrigin.length(); i++) {
        if (transformOrigin.charAt(i) != FunctionParser.SPACE) {
          break;
        }
      }
      if (i < transformOrigin.length() && transformOrigin.charAt(i) != FunctionParser.SPACE) {
        List<String> list = new ArrayList<>(2);
        list.add(transformOrigin.substring(0, firstSpace).trim());
        list.add(transformOrigin.substring(i, transformOrigin.length()).trim());
        return parsePivot(list, width, height,viewportW);
      }
    }
  }
  return parsePivot(Arrays.asList(WXAnimationBean.Style.CENTER,
                                  WXAnimationBean.Style.CENTER), width, height,viewportW);
}
 
Example 30
Project: prebid-mobile-android   File: BidManagerTest.java   View source code 5 votes vote down vote up
@Test
public void testKeywordString() throws Exception {
    //Registering a list of adUnits test
    ArrayList<BidResponse> bids = new ArrayList<>();
    BidResponse testBid = new BidResponse(TestConstants.cpm3, ServerResponses.ut_url);
    testBid.addCustomKeyword("pb_cache_id", "14y3834yq5iu5");
    testBid.addCustomKeyword("hb_pb", "0.54");
    testBid.addCustomKeyword("hb_bidder", "mock_bidder");
    bids.add(testBid);
    MockServer.addTestSetup(TestConstants.configID1, bids);
    ArrayList<AdUnit> adUnits = new ArrayList<AdUnit>();
    adUnits.add(adUnit1);
    Prebid.init(activity.getApplicationContext(), adUnits, TestConstants.accountId);
    Robolectric.flushBackgroundThreadScheduler();
    Robolectric.flushForegroundThreadScheduler();
    ArrayList<Pair<String, String>> keywords = BidManager.getKeywordsForAdUnit(adUnit1.getCode(), activity.getApplicationContext());
    for (Pair keywordPair : keywords) {
        if ("pb_cache_id".equals(keywordPair.first)) {
            assertEquals("14y3834yq5iu5", keywordPair.second);
        } else if ("hb_pb".equals(keywordPair.first)) {
            assertEquals("0.54", keywordPair.second);
        } else if ("hb_bidder".equals(keywordPair.first)) {
            assertEquals("mock_bidder", keywordPair.second);
        }
    }
}
 
Example 31
Project: revolution-irc   File: ChannelSearchDialog.java   View source code 5 votes vote down vote up
@Override
public void bind(Pair<ServerConnectionInfo, String> item) {
    String name = item.first.getName();
    String channel = item.second;
    int iof = channel.indexOf(mHighlightQuery);
    SpannableString str = new SpannableString(channel + "  " + name);
    str.setSpan(new ForegroundColorSpan(mHighlightTextColor), iof, iof + mHighlightQuery.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    str.setSpan(new ForegroundColorSpan(mSecondaryTextColor), channel.length() + 2, channel.length() + 2 + name.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    mText.setText(str);
}
 
Example 32
Project: Exoplayer2Radio   File: CodecSpecificDataUtil.java   View source code 5 votes vote down vote up
/**
 * Parses an AudioSpecificConfig, as defined in ISO 14496-3 1.6.2.1
 *
 * @param audioSpecificConfig The AudioSpecificConfig to parse.
 * @return A pair consisting of the sample rate in Hz and the channel count.
 */
public static Pair<Integer, Integer> parseAacAudioSpecificConfig(byte[] audioSpecificConfig) {
  ParsableBitArray bitArray = new ParsableBitArray(audioSpecificConfig);
  int audioObjectType = getAacAudioObjectType(bitArray);
  int sampleRate = getAacSamplingFrequency(bitArray);
  int channelConfiguration = bitArray.readBits(4);
  if (audioObjectType == AUDIO_OBJECT_TYPE_SBR || audioObjectType == AUDIO_OBJECT_TYPE_PS) {
    // For an AAC bitstream using spectral band replication (SBR) or parametric stereo (PS) with
    // explicit signaling, we return the extension sampling frequency as the sample rate of the
    // content; this is identical to the sample rate of the decoded output but may differ from
    // the sample rate set above.
    // Use the extensionSamplingFrequencyIndex.
    sampleRate = getAacSamplingFrequency(bitArray);
    audioObjectType = getAacAudioObjectType(bitArray);
    if (audioObjectType == AUDIO_OBJECT_TYPE_ER_BSAC) {
      // Use the extensionChannelConfiguration.
      channelConfiguration = bitArray.readBits(4);
    }
  }
  int channelCount = AUDIO_SPECIFIC_CONFIG_CHANNEL_COUNT_TABLE[channelConfiguration];
  Assertions.checkArgument(channelCount != AUDIO_SPECIFIC_CONFIG_CHANNEL_CONFIGURATION_INVALID);
  return Pair.create(sampleRate, channelCount);
}
 
Example 33
Project: fuckView   File: Hook.java   View source code 5 votes vote down vote up
private Pair<Boolean, Integer> isBlockDialog(ArrayList<BlockModel> mBlockList, View view) {
    final String pkg = view.getContext().getPackageName();
    final int len = mBlockList.size();
    for (int i = 0; i < len; i++) {
        BlockModel model = mBlockList.get(i);
        if (!model.packageName.equals(pkg) || !model.className.equals(DIALOG_VIRTUAL_CLASSNAME)) {
            continue;
        }
        if (model.record.equals(getAllText(view))) {
            return new Pair<>(model.enable, i);
        }
    }
    return new Pair<>(false, -1);
}
 
Example 34
Project: Android-Allocine-Api   File: AllocineApi.java   View source code 5 votes vote down vote up
/**
 * Recherche
 */
public Single<AllocineResponse> search(final String recherche, final List<String> filter, final int count, final int page) {
    return Single
            .create(new SingleOnSubscribe<Pair<String, String>>() {
                @Override
                public void subscribe(SingleEmitter<Pair<String, String>> e) throws Exception {
                    final String params = ServiceSecurity.construireParams(false,
                            AllocineService.Q, "" + recherche.replace(" ", "+"),
                            AllocineService.FILTER, filter,
                            AllocineService.COUNT, "" + count,
                            AllocineService.PAGE, "" + page
                    );

                    final String sed = ServiceSecurity.getSED();
                    final String sig = ServiceSecurity.getSIG(params, sed);

                    e.onSuccess(Pair.create(sed, sig));
                }
            })
            .flatMap(new Function<Pair<String, String>, SingleSource<? extends AllocineResponse>>() {
                @Override
                public SingleSource<? extends AllocineResponse> apply(Pair<String, String> pair) throws Exception {
                    return allocineService.search(recherche, ServiceSecurity.applatir(filter), count, page, pair.first, pair.second);
                }
            })
            .compose(this.<AllocineResponse>retry());
}
 
Example 35
Project: aosp_nav_bar_ex   File: NavBarEntryAdapter.java   View source code 5 votes vote down vote up
@Override
public View getView(final int position, View convertView, ViewGroup parent)
{
	View resultView = convertView;

	ViewHolder holder;

	if (resultView == null)
	{
		resultView = inflater.inflate(android.R.layout.simple_list_item_1, null);
		holder = new ViewHolder((TextView) resultView.findViewById(android.R.id.text1));

		resultView.setTag(holder);
	}
	else
	{
		holder = (ViewHolder) resultView.getTag();
	}

	Pair<String /* uuid */, NavBarEntry> entry = getItem(position);
	fillViews(holder, entry);

	return resultView;
}
 
Example 36
Project: PeSanKita-android   File: MessageSender.java   View source code 5 votes vote down vote up
private static void sendTextSelf(Context context, long messageId, long expiresIn) {
  EncryptingSmsDatabase database = DatabaseFactory.getEncryptingSmsDatabase(context);

  database.markAsSent(messageId, true);

  Pair<Long, Long> messageAndThreadId = database.copyMessageInbox(messageId);
  database.markAsPush(messageAndThreadId.first);

  if (expiresIn > 0) {
    ExpiringMessageManager expiringMessageManager = ApplicationContext.getInstance(context).getExpiringMessageManager();

    database.markExpireStarted(messageId);
    expiringMessageManager.scheduleDeletion(messageId, false, expiresIn);
  }
}
 
Example 37
Project: TPlayer   File: VideoView.java   View source code 5 votes vote down vote up
/**
 * Set the display options
 *
 * @param layout      <ul>
 *                    <li>{@link #VIDEO_LAYOUT_ORIGIN}
 *                    <li>{@link #VIDEO_LAYOUT_SCALE}
 *                    <li>{@link #VIDEO_LAYOUT_STRETCH}
 *                    <li>{@link #VIDEO_LAYOUT_FIT_PARENT}
 *                    <li>{@link #VIDEO_LAYOUT_ZOOM}
 *                    </ul>
 * @param aspectRatio video aspect ratio, will audo detect if 0.
 */
public void setVideoLayout(int layout, float aspectRatio) {
	LayoutParams lp = getLayoutParams();
	Pair<Integer, Integer> res = ScreenResolution.getResolution(mContext);
	int windowWidth = res.first.intValue(), windowHeight = res.second.intValue();
	float windowRatio = windowWidth / (float) windowHeight;
	float videoRatio = aspectRatio <= 0.01f ? mVideoAspectRatio : aspectRatio;
	mSurfaceHeight = mVideoHeight;
	mSurfaceWidth = mVideoWidth;
	if (VIDEO_LAYOUT_ORIGIN == layout && mSurfaceWidth < windowWidth && mSurfaceHeight < windowHeight) {
		lp.width = (int) (mSurfaceHeight * videoRatio);
		lp.height = mSurfaceHeight;
	} else if (layout == VIDEO_LAYOUT_ZOOM) {
		lp.width = windowRatio > videoRatio ? windowWidth : (int) (videoRatio * windowHeight);
		lp.height = windowRatio < videoRatio ? windowHeight : (int) (windowWidth / videoRatio);
	} else if (layout == VIDEO_LAYOUT_FIT_PARENT) {
		ViewGroup parent = (ViewGroup) getParent();
		float parentRatio = ((float) parent.getWidth()) / ((float) parent.getHeight());
		lp.width = (parentRatio < videoRatio) ? parent.getWidth() : Math.round(((float) parent.getHeight()) * videoRatio);
		lp.height = (parentRatio > videoRatio) ? parent.getHeight() : Math.round(((float) parent.getWidth()) / videoRatio);
	} else {
		boolean full = layout == VIDEO_LAYOUT_STRETCH;
		lp.width = (full || windowRatio < videoRatio) ? windowWidth : (int) (videoRatio * windowHeight);
		lp.height = (full || windowRatio > videoRatio) ? windowHeight : (int) (windowWidth / videoRatio);
	}
	setLayoutParams(lp);
	getHolder().setFixedSize(mSurfaceWidth, mSurfaceHeight);
   Log.d("VIDEO: %dx%dx%f, Surface: %dx%d, LP: %dx%d, Window: %dx%dx%f", mVideoWidth, mVideoHeight, mVideoAspectRatio, mSurfaceWidth, mSurfaceHeight, lp.width, lp.height, windowWidth, windowHeight, windowRatio);
   mVideoLayout = layout;
   mAspectRatio = aspectRatio;
 }
 
Example 38
Project: easyfilemanager   File: MultiSelectionUtil.java   View source code 5 votes vote down vote up
private void tryRestoreInstanceState(HashSet<Long> idsToCheckOnRestore) {
    if (idsToCheckOnRestore == null || mListView.getAdapter() == null) {
        return;
    }
    boolean idsFound = false;
    Adapter adapter = mListView.getAdapter();
    for (int pos = adapter.getCount() - 1; pos >= 0; pos--) {
        if (idsToCheckOnRestore.contains(adapter.getItemId(pos))) {
            idsFound = true;
            if (mItemsToCheck == null) {
                mItemsToCheck = new HashSet<Pair<Integer, Long>>();
            }
            mItemsToCheck.add(new Pair<Integer, Long>(pos, adapter.getItemId(pos)));
        }
    }
    if (idsFound) {
        // We found some IDs that were checked. Let's now restore the multi-selection
        // state.
        mActionMode = mActivity.startSupportActionMode(mCallbacks);
    }
}
 
Example 39
Project: rxbase-android   File: TfcBaseActivityPresenter.java   View source code 5 votes vote down vote up
/**
 * By composing this transformer with an observable you guarantee that every observable in your view model
 * will be properly completed when the view model completes.
 * <p>
 * It is required that *every* observable in a view model do `.compose(bindToLifecycle())` before calling
 * `subscribe`.
 */
public
@NonNull
<T> Observable.Transformer<T, T> bindToLifecycle() {
    return source -> source.takeUntil(
            view.switchMap(v -> v.lifecycle().map(e -> Pair.create(v, e)))
                    .filter(ve -> isFinished(ve.first, ve.second))
    );
}
 
Example 40
Project: Exoplayer2Radio   File: DefaultDrmSessionManager.java   View source code 5 votes vote down vote up
private long getLicenseDurationRemainingSec() {
  if (!C.WIDEVINE_UUID.equals(uuid)) {
    return Long.MAX_VALUE;
  }
  Pair<Long, Long> pair = WidevineUtil.getLicenseDurationRemainingSec(this);
  return Math.min(pair.first, pair.second);
}