auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void beforeEachTest() { this.me = new WorkbenchUser(); this.me.setName("Mr. Breeder"); this.me.setUserid(1); this.me.setPassword("password"); this.myBreedingBuddy = new WorkbenchUser(); this.myBreedingBuddy.setName("My Breeding Buddy"); this.myBreedingBuddy.setUserid(2); this.myBreedingBuddy.setPassword("password"); this.loggedInUser = new UsernamePasswordAuthenticationToken(this.me.getName(), this.me.getPassword()); SecurityContextHolder.getContext().setAuthentication(this.loggedInUser); Mockito.when(this.workbenchDataManager.getUserById(this.me.getUserid())).thenReturn(this.me); Mockito.when(this.workbenchDataManager.getUserById(this.myBreedingBuddy.getUserid())).thenReturn(this.myBreedingBuddy); Mockito.when(this.workbenchDataManager.getUserByUsername(this.me.getName())).thenReturn(this.me); Mockito.when(this.workbenchDataManager.getUserByUsername(this.myBreedingBuddy.getName())).thenReturn(this.myBreedingBuddy); Mockito.when(securityService.getCurrentlyLoggedInUser()).thenCallRealMethod(); }

Target:
public void beforeEachTest() { this.me = new WorkbenchUser(); this.me.setName("Mr. Breeder"); this.me.setUserid(1); this.me.setPassword("password"); this.myBreedingBuddy = new WorkbenchUser(); this.myBreedingBuddy.setName("My Breeding Buddy"); this.myBreedingBuddy.setUserid(2); this.myBreedingBuddy.setPassword("password"); Mockito.when(this.workbenchDataManager.getUserById(this.me.getUserid())).thenReturn(this.me); Mockito.when(this.workbenchDataManager.getUserById(this.myBreedingBuddy.getUserid())).thenReturn(this.myBreedingBuddy); Mockito.when(this.workbenchDataManager.getUserByUsername(this.me.getName())).thenReturn(this.me); Mockito.when(this.workbenchDataManager.getUserByUsername(this.myBreedingBuddy.getName())).thenReturn(this.myBreedingBuddy); Mockito.when(this.securityService.getCurrentlyLoggedInUser()).thenReturn(this.me); }
Source:
public void beginTransaction_readOnlyThrows() { RealmConfiguration config = configFactory.createConfigurationBuilder() .name("readonly.realm") .schema(StringOnly.class) .assetFile("readonly.realm") .readOnly() .build(); realm = Realm.getInstance(config); try { realm.beginTransaction(); } catch (IllegalStateException e) { assertTrue(e.getMessage().startsWith("Write transactions cannot be used ")); } }

Target:
public void beginTransaction_readOnlyThrows() { RealmConfiguration config = configFactory.createConfigurationBuilder() .name("readonly.realm") .schema(StringOnlyReadOnly.class) .assetFile("readonly.realm") .readOnly() .build(); Realm realm = Realm.getInstance(config); try { realm.beginTransaction(); fail(); } catch (IllegalStateException e) { assertTrue(e.getMessage().startsWith("Write transactions cannot be used ")); } finally { realm.close(); } }
Source:
public boolean onCreateOptionsMenu(final Menu menu) { super.onCreateOptionsMenu(menu); final Intent i = getIntent(); menu.findItem(R.id.action_add_contact).setVisible(true); return true; }

Target:
public boolean onCreateOptionsMenu(final Menu menu) { super.onCreateOptionsMenu(menu); menu.findItem(R.id.action_add_contact).setVisible(true); return true; }
Source:
public void testIntervalAnnotationRejectsNonFixed12() { for (int i = 1; i < 50; i += 1) { final int length = i; if (length != 12) { assertThrows("Should reject fixed with length: " + i, IllegalStateException.class, new Callable<Type>() { @Override public Type call() throws Exception { return Types.required(FIXED_LEN_BYTE_ARRAY).length(length) .as(INTERVAL).named("interval"); } }); } } }

Target:
public void testIntervalAnnotationRejectsNonFixed12() { assertThrows("Should reject fixed with length != 12: " + 11, IllegalStateException.class, new Callable<Type>() { @Override public Type call() throws Exception { return Types.required(FIXED_LEN_BYTE_ARRAY).length(11) .as(INTERVAL).named("interval"); } }); }
Source:
protected boolean canDoAction() { VDS vds = getVds(); if (vds != null) { VDSGroup vdsGroup = getDbFacade().getVdsGroupDao().get(vds.getVdsGroupId()); if (vdsGroup != null && !vdsGroup.getFencingPolicy().isFencingEnabled()) { AuditLogableBase alb = new AuditLogableBase(); alb.setVds(vds); AuditLogDirector.log(alb, AuditLogType.VDS_FENCE_DISABLED_BY_CLUSTER_POLICY); addCanDoActionMessage(VdcBllMessages.VDS_FENCE_DISABLED_BY_CLUSTER_POLICY); return false; } } return super.canDoAction(); }

Target:
protected boolean canDoAction() { VDS vds = getVds(); if (vds != null) { VDSGroup vdsGroup = getDbFacade().getVdsGroupDao().get(vds.getVdsGroupId()); if (vdsGroup != null && !vdsGroup.getFencingPolicy().isFencingEnabled()) { AuditLogableBase alb = new AuditLogableBase(); alb.setVdsId(vds.getId()); AuditLogDirector.log(alb, AuditLogType.VDS_ALERT_FENCE_DISABLED_BY_CLUSTER_POLICY); addCanDoActionMessage(VdcBllMessages.VDS_FENCE_DISABLED_BY_CLUSTER_POLICY); return false; } } return super.canDoAction(); }
Source:
public void testPredicatePushDownOverProjection() { assertPlan( "with t as (select orderkey * 2 x from orders) select * from t where x + x > 1", anyTree( filter("((expr + expr) > BIGINT '1')", project(ImmutableMap.of("expr", expression("orderkey * BIGINT '2'")), tableScan("orders", ImmutableMap.of("ORDERKEY", "orderkey")))))); assertPlan( "with t as (select orderkey * 2 x, 1 y from orders) select * from t where x + y + y >1", anyTree( project( filter("(((orderkey * BIGINT '2') + BIGINT '1') + BIGINT '1') > BIGINT '1'", tableScan("orders", ImmutableMap.of( "orderkey", "orderkey")))))); assertPlan( "with t as (select orderkey * 2 x from orders) select * from t where x > 1", anyTree( project( filter("(orderkey * BIGINT '2') > BIGINT '1'", tableScan("orders", ImmutableMap.of( "orderkey", "orderkey")))))); assertPlan( "with t as (select orderkey * 2 x, orderkey y from orders) select * from t where x + y > 1", anyTree( project( filter("((orderkey * BIGINT '2') + orderkey) > BIGINT '1'", tableScan("orders", ImmutableMap.of( "orderkey", "orderkey")))))); assertPlan( "with t as (select orderkey x from orders) select * from t where x >1", anyTree( filter("orderkey > BIGINT '1'", tableScan("orders", ImmutableMap.of( "orderkey", "orderkey"))))); }

Target:
public void testPredicatePushDownOverProjection() { assertPlan( "WITH t AS (SELECT orderkey * 2 x FROM orders) " + "SELECT * FROM t WHERE x + x > 1", anyTree( filter("((expr + expr) > BIGINT '1')", project(ImmutableMap.of("expr", expression("orderkey * BIGINT '2'")), tableScan("orders", ImmutableMap.of("ORDERKEY", "orderkey")))))); assertPlan( "with t AS (SELECT orderkey * 2 x, 1 y FROM orders) " + "SELECT * FROM t WHERE x + y + y >1", anyTree( project( filter("(((orderkey * BIGINT '2') + BIGINT '1') + BIGINT '1') > BIGINT '1'", tableScan("orders", ImmutableMap.of( "orderkey", "orderkey")))))); assertPlan( "WITH t AS (SELECT orderkey * 2 x FROM orders) " + "SELECT * FROM t WHERE x > 1", anyTree( project( filter("(orderkey * BIGINT '2') > BIGINT '1'", tableScan("orders", ImmutableMap.of( "orderkey", "orderkey")))))); assertPlan( "with t AS (SELECT orderkey * 2 x, orderkey y FROM orders) " + "SELECT * FROM t WHERE x + y > 1", anyTree( project( filter("((orderkey * BIGINT '2') + orderkey) > BIGINT '1'", tableScan("orders", ImmutableMap.of( "orderkey", "orderkey")))))); assertPlan( "WITH t AS (SELECT orderkey x FROM orders) " + "SELECT * FROM t WHERE x >1", anyTree( filter("orderkey > BIGINT '1'", tableScan("orders", ImmutableMap.of( "orderkey", "orderkey"))))); assertPlan( "WITH t AS (SELECT rand() * orderkey x FROM orders) " + "SELECT * FROM t WHERE x > 5000", anyTree( filter("expr > 5E3", project(ImmutableMap.of("expr", expression("rand() * CAST(orderkey AS double)")), tableScan("orders", ImmutableMap.of( "ORDERKEY", "orderkey")))))); }
Source:
public void acceptRecord(final GcBiasCollectorArgs args) { final SAMRecord rec = args.getRec(); if (rec.getReadBases().length == 0) { log.warn("Omitting read " + rec.getReadName() + " with '*' in SEQ field."); return; } if (!rec.getReadUnmappedFlag()) { if (referenceIndex != rec.getReferenceIndex() || gc == null) { final ReferenceSequence ref = args.getRef(); refBases = ref.getBases(); StringUtil.toUpperCase(refBases); final int refLength = refBases.length; final int lastWindowStart = refLength - scanWindowSize; gc = GcBiasUtils.calculateAllGcs(refBases, lastWindowStart, scanWindowSize); referenceIndex = rec.getReferenceIndex(); } addReadToGcData(rec, this.gcData, ""); if (IS_NON_DUPLICATES && !rec.getDuplicateReadFlag()) { addReadToGcData(rec, this.gcDataNonDups, NON_DUPS_PREFIX); } } else { updTotalClusters(rec, this.gcData); if (IS_NON_DUPLICATES && !rec.getDuplicateReadFlag()) { updTotalClusters(rec, this.gcDataNonDups); } } }

Target:
public void acceptRecord(final GcBiasCollectorArgs args) { final SAMRecord rec = args.getRec(); if (logCounter < 100 && rec.getReadBases().length == 0) { log.warn("Omitting read " + rec.getReadName() + " with '*' in SEQ field."); if (++logCounter == 100) { log.warn("There are more than 100 reads with '*' in SEQ field in file."); } return; } if (!rec.getReadUnmappedFlag()) { if (referenceIndex != rec.getReferenceIndex() || gc == null) { final ReferenceSequence ref = args.getRef(); refBases = ref.getBases(); StringUtil.toUpperCase(refBases); final int refLength = refBases.length; final int lastWindowStart = refLength - scanWindowSize; gc = GcBiasUtils.calculateAllGcs(refBases, lastWindowStart, scanWindowSize); referenceIndex = rec.getReferenceIndex(); } addReadToGcData(rec, this.gcData); if (ignoreDuplicates && !rec.getDuplicateReadFlag()) { addReadToGcData(rec, this.gcDataNonDups); } } else { updateTotalClusters(rec, this.gcData); if (ignoreDuplicates && !rec.getDuplicateReadFlag()) { updateTotalClusters(rec, this.gcDataNonDups); } } }
Source:
public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_browser_current_category: PageTitle title = Utils.getPageTitle(String.format("Category:%s", categoryName)); Utils.handleWebUrl(this, Uri.parse(title.getCanonicalUri())); return true; default: return super.onOptionsItemSelected(item); } }

Target:
public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_browser_current_category: PageTitle title = Utils.getPageTitle(CATEGORY_PREFIX + categoryName); Utils.handleWebUrl(this, Uri.parse(title.getCanonicalUri())); return true; default: return super.onOptionsItemSelected(item); } }
Source:
public void testDownloadLog() throws Exception { String testLogName = "strongbox-test.log"; Files.createFile(Paths.get(propertiesBooter.getLogsDirectory(), testLogName)) .toFile() .deleteOnExit(); String url = getContextBaseUrl() + "/log/" + testLogName; mockMvc.header(HttpHeaders.ACCEPT, MediaType.TEXT_PLAIN_VALUE) .when() .get(url) .peek() .then() .statusCode(HttpStatus.OK.value()); }

Target:
public void testDownloadLog() throws Exception { String testLogName = "strongbox-test.log"; Path file = Paths.get(propertiesBooter.getLogsDirectory(), testLogName); Files.createFile(file) .toFile() .deleteOnExit(); List<String> lines = Arrays.asList("Strongbox", "is", "awesome!"); Files.write(file, lines, StandardCharsets.UTF_8); assertThat(file.toFile().length()).isGreaterThan(0); String url = getContextBaseUrl() + "/download/" + testLogName; ResponseBodyExtractionOptions body = mockMvc.header(HttpHeaders.ACCEPT, MediaType.APPLICATION_OCTET_STREAM_VALUE) .when() .get(url) .peek() .then() .statusCode(HttpStatus.OK.value()) .extract() .body(); assertThat(body.asByteArray().length).isEqualTo(file.toFile().length()); }
Source:
public int unsynchronizedGetExclusiveBuffersUsed() { return Math.max(0, initialCredit - bufferManager.getNumberOfAvailableExclusiveBuffers()); }

Target:
public int unsynchronizedGetExclusiveBuffersUsed() { return Math.max(0, initialCredit - bufferManager.unsynchronizedGetExclusiveBuffersUsed()); }
Source:
private boolean upgradeEightNine(SQLiteDatabase db) { db.beginTransaction(); try { if (multipleInstalledAppRecords()) { throw new MigrationException(true); } SqlStorage<FormRecordV1> oldStorage = new SqlStorage<>( FormRecord.STORAGE_KEY, FormRecordV1.class, new ConcreteAndroidDbHelper(c, db)); String appId = getInstalledAppRecord().getApplicationId(); Vector<FormRecord> upgradedRecords = new Vector<>(); for (FormRecordV1 oldRecord : oldStorage) { FormRecord newRecord = new FormRecord( oldRecord.getInstanceURIString(), oldRecord.getStatus(), oldRecord.getFormNamespace(), oldRecord.getAesKey(), oldRecord.getInstanceID(), oldRecord.lastModified(), appId); newRecord.setID(oldRecord.getID()); upgradedRecords.add(newRecord); } db.execSQL(DatabaseAppOpenHelper.addColumnToTable( FormRecord.STORAGE_KEY, FormRecord.META_APP_ID, "TEXT")); SqlStorage<FormRecord> newStorage = new SqlStorage<>( FormRecord.STORAGE_KEY, FormRecord.class, new ConcreteAndroidDbHelper(c, db)); for (FormRecord r : upgradedRecords) { newStorage.write(r); } db.setTransactionSuccessful(); return true; } finally { db.endTransaction(); } }

Target:
private boolean upgradeEightNine(SQLiteDatabase db) { return FixtureSerializationMigration.migrateFixtureDbBytes(db, c); }
Source:
public FileSystem newFileSystem(URI uri, Map<String, ?> config) throws IOException { String accountName = extractAccountName(uri); if (this.openFileSystems.containsKey(accountName)) { throw new FileSystemAlreadyExistsException(); } AzureFileSystem afs = new AzureFileSystem(this, accountName, config); this.openFileSystems.put(accountName, afs); return afs; }

Target:
public FileSystem newFileSystem(URI uri, Map<String, ?> config) throws IOException { String accountName = extractAccountName(uri); if (this.openFileSystems.containsKey(accountName)) { throw Utility.logError(this.logger, new FileSystemAlreadyExistsException("Name: " + accountName)); } AzureFileSystem afs = new AzureFileSystem(this, accountName, config); this.openFileSystems.put(accountName, afs); return afs; }
Source:
public EtcdNettyClient(final EtcdNettyConfig config, final EtcdSecurityContext securityContext, final URI... uris) { this(config, securityContext, new HashedWheelTimer(new ThreadFactory() { @Override public Thread newThread(Runnable r) { Thread t = new Thread(r, "etcd4j-timer-thread"); t.setDaemon(false); return t; } }), uris); }

Target:
public EtcdNettyClient(final EtcdNettyConfig config, final EtcdSecurityContext securityContext, final URI... uris) { logger.info("Setting up Etcd4j Netty client"); this.lastWorkingUriIndex = 0; this.config = config.clone(); this.securityContext = securityContext.clone(); this.uris = uris; this.timer = config.getTimer(); this.eventLoopGroup = config.getEventLoopGroup(); this.bootstrap = new Bootstrap() .group(eventLoopGroup) .channel(config.getSocketChannelClass()) .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .option(ChannelOption.TCP_NODELAY, true) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.getConnectTimeout()) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); if (securityContext.hasNettySsl()) { p.addLast(securityContext.nettySslContext().newHandler(ch.alloc())); } else if (securityContext.hasSsl()) { p.addLast(new SslHandler(securityContext.sslContext().createSSLEngine())); } p.addLast("codec", new HttpClientCodec()); if(securityContext.hasCredentials()) { p.addLast("auth", new HttpBasicAuthHandler()); } p.addLast("chunkedWriter", new ChunkedWriteHandler()); p.addLast("aggregate", new HttpObjectAggregator(config.getMaxFrameSize())); } }); }
Source:
private static void initializePortraits() { if (parseDirectory) { parseDirectory = false; try { portraitDirectory = new DirectoryItems(Configuration.portraitImagesDir(), "", ImageFileFactory.getInstance()); } catch (Exception e) { MegaMek.getLogger().error("Could not parse the portraits directory!"); e.printStackTrace(); } } }

Target:
private static void initializePortraits() { if (parseDirectory) { parseDirectory = false; try { portraitDirectory = new DirectoryItems(Configuration.portraitImagesDir(), "", ImageFileFactory.getInstance()); } catch (Exception e) { MegaMek.getLogger().error("Could not parse the portraits directory!", e); } } }
Source:
private String getQualifiedNetworksServiceClassName() { String className = mPhone.getContext().getResources().getString( com.android.internal.R.string.config_qualified_networks_service_class); PersistableBundle b = mCarrierConfigManager.getConfigForSubId(mPhone.getSubId()); if (b != null) { String carrierConfigPackageName = b.getString(CarrierConfigManager .KEY_CARRIER_QUALIFIED_NETWORKS_SERVICE_CLASS_OVERRIDE_STRING); if (!TextUtils.isEmpty(carrierConfigPackageName)) { if (DBG) log("Found carrier config override " + carrierConfigPackageName); className = carrierConfigPackageName; } } List<ResolveInfo> resolveInfo = mPhone.getContext().getPackageManager().queryIntentServices( new Intent(QualifiedNetworksService.QUALIFIED_NETWORKS_SERVICE_INTERFACE), PackageManager.MATCH_SYSTEM_ONLY); if (resolveInfo != null) { for (ResolveInfo info : resolveInfo) { if (info.serviceInfo == null) continue; if ((info.serviceInfo.name).contains(className)) { className = info.serviceInfo.name; break; } } } return className; }

Target:
private String getQualifiedNetworksServiceClassName() { String className = mPhone.getContext().getResources().getString( com.android.internal.R.string.config_qualified_networks_service_class); PersistableBundle b = mCarrierConfigManager.getConfigForSubId(mPhone.getSubId()); if (b != null) { String carrierConfigClassName = b.getString(CarrierConfigManager .KEY_CARRIER_QUALIFIED_NETWORKS_SERVICE_CLASS_OVERRIDE_STRING); if (!TextUtils.isEmpty(carrierConfigClassName)) { if (DBG) log("Found carrier config override " + carrierConfigClassName); className = carrierConfigClassName; } } return className; }
Source:
public BlockPiston(boolean sticky) { this.sticky = sticky; if (!sticky) { setDrops(new ItemStack(Material.PISTON_BASE)); } else { setDrops(new ItemStack(Material.PISTON_STICKY_BASE)); } }

Target:
public BlockPiston(boolean sticky) { this.sticky = sticky; if (sticky) { setDrops(new ItemStack(Material.PISTON_STICKY_BASE)); } else { setDrops(new ItemStack(Material.PISTON_BASE)); } }
Source:
public void toggleStars(final ToggleStarRequest req, final AsyncCallback<VoidResult> callback) { run(callback, new Action<VoidResult>() { public VoidResult run(final ReviewDb db) throws OrmException { final Account.Id me = getAccountId(); final Set<Change.Id> existing = currentUser.get().getStarredChanges(); List<StarredChange> add = new ArrayList<StarredChange>(); List<StarredChange.Key> remove = new ArrayList<StarredChange.Key>(); if (req.getAddSet() != null) { for (final Change.Id id : req.getAddSet()) { if (!existing.contains(id)) { StarredChange.Key key = new StarredChange.Key(me, id); add.add(new StarredChange(key)); starredChangesCache.evict(key); } } } if (req.getRemoveSet() != null) { for (final Change.Id id : req.getRemoveSet()) { StarredChange.Key key = new StarredChange.Key(me, id); remove.add(key); starredChangesCache.evict(key); } } db.starredChanges().insert(add); db.starredChanges().deleteKeys(remove); return VoidResult.INSTANCE; } }); }

Target:
public void toggleStars(final ToggleStarRequest req, final AsyncCallback<VoidResult> callback) { run(callback, new Action<VoidResult>() { public VoidResult run(final ReviewDb db) throws OrmException { final Account.Id me = getAccountId(); final Set<Change.Id> existing = currentUser.get().getStarredChanges(); List<StarredChange> add = new ArrayList<StarredChange>(); List<StarredChange.Key> remove = new ArrayList<StarredChange.Key>(); if (req.getAddSet() != null) { for (final Change.Id id : req.getAddSet()) { if (!existing.contains(id)) { StarredChange.Key key = new StarredChange.Key(me, id); add.add(new StarredChange(key)); } } } if (req.getRemoveSet() != null) { for (final Change.Id id : req.getRemoveSet()) { StarredChange.Key key = new StarredChange.Key(me, id); remove.add(key); } } db.starredChanges().insert(add); db.starredChanges().deleteKeys(remove); for (StarredChange sc : add) { starredChangesCache.evict(new StarredChange.Key(sc.getAccountId(), sc .getChangeId())); } for (StarredChange.Key key : remove) { starredChangesCache.evict(key); } return VoidResult.INSTANCE; } }); }
Source:
private void writeResponse() { String result = "HTTP/1.1 200 OK\r\n" + "Content-Type: text/html\r\n" + "Content-Length: " + 0 + "\r\n" + "Connection: close\r\n\r\n"; try { os.write(result.getBytes()); os.flush(); } catch (IOException e) { e.printStackTrace(); } }

Target:
private void writeResponse() { String result = "HTTP/1.1 200 OK\r\n" + "Content-Type: text/html\r\n" + "Content-Length: " + 0 + "\r\n" + "Connection: close\r\n\r\n"; try { os.write(result.getBytes()); os.flush(); } catch (IOException e) { logger.error(e.getMessage()); } }
Source:
private String getErrorString(final String errorMessage, final List<String> issues) { if((issues == null) || issues.isEmpty()) { return null; } StringBuilder builder = new StringBuilder(); builder.append(errorMessage); for (String issue : issues) { builder.append(" "); builder.append(issue); } return builder.toString(); }

Target:
private String getErrorString(final String errorMessage, final List<String> issues) { if ((issues == null) || issues.isEmpty()) { return null; } StringBuilder errorStringBuilder = new StringBuilder(errorMessage); errorStringBuilder.append(" "); errorStringBuilder.append(StaticUtils.collectionToString(issues, " ")); return errorStringBuilder.toString(); }
Source:
public SavedRequest getRequest(HttpServletRequest request, HttpServletResponse response) { Cookie savedRequestCookie = WebUtils.getCookie(request, cookieName); return savedRequestCookie != null ? new SimpleSavedRequest(savedRequestCookie.getValue()) : null; }

Target:
public SavedRequest getRequest(HttpServletRequest request, HttpServletResponse response) { Cookie savedRequestCookie = WebUtils.getCookie(request, COOKIE_NAME); if (savedRequestCookie != null) { String originalURI = decodeCookie(savedRequestCookie.getValue()); UriComponents uriComponents = UriComponentsBuilder.fromUriString(originalURI).build(); DefaultSavedRequest.Builder builder = new DefaultSavedRequest.Builder(); int port = uriComponents.getPort(); if (port == -1) { if ("https".equalsIgnoreCase(uriComponents.getScheme())) { port = 443; } else { port = 80; } } return builder.setScheme(uriComponents.getScheme()) .setServerName(uriComponents.getHost()) .setRequestURI(uriComponents.getPath()) .setQueryString(uriComponents.getQuery()) .setServerPort(port) .build(); } return null; }
Source:
private CoverageUnit getMethodCoverageUnit(CoverageUnit fromFile, CoverageItem fromItem) { for (CoverageUnit unit : fromFile.getCoverageUnits()) { if (unit.getName().equals(fromItem.getParent().getName())) { if (!forMethodNumbers || (forMethodNumbers && unit.getOrderNumber().equals( fromItem.getParent().getOrderNumber()))) { return unit; } } } return null; }

Target:
private CoverageUnit getMethodCoverageUnit(CoverageUnit fromFile, CoverageItem fromItem) { CoverageUnit ret = null; for (CoverageUnit unit : fromFile.getCoverageUnits()) { if (methodsMatched(unit, fromFile, forceCompareMethodNumbers)) { ret = unit; break; } } return ret; }
Source:
public T obtain() throws E, TimeoutException { while (true) { try { if (!semaphore.tryAcquire(1, obtainClientTimeoutMs, TimeUnit.MILLISECONDS)) { throw new TimeoutException("Failed to obtain client."); } break; } catch (InterruptedException e) { LOG.warn("Wait interrupted. Ignoring and retrying."); } } T client = elements.poll(); if (client != null) { return client; } return create(); }

Target:
public T obtain() throws E, TimeoutException, InterruptedException { semaphore.acquire(); return getOrCreate(); }
Source:
public double pastCompositionFactor() { double compositionFactor = 1.0d; LocalDate currentFixing = firstFixing; LocalDate currentPublication = index.calculatePublicationFromFixing(currentFixing); while ((!currentFixing.isAfter(lastFixingNonCutoff)) && env.getValuationDate().isAfter(currentPublication)) { LocalDate effectiveDate = index.calculateEffectiveFromFixing(currentFixing); LocalDate maturityDate = index.calculateMaturityFromEffective(effectiveDate); double accrualFactor = index.getDayCount().yearFraction(effectiveDate, maturityDate); compositionFactor *= 1.0d + accrualFactor * checkedFixing(currentFixing, indexFixingDateSeries, index); currentFixing = fixingCalendar.next(currentFixing); currentPublication = index.calculatePublicationFromFixing(currentFixing); } if (currentFixing.equals(lastFixingNonCutoff) && env.getValuationDate().isAfter(currentPublication)) { double rate = checkedFixing(currentFixing, indexFixingDateSeries, index); for (int i = 0; i < cutoffOffset - 1; i++) { compositionFactor *= 1.0d + accrualFactorCutoff[i] * rate; } currentFixing = fixingCalendar.next(currentFixing); } nextFixing = currentFixing; return compositionFactor; }

Target:
private double pastCompositionFactor() { double compositionFactor = 1.0d; LocalDate currentFixing = firstFixing; LocalDate currentPublication = index.calculatePublicationFromFixing(currentFixing); while ((currentFixing.isBefore(lastFixingNonCutoff)) && env.getValuationDate().isAfter(currentPublication)) { LocalDate effectiveDate = index.calculateEffectiveFromFixing(currentFixing); LocalDate maturityDate = index.calculateMaturityFromEffective(effectiveDate); double accrualFactor = index.getDayCount().yearFraction(effectiveDate, maturityDate); compositionFactor *= 1.0d + accrualFactor * checkedFixing(currentFixing, indexFixingDateSeries, index); currentFixing = fixingCalendar.next(currentFixing); currentPublication = index.calculatePublicationFromFixing(currentFixing); } if (currentFixing.equals(lastFixingNonCutoff) && env.getValuationDate().isAfter(currentPublication)) { double rate = checkedFixing(currentFixing, indexFixingDateSeries, index); LocalDate effectiveDate = index.calculateEffectiveFromFixing(currentFixing); LocalDate maturityDate = index.calculateMaturityFromEffective(effectiveDate); double accrualFactor = index.getDayCount().yearFraction(effectiveDate, maturityDate); compositionFactor *= 1.0d + accrualFactor * rate; for (int i = 0; i < cutoffOffset - 1; i++) { compositionFactor *= 1.0d + accrualFactorCutoff[i] * rate; } currentFixing = fixingCalendar.next(currentFixing); } nextFixing = currentFixing; return compositionFactor; }
Source:
public HeaderWriterServerLogoutHandler(ServerHttpHeadersWriter headersWriter) { Assert.notNull(headersWriter, "ServerHttpHeadersWriter must not be null"); this.headersWriter = headersWriter; }

Target:
public HeaderWriterServerLogoutHandler(ServerHttpHeadersWriter headersWriter) { Assert.notNull(headersWriter, "headersWriter cannot be null"); this.headersWriter = headersWriter; }
Source:
public void testReadProtocolWithBrokenState() { client.connect(); try { client.getOne(); } catch (JedisConnectionException ignored) { } try { client.getOne(); fail("Should throw exception"); } catch (JedisConnectionException exc) { assertEquals("Trying to read from a broken connection", exc.getMessage()); } }

Target:
public void testReadProtocolWithBrokenState() { client.connect(); try { client.getOne(); fail("Should have thrown an exception as there is nothing to read"); } catch (JedisConnectionException ignored) { assertEquals("Unexpected end of stream.", ignored.getMessage()); } try { client.getOne(); fail("Should have failed due to reading from a broken connection"); } catch (JedisConnectionException exc) { assertEquals("Trying to read from a broken connection", exc.getMessage()); } }
Source:
static EquatableValueSet of(Type type, Object first, Object... rest) { LinkedHashSet<ValueEntry> set = new LinkedHashSet<>(rest.length + 1); set.add(ValueEntry.create(type, first)); for (Object value : rest) { set.add(ValueEntry.create(type, value)); } return new EquatableValueSet(type, true, set); }

Target:
static EquatableValueSet of(Type type, Object first, Object... rest) { HashSet<ValueEntry> set = new LinkedHashSet<>(rest.length + 1); set.add(ValueEntry.create(type, first)); for (Object value : rest) { set.add(ValueEntry.create(type, value)); } return new EquatableValueSet(type, true, set); }
Source:
public boolean saveValue(final String variableKey, final char[] variableValue) { try { final SecretKeyFactory factory = SecretKeyFactory.getInstance( SECRETS_STORE_SECRET_KEY_FACTORY_TYPE); final SecretKey generatedSecret = factory.generateSecret(new PBEKeySpec(encrypt(variableValue).toCharArray())); final KeyStore keyStore = getSecretsStore(); final PasswordProtection keyStorePP = new PasswordProtection(loadStorePassword()); keyStore.setEntry(variableKey, new KeyStore.SecretKeyEntry(generatedSecret), keyStorePP); saveSecretsStore(keyStore); } catch (Exception e) { Logger.warn(this.getClass(), "Unable to save secret from " + SECRETS_STORE_FILE + ": " + e); throw new DotRuntimeException(e); } return true; }

Target:
public boolean saveValue(final String variableKey, final char[] variableValue) { try { final SecretKeyFactory factory = SecretKeyFactory.getInstance(SECRETS_STORE_SECRET_KEY_FACTORY_TYPE); final KeyStore keyStore = getSecretsStore(); final char encryptedVal = encrypt(variableValue).toCharArray(); final SecretKey generatedSecret = factory.generateSecret(new PBEKeySpec(encryptedVal)); final PasswordProtection keyStorePP = new PasswordProtection(loadStorePassword()); keyStore.setEntry(variableKey, new KeyStore.SecretKeyEntry(generatedSecret), keyStorePP); saveSecretsStore(keyStore); putInCache(variableKey, encryptedVal); } catch (Exception e) { Logger.warn(this.getClass(), "Unable to save secret from " + SECRETS_STORE_FILE + ": " + e); throw new DotRuntimeException(e); } return true; }
Source:
public RealmEventStreamTask<DocumentT> watch(final BsonValue... ids) { return new RealmEventStreamTaskImpl<>(getNamespace().getFullName(), new RealmEventStreamTaskImpl.Executor<DocumentT>() { @Override public EventStream<DocumentT> run() throws IOException { return osMongoCollection.watch(ids); } }); }

Target:
public RealmEventStreamTask<DocumentT> watch(final BsonValue... ids) { return new RealmEventStreamTaskImpl<>(getNamespace().getFullName(), new RealmEventStreamTaskImpl.Executor<DocumentT>() { @Override public EventStream<DocumentT> run() throws IOException { return osMongoCollection.watch(Arrays.asList(ids)); } }); }
Source:
protected abstract void isMasterRunning() throws ServiceException; private Object makeStubNoRetries() throws IOException, ServiceException { ServerName sn = registry.getActiveMaster(); if (sn == null) { String msg = "ZooKeeper available but no active master location found"; LOG.info(msg); throw new MasterNotRunningException(msg); } if (isDeadServer(sn)) { throw new MasterNotRunningException(sn + " is dead."); } String key = getStubKey(getServiceName(), sn.getHostname(), sn.getPort(), hostnamesCanChange); connectionLock.putIfAbsent(key, key); Object stub = null; synchronized (connectionLock.get(key)) { stub = stubs.get(key); if (stub == null) { BlockingRpcChannel channel = rpcClient.createBlockingRpcChannel(sn, user, rpcTimeout); stub = makeStub(channel); isMasterRunning(); stubs.put(key, stub); } } return stub; }

Target:
protected abstract void isMasterRunning() throws ServiceException; private Object makeStubNoRetries() throws IOException, ServiceException { ServerName sn = registry.getActiveMaster(); if (sn == null) { String msg = "No active master location found"; LOG.info(msg); throw new MasterNotRunningException(msg); } if (isDeadServer(sn)) { throw new MasterNotRunningException(sn + " is dead."); } String key = getStubKey(getServiceName(), sn.getHostname(), sn.getPort(), hostnamesCanChange); connectionLock.putIfAbsent(key, key); Object stub = null; synchronized (connectionLock.get(key)) { stub = stubs.get(key); if (stub == null) { BlockingRpcChannel channel = rpcClient.createBlockingRpcChannel(sn, user, rpcTimeout); stub = makeStub(channel); isMasterRunning(); stubs.put(key, stub); } } return stub; }
Source:
public RouteServerExposer( @Nullable @Named("che.infra.openshift.route.labels") String labelsProperty) { this.labels = labelsProperty != null ? Splitter.on(",").withKeyValueSeparator("=").split(labelsProperty) : new HashMap<>(); }

Target:
public RouteServerExposer( @Nullable @Named("che.infra.openshift.route.labels") String labelsProperty) { this.labels = labelsProperty != null ? Splitter.on(",").withKeyValueSeparator("=").split(labelsProperty) : emptyMap(); }
Source:
public static void sendPullRequestBuildStatusEvent(final PullRequestMergeCommitCreatedEventArgs gitCodePushedEventArgs, final GitStatusState buildState, final String buildDescription, final String targetUrl, final String jobFullPath) { try { final TeamGitStatus status = new TeamGitStatus(); status.state = buildState; status.description = buildDescription; status.targetUrl = targetUrl; status.context = new GitStatusContext(" ", StringUtils.stripEnd(jobFullPath, "/")); final URI collectionUri = gitCodePushedEventArgs.collectionUri; final TeamRestClient client = new TeamRestClient(collectionUri); client.addPullRequestStatus(gitCodePushedEventArgs, status); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return; }

Target:
public static void sendPullRequestBuildStatusEvent(final PullRequestMergeCommitCreatedEventArgs gitCodePushedEventArgs, final GitStatusState buildState, final String buildDescription, final String targetUrl, final String jobFullPath) { try { final TeamGitStatus status = new TeamGitStatus(); status.state = buildState; status.description = buildDescription; status.targetUrl = targetUrl; status.context = new GitStatusContext(" ", StringUtils.stripEnd(jobFullPath, "/")); final URI collectionUri = gitCodePushedEventArgs.collectionUri; final TeamRestClient client = new TeamRestClient(collectionUri); client.addPullRequestStatus(gitCodePushedEventArgs, status); } catch (MalformedURLException e) { log.warning("ERROR: sendPullRequestBuildStatusEvent fails due to MalformedURLException: " + e.getMessage()); } catch (IOException e) { log.warning("ERROR: sendPullRequestBuildStatusEvent fails due to IOException: " + e.getMessage()); } return; }
Source:
public void canDeserializeClientConfig() throws IOException { PrivilegesConfiguration configuration = deserialize(getConfigFile(CLIENT_PRIVILEGES_CONFIG)); assertThat(configuration).isInstanceOf(ClientPrivilegesConfiguration.class); assertThat(configuration.id()).isEqualTo(CLIENT_ID); Privileges privileges = configuration.privileges(); assertThat(privileges.hasPrivilege(CLIENT_NAMESPACE_1)).isTrue(); assertThat(privileges.hasPrivilege(CLIENT_NAMESPACE_2)).isTrue(); }

Target:
public void canDeserializeClientConfig() throws IOException { PrivilegesConfiguration deserializedConfiguration = deserialize(getConfigFile(CLIENT_PRIVILEGES_CONFIG)); ClientPrivilegesConfiguration expectedConfiguration = ImmutableClientPrivilegesConfiguration.builder() .clientId(CLIENT_ID) .addNamespaces(CLIENT_NAMESPACE_1, CLIENT_NAMESPACE_2) .build(); assertThat(deserializedConfiguration).isEqualTo(expectedConfiguration); }
Source:
default Option<Double> average() { if (isEmpty()) { return Option.none(); } else { final T head; final java.util.stream.Stream<T> elements; if (isTraversableAgain()) { head = head(); elements = toJavaStream(); } else { final Iterator<T> iterator = iterator(); head = iterator.next(); elements = Iterator.of(head).concat(iterator).toJavaStream(); } if (head instanceof Number) { final java.util.stream.Stream<Number> numbers = (java.util.stream.Stream<Number>) elements; final double avg; if (head instanceof Integer || head instanceof Long || head instanceof Byte || head instanceof BigInteger || head instanceof Short) { avg = numbers.mapToLong(Number::longValue).average().getAsDouble(); } else { avg = numbers.mapToDouble(Number::doubleValue).average().getAsDouble(); } return Option.some(avg); } else { throw new UnsupportedOperationException("not numeric"); } } }

Target:
default Option<Double> average() { try { final double[] sum = TraversableModule.neumaierSum(this, t -> ((Number) t).doubleValue()); final double count = sum[1]; return (count == 0) ? Option.none() : Option.some(sum[0] / count); } catch(ClassCastException x) { throw new UnsupportedOperationException("not numeric", x); } }
Source:
public void showNotificationPane(Node graphic, String text, Action action) { hideNotificationPane(); Platform.runLater(() -> { notificationPane.setGraphic(graphic); notificationPane.setText(text); notificationPane.getActions().clear(); notificationPane.getActions().add(action); notificationPane.show(); notificationPaneTimer.restart(); if (notificationPaneTimer.isPaused()) { notificationPaneTimer.resume(); } }); }

Target:
public void showNotificationPane(Node graphic, String text, Action action) { Platform.runLater(() -> { hideNotificationPane(); notificationPane.setGraphic(graphic); notificationPane.setText(text); notificationPane.getActions().clear(); notificationPane.getActions().add(action); notificationPane.show(); notificationPaneTimer.restart(); if (notificationPaneTimer.isPaused()) { notificationPaneTimer.resume(); } }); }
Source:
protected Map<String, Object> toMap() { ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); try { String json = mapper.writeValueAsString(this); final MapType type = mapper.getTypeFactory().constructMapType(Map.class, String.class, Object.class); return mapper.readValue(json, type); } catch (Exception e) { throw new RuntimeException("Failed to convert " + this.getClass().getName() + " to map.", e); } }

Target:
protected Map<String, Object> toMap() { try { String json = MAPPER.writeValueAsString(this); final MapType type = MAPPER.getTypeFactory().constructMapType(Map.class, String.class, Object.class); return MAPPER.readValue(json, type); } catch (Exception e) { throw new RuntimeException("Failed to convert " + this.getClass().getName() + " to map.", e); } }
Source:
private static String[] decodeParams(HttpPostCommand command, int expectedParamCount) throws UnsupportedEncodingException { final byte[] data = command.getData(); final String[] encoded = bytesToString(data).split("&"); final String[] decoded = new String[encoded.length]; if (encoded.length < expectedParamCount) { return null; } for (int i = 0; i < expectedParamCount; i++) { decoded[i] = URLDecoder.decode(encoded[i], "UTF-8"); } return decoded; }

Target:
String[] decodeParams(HttpPostCommand command, int expectedParamCount) throws UnsupportedEncodingException { byte[] data = command.getData(); if (data == null) { throw new HttpBadRequestException( "This endpoint expects at least " + expectedParamCount + " parameters"); } String[] encoded = bytesToString(data).split("&", expectedParamCount); String[] decoded = new String[encoded.length]; if (encoded.length < expectedParamCount) { throw new HttpBadRequestException( "This endpoint expects at least " + expectedParamCount + " parameters"); } for (int i = 0; i < expectedParamCount; i++) { decoded[i] = URLDecoder.decode(encoded[i], "UTF-8"); } return decoded; }
Source:
public void afterReceive(boolean messageReceived, MessageSource<?> source) { if (this.logger.isTraceEnabled()) { this.logger.trace("Poll resulted in message: " + messageReceived); } this.factory.clearThreadKey(); if (!this.fair && !messageReceived) { configureSource(source); } }

Target:
public void afterReceive(boolean messageReceived, MessageSource<?> source) { if (this.logger.isTraceEnabled()) { this.logger.trace("Poll produced " + (messageReceived ? "a" : "no") + " message"); } this.factory.clearThreadKey(); if (!this.fair && !messageReceived) { configureSource(source); } }
Source:
public void setup() { observable = Observable.never(); subscriber = new Subscriber<Object>() { @Override public void onCompleted() { onCompleteCalled = true; } @Override public void onError(Throwable e) { } @Override public void onNext(Object o) { } }; onCompleteCalled = false; }

Target:
public void setup() { MockitoAnnotations.initMocks(this); }
Source:
public static Map<Cell, byte[]> deserializeCellVals(final TableMetadata metadata, JsonNode node) { Iterable<Iterable<Entry<Cell, byte[]>>> cellVals; cellVals = new JsonNodeIterable<>(node, subNode -> deserializeCellVal(metadata, subNode)); ImmutableMap.Builder<Cell, byte[]> builder = ImmutableMap.builder(); for (Iterable<Entry<Cell, byte[]>> entries : cellVals) { for (Entry<Cell, byte[]> entry : entries) { builder.put(entry); } } return builder.build(); }

Target:
public static Map<Cell, byte[]> deserializeCellVals(final TableMetadata metadata, JsonNode node) { Iterable<Iterable<Entry<Cell, byte[]>>> cellVals = new JsonNodeIterable<>(node, subNode -> deserializeCellVal(metadata, subNode)); ImmutableMap.Builder<Cell, byte[]> builder = ImmutableMap.builder(); for (Iterable<Entry<Cell, byte[]>> entries : cellVals) { for (Entry<Cell, byte[]> entry : entries) { builder.put(entry); } } return builder.build(); }
Source:
void nonEnabledHealthReport() { HealthDescriptor descriptor = new HealthDescriptor("2", "1", Priority.NORMAL); HealthSeriesBuilder builder = new HealthSeriesBuilder(descriptor); StaticAnalysisRun run = createSimpleBuildResult(3); List<Integer> computeResult = builder.computeSeries(run); assertThat(computeResult).hasSize(1); assertThat(computeResult).startsWith(3); }

Target:
void nonEnabledHealthReport() { HealthSeriesBuilder builder = createBuilder("2", "1", Priority.NORMAL); StaticAnalysisRun run = createSimpleBuildResult(3); List<Integer> computeResult = builder.computeSeries(run); assertThat(computeResult).containsExactly(3); }
Source:
public BackendInternal getBackend() { return super.getBackend(); }

Target:
public BackendInternal getBackend() { return Backend.getInstance(); }
Source:
private ByteBuffer deepCopyBuffer(ByteBuf byteBuf) { ByteBuffer buffer = byteBuf.nioBuffer(); int offset = buffer.position(); int size = buffer.remaining(); byte[] duplicate = new byte[size]; for (int i = 0; i < size; i++) { duplicate[i] = buffer.get(i + offset); } return ByteBuffer.wrap(duplicate); }

Target:
private static ByteBuffer deepCopyBuffer(ByteBuf byteBuf) { ByteBuffer buffer = ByteBuffer.allocate(byteBuf.readableBytes()); byteBuf.readBytes(buffer); buffer.rewind(); return buffer; }
Source:
ListBookiesCmd() { super(CMD_LISTBOOKIES); opts.addOption("rw", "readwrite", false, "Print readwrite bookies"); opts.addOption("ro", "readonly", false, "Print readonly bookies"); }

Target:
ListBookiesCmd() { super(CMD_LISTBOOKIES); opts.addOption("rw", "readwrite", false, "Print readwrite bookies"); opts.addOption("ro", "readonly", false, "Print readonly bookies"); opts.addOption("h", "hostnames", false, "Also print hostname of the bookie"); }
Source:
public KuduTableHandle getTableHandle(ConnectorSession session, SchemaTableName schemaTableName) { try { KuduTable table = clientSession.openTable(schemaTableName); return new KuduTableHandle(connectorId, schemaTableName, table); } catch (Exception e) { return null; } }

Target:
public KuduTableHandle getTableHandle(ConnectorSession session, SchemaTableName schemaTableName) { try { KuduTable table = clientSession.openTable(schemaTableName); return new KuduTableHandle(connectorId, schemaTableName, table); } catch (NotFoundException e) { return null; } }
Source:
public boolean deployAllAPIsAtGatewayStartup (Set<String> assignedGatewayLabels) { if (gatewayArtifactSynchronizerProperties.isRetrieveFromStorageEnabled()) { if (artifactRetriever != null) { try { for (Iterator<String> it = assignedGatewayLabels.iterator(); it.hasNext();) { String label = it.next(); List<String> gatewayRuntimeArtifacts = ServiceReferenceHolder .getInstance().getArtifactRetriever().retrieveAllArtifacts(label); for (String APIruntimeArtifact :gatewayRuntimeArtifacts){ GatewayAPIDTO gatewayAPIDTO = null; try { gatewayAPIDTO = new Gson().fromJson(APIruntimeArtifact, GatewayAPIDTO.class); log.info("Deploying synapse artifacts of " + gatewayAPIDTO.getName()); apiGatewayAdmin.deployAPI(gatewayAPIDTO); } catch (AxisFault axisFault) { log.error("Error in deploying" + gatewayAPIDTO.getName()+ " to the Gateway "); continue; } } } return true; } catch (ArtifactSynchronizerException e ) { log.error("Error deploying APIs to the Gateway " + e ); } } else { log.error("Artifact retriever not found"); } } return false; }

Target:
public boolean deployAllAPIsAtGatewayStartup (Set<String> assignedGatewayLabels) { if (gatewayArtifactSynchronizerProperties.isRetrieveFromStorageEnabled()) { if (artifactRetriever != null) { try { Iterator<String> it = assignedGatewayLabels.iterator(); while (it.hasNext()) { String label = it.next(); List<String> gatewayRuntimeArtifacts = ServiceReferenceHolder .getInstance().getArtifactRetriever().retrieveAllArtifacts(label); for (String APIruntimeArtifact :gatewayRuntimeArtifacts){ GatewayAPIDTO gatewayAPIDTO = null; try { if (APIruntimeArtifact != null) { gatewayAPIDTO = new Gson().fromJson(APIruntimeArtifact, GatewayAPIDTO.class); log.info("Deploying synapse artifacts of " + gatewayAPIDTO.getName()); apiGatewayAdmin.deployAPI(gatewayAPIDTO); } } catch (AxisFault axisFault) { log.error("Error in deploying" + gatewayAPIDTO.getName()+ " to the Gateway "); continue; } } } return true; } catch (ArtifactSynchronizerException e ) { log.error("Error deploying APIs to the Gateway " + e ); } } else { log.error("Artifact retriever not found"); } } return false; }
Source:
private Cursor getNicknameCursor(String nickname) { Uri queryUriForNickname = ContactsContract.Data.CONTENT_URI; final String[] PROJECTION_NICKNAME = new String[] { ContactsContract.Data.CONTACT_ID, ContactsContract.CommonDataKinds.Nickname.NAME }; return getContext().getContentResolver().query(queryUriForNickname, PROJECTION_NICKNAME, ContactsContract.CommonDataKinds.Nickname.NAME + " LIKE ? AND " + Data.MIMETYPE + " = ?", new String[] { nickname, ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE }, null); }

Target:
private Cursor getNicknameCursor(String nickname) { nickname = "%" + nickname + "%"; Uri queryUriForNickname = ContactsContract.Data.CONTENT_URI; return getContext().getContentResolver().query(queryUriForNickname, PROJECTION_NICKNAME, ContactsContract.CommonDataKinds.Nickname.NAME + " LIKE ? AND " + Data.MIMETYPE + " = ?", new String[] { nickname, ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE }, null); }
Source:
public long getLastCacheUpdateTime(String cacheType, String cacheKey) { try { if (cacheType == null || cacheKey == null || Constants.EMPTY_STRING.equals(cacheType) || Constants.EMPTY_STRING.equals(cacheKey)) { return 0; } final String soupName = cacheType + cacheKey; if (!doesCacheExist(soupName)) { return 0; } final String smartSql = "SELECT {" + soupName + ":" + String.format(CACHE_TIME_KEY, cacheKey) + "} FROM {" + soupName + "}"; QuerySpec querySpec = QuerySpec.buildSmartQuerySpec(smartSql, 10); int count = smartStore.countQuery(querySpec); if (count == 0) { return 0; } querySpec = QuerySpec.buildSmartQuerySpec(smartSql, count); final JSONArray results = smartStore.query(querySpec, 0); if (results != null && results.length() > 0) { final JSONArray array = results.optJSONArray(0); if (array != null && array.length() > 0) { final String res = array.optString(0); if (res != null && !Constants.EMPTY_STRING.equals(res)) { return Long.parseLong(res); } } } } catch (IllegalStateException e) { Log.e(TAG, "IllegalStateException occurred while attempting to read last cached time", e); } catch (JSONException e) { Log.e(TAG, "JSONException occurred while attempting to read last cached time", e); } catch (SmartStoreException e) { Log.e(TAG, "SmartStoreException occurred while attempting to read last cached time", e); } return 0; }

Target:
public long getLastCacheUpdateTime(String cacheType, String cacheKey) { try { if (cacheType == null || cacheKey == null || Constants.EMPTY_STRING.equals(cacheType) || Constants.EMPTY_STRING.equals(cacheKey)) { return 0; } final String soupName = cacheType + cacheKey; if (!doesCacheExist(soupName)) { return 0; } final String smartSql = "SELECT {" + soupName + ":" + String.format(CACHE_TIME_KEY, cacheKey) + "} FROM {" + soupName + "}"; final QuerySpec querySpec = QuerySpec.buildSmartQuerySpec(smartSql, 1); final JSONArray results = smartStore.query(querySpec, 0); if (results != null && results.length() > 0) { final JSONArray array = results.optJSONArray(0); if (array != null && array.length() > 0) { return array.optLong(0); } } } catch (IllegalStateException e) { Log.e(TAG, "IllegalStateException occurred while attempting to read last cached time", e); } catch (JSONException e) { Log.e(TAG, "JSONException occurred while attempting to read last cached time", e); } catch (SmartStoreException e) { Log.e(TAG, "SmartStoreException occurred while attempting to read last cached time", e); } return 0; }