auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private boolean shouldFlushL1(TxInvocationContext ctx) { return shouldInvokeRemoteTxCommand(ctx) || // We fall into this situation if we are a remote node, happen to be the primary data owner and have locked keys. // it is still our responsibility to invalidate L1 caches in the cluster. !ctx.isOriginLocal() && !ctx.getAffectedKeys().isEmpty(); }

Target:
private boolean shouldFlushL1(TxInvocationContext ctx) { return !ctx.getAffectedKeys().isEmpty(); }
Source:
public Object visitDataWriteCommand(InvocationContext ctx, DataWriteCommand command, boolean assumeOriginKeptEntryInL1) throws Throwable { Object returnValue = invokeNextInterceptor(ctx, command); Object key; if (shouldUpdateOnWriteCommand(command) && command.isSuccessful() && cdl.localNodeIsPrimaryOwner((key = command.getKey()))) { getLog().tracef("Sending additional invalidation for requestors if necessary."); // Send out a last attempt L1 invalidation in case if someone cached the L1 // value after they already received an invalidation l1Manager.flushCache(Collections.singleton(key), ctx.getOrigin(), assumeOriginKeptEntryInL1); } return returnValue; }

Target:
public Object visitDataWriteCommand(InvocationContext ctx, DataWriteCommand command, boolean assumeOriginKeptEntryInL1) throws Throwable { Object returnValue = invokeNextInterceptor(ctx, command); Object key; if (shouldUpdateOnWriteCommand(command) && command.isSuccessful() && cdl.localNodeIsPrimaryOwner((key = command.getKey()))) { if (trace) { log.trace("Sending additional invalidation for requestors if necessary."); } // Send out a last attempt L1 invalidation in case if someone cached the L1 // value after they already received an invalidation l1Manager.flushCache(Collections.singleton(key), ctx.getOrigin(), assumeOriginKeptEntryInL1); } return returnValue; }
Source:
public void testGetOnlyQueriesCacheOnOwners() throws CacheLoaderException { prepareClearTest(); // Make a key that own'ers is c1 and c2 final MagicKey k = new MagicKey("key1", c1, c2); final String v1 = "real-data"; final String v2 = "stale-data"; // Simulate c3 was by itself and someone wrote a value that is now stale CacheStore store = TestingUtil.extractComponent(c3, CacheLoaderManager.class).getCacheStore(); store.store(TestInternalCacheEntryFactory.create(k, v2)); c1.put(k, v1); assertEquals(v1, c3.get(k)); }

Target:
public void testGetOnlyQueriesCacheOnOwners() throws CacheLoaderException { // Make a key that own'ers is c1 and c2 final MagicKey k = new MagicKey("key1", c1, c2); final String v1 = "real-data"; final String v2 = "stale-data"; // Simulate c3 was by itself and someone wrote a value that is now stale CacheStore store = TestingUtil.extractComponent(c3, CacheLoaderManager.class).getCacheStore(); store.store(TestInternalCacheEntryFactory.create(k, v2)); c1.put(k, v1); assertEquals(v1, c3.get(k)); }
Source:
public Object visitPrepareCommand(TxInvocationContext ctx, PrepareCommand command) throws Throwable { //if it is remote and 2PC then first log the tx only after replying mods if (this.statisticsEnabled) prepares.incrementAndGet(); Object result = invokeNextInterceptorAndVerifyTransaction(ctx, command); if (!ctx.isOriginLocal()) { if (command.isOnePhaseCommit()) { txTable.remoteTransactionCommitted(command.getGlobalTransaction(), false); } else { txTable.remoteTransactionPrepared(command.getGlobalTransaction()); } } return result; }

Target:
public Object visitPrepareCommand(TxInvocationContext ctx, PrepareCommand command) throws Throwable { //if it is remote and 2PC then first log the tx only after replying mods if (this.statisticsEnabled) prepares.incrementAndGet(); Object result = invokeNextInterceptorAndVerifyTransaction(ctx, command); if (!ctx.isOriginLocal()) { if (command.isOnePhaseCommit()) { txTable.remoteTransactionCommitted(command.getGlobalTransaction(), true); } else { txTable.remoteTransactionPrepared(command.getGlobalTransaction()); } } return result; }
Source:
public Object visitKeySetCommand(InvocationContext ctx, KeySetCommand command) throws Throwable { Object keys = super.visitKeySetCommand(ctx, command); // TODO: this doesn't do write through to the back end store and currently doesn't even do write through to the // backend data container if (enabled && passivationEnabled && !shouldSkipCacheLoader(command)) { Set<Object> set = loader.loadAllKeys(Collections.emptySet()); Set<Object> union = new HashSet<Object>(set); union.addAll((Set<Object>)keys); return Collections.unmodifiableSet(union); } return keys; }

Target:
public Object visitKeySetCommand(InvocationContext ctx, KeySetCommand command) throws Throwable { Object keys = super.visitKeySetCommand(ctx, command); if (enabled && !shouldSkipCacheLoader(command)) { Set<Object> union = new HashSet<Object>((Set<Object>)keys); // Exclude the keys in memory as we don't want to deserialize those again union.addAll(loader.loadAllKeys(union)); return Collections.unmodifiableSet(union); } return keys; }
Source:
public void stop() { // Clear class cache marshallableTypeHints.clear(); // Clear thread local marshallerTL.remove(); }

Target:
public void stop() { // Clear class cache marshallableTypeHints.clear(); }
Source:
protected Set<byte[]> executeOperation(Transport transport) { HeaderParams params = writeHeader(transport, BULK_GET_KEYS_REQUEST); transport.flush(); System.out.println("hello"); readHeaderAndValidate(transport, params); System.out.println("validated"); Set<byte[]> result = new HashSet<byte[]>(); while ( transport.readByte() == 1) { //there's more! result.add(transport.readArray()); } return result; }

Target:
protected Set<byte[]> executeOperation(Transport transport) { HeaderParams params = writeHeader(transport, BULK_GET_KEYS_REQUEST); transport.flush(); readHeaderAndValidate(transport, params); Set<byte[]> result = new HashSet<byte[]>(); while ( transport.readByte() == 1) { //there's more! result.add(transport.readArray()); } return result; }
Source:
protected boolean getPermissionToJoin() throws Exception { boolean gotPermission; if (distributionManager.isJoinComplete()) { throw new IllegalStateException("Join on " + getMyAddress() + " cannot be complete without rehash to finishing"); } // 1. Get chOld from coord. chOld = retrieveOldConsistentHash(); gotPermission = true; // 2. new CH instance if (chOld.getCaches().contains(self)) chNew = chOld; else chNew = createConsistentHash(configuration, chOld.getCaches(), distributionManager.getTopologyInfo(), self); return gotPermission; }

Target:
protected void getPermissionToJoin() throws Exception { if (distributionManager.isJoinComplete()) { throw new IllegalStateException("Join on " + getMyAddress() + " cannot be complete without rehash to finishing"); } // 1. Get chOld from coord. chOld = retrieveOldConsistentHash(); // 2. new CH instance if (chOld.getCaches().contains(self)) chNew = chOld; else chNew = createConsistentHash(configuration, chOld.getCaches(), distributionManager.getTopologyInfo(), self); }
Source:
public CredentialsSVNAuthenticationProviderImpl(Credentials credentials) { this.provider = new RemotableSVNAuthenticationBuilderProvider(credentials, Collections.<String, Credentials>emptyMap(), /* TODO */ TaskListener.NULL); }

Target:
public CredentialsSVNAuthenticationProviderImpl(Credentials credentials) { this(credentials, null, /* TODO */ TaskListener.NULL); }
Source:
public RosActivity(String notificationTicker, String notificationTitle) { super(); rosActivityComponent = new RosActivityComponent(this, notificationTicker, notificationTitle, new RosActivityEventsHandler()); }

Target:
public RosActivity(String notificationTicker, String notificationTitle) { rosActivityComponent = new RosActivityComponent(this, notificationTicker, notificationTitle, new RosActivityEventsHandler()); }
Source:
public static long crc32(String data) { if (data == null) { return -1; } try { // get bytes from string byte bytes[] = data.getBytes("UTF-8"); Checksum checksum = new CRC32(); // update the current checksum with the specified array of bytes checksum.update(bytes, 0, bytes.length); // get the current checksum value return checksum.getValue(); } catch (UnsupportedEncodingException e) { return -1; } }

Target:
public static long crc32(String data) { if (data == null) { return -1; } try { // get bytes from string byte bytes[] = data.getBytes("UTF-8"); Checksum checksum = new CRC32(); // update the current checksum with the specified array of bytes checksum.update(bytes, 0, bytes.length); // get the current checksum value return checksum.getValue(); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } }
Source:
private Double getOverlappingPercentages(double cMin, double cMax, double bMin, double bMax) { if (cMin > bMax || cMax < bMin) { return 0.0; } double regionMin = Math.max(cMin, bMin); double regionMax = Math.min(cMax, bMax); double dividend = regionMax - regionMin; double divider = bMax - bMin; if (dividend == divider) return 1.0; else return dividend / divider; }

Target:
private Double getOverlappingPercentages(double cMin, double cMax, double bMin, double bMax) { if (cMin > bMax || cMax < bMin) { return 0.0; } double regionMin = Math.max(cMin, bMin); double regionMax = Math.min(cMax, bMax); double dividend = regionMax - regionMin; double divider = bMax - bMin; if (divider == 0.0) { // bucket min and max are equal, handling 0 divider case if (dividend == 0.0) { return 1.0; } else return 0.0; } else return dividend / divider; }
Source:
public Batch getNextEmptyBatch() throws InterruptedException { synchronized(availableBatches) { if (availableBatches.isEmpty()) { availableBatches.wait(); Integer batchIdx = availableBatches.pop(); return batches[batchIdx]; } Integer batchIdx = availableBatches.pop(); return batches[batchIdx]; } }

Target:
public Batch getNextEmptyBatch() throws InterruptedException { synchronized(availableBatches) { while (availableBatches.isEmpty()) { availableBatches.wait(); } Integer batchIdx = availableBatches.pop(); return batches[batchIdx]; } }
Source:
public UserInfo about(String username) throws ActionFailedException { // Send GET request to get the account overview if(username == "[deleted]") throw new ActionFailedException("There is no information associated with the username [deleted]"); JSONObject object = (JSONObject) restClient.get(String.format(ApiEndpointUtils.USER_ABOUT, username), null).getResponseObject(); JSONObject data = (JSONObject) object.get("data"); // Init account info wrapper return data != null ? new UserInfo(data) : null; }

Target:
public UserInfo about(String username) throws ActionFailedException { // Send GET request to get the account overview if(username.equals("[deleted]")) { throw new ActionFailedException("There is no information associated with the username [deleted]"); } JSONObject object = (JSONObject) restClient.get(String.format(ApiEndpointUtils.USER_ABOUT, username), null).getResponseObject(); JSONObject data = (JSONObject) object.get("data"); // Init account info wrapper return data != null ? new UserInfo(data) : null; }
Source:
public CifsTelnetConnection(String type, ConnectionOptions options, AddressPortMapper mapper) { super(type, options, mapper, true); ConnectionValidator.assertIsWindowsHost(os, CIFS_PROTOCOL, cifsConnectionType); ConnectionValidator.assertNotNewStyleWindowsDomain(username, CIFS_PROTOCOL, cifsConnectionType); // Make sure that we're properly cleaned up by setting the connected state. connected(); }

Target:
public CifsTelnetConnection(String type, ConnectionOptions options, AddressPortMapper mapper) { super(type, options, mapper); }
Source:
private synchronized void drainQueueForRequests() { final PrefetchRecordsRetrieved recordsToDeliver = (PrefetchRecordsRetrieved) peekNextResult(); // If there is an event available to drain and if there is at least one demand, // then schedule it for delivery if (publisherSession.hasDemandToPublish() && canDispatchRecord(recordsToDeliver)) { subscriber.onNext(recordsToDeliver.prepareForPublish()); recordsToDeliver.dispatched(); lastEventDeliveryTime = Instant.now(); } }

Target:
synchronized void drainQueueForRequests() { final PrefetchRecordsRetrieved recordsToDeliver = peekNextResult(); // If there is an event available to drain and if there is at least one demand, // then schedule it for delivery if (publisherSession.hasDemandToPublish() && canDispatchRecord(recordsToDeliver)) { subscriber.onNext(recordsToDeliver.prepareForPublish()); recordsToDeliver.dispatched(); lastEventDeliveryTime = Instant.now(); } }
Source:
@Override public synchronized Boolean isLeader(String workerId) { // if no leaders yet, synchronously get leaders. This will happen at first Shard Sync. if (executeConditionCheckWithReadLock(() -> CollectionUtils.isNullOrEmpty(leaders))) { electLeaders(); // start a scheduled executor that will periodically update leaders. // The first run will be after a minute. // We don't need jitter since it is scheduled with a fixed delay and time taken to scan leases // will be different at different times and on different hosts/workers. leaderElectionThreadPool.scheduleWithFixedDelay(this::electLeaders, ELECTION_INITIAL_DELAY_MILLIS, ELECTION_SCHEDULING_INTERVAL_MILLIS, TimeUnit.MILLISECONDS); } return executeConditionCheckWithReadLock(() -> isWorkerLeaderForShardSync(workerId)); }

Target:
public synchronized Boolean isLeader(String workerId) { // if no leaders yet, synchronously get leaders. This will happen at first Shard Sync. if (executeConditionCheckWithReadLock(() -> CollectionUtils.isNullOrEmpty(leaders))) { electLeaders(); // start a scheduled executor that will periodically update leaders. // The first run will be after a minute. // We don't need jitter since it is scheduled with a fixed delay and time taken to scan leases // will be different at different times and on different hosts/workers. leaderElectionThreadPool.scheduleWithFixedDelay(this::electLeaders, ELECTION_INITIAL_DELAY_MILLIS, ELECTION_SCHEDULING_INTERVAL_MILLIS, TimeUnit.MILLISECONDS); } return executeConditionCheckWithReadLock(() -> isWorkerLeaderForShardSync(workerId)); }
Source:
public NSDictionary searchTargetNSDict(NSDictionary rootDict, CoffeeName targetName) { final NSArray itemNSArray = (NSArray) (rootDict .objectForKey(ITEM_ARRAY)); NSDictionary resultDict = null; for (NSObject item : itemNSArray.getArray()) { final NSDictionary dict = (NSDictionary) item; final String itemName = NSDictionaryHelper.stringForKey(dict, CoffeeName.ITEM_NAME); if (!TextUtils.equals(targetName.getCoffeeName(), itemName)) { // mCoffeeNameと異なる場合は次へ continue; } resultDict = dict; } return resultDict; }

Target:
public NSDictionary searchTargetNSDict(NSDictionary rootDict, CoffeeName targetName) { final NSArray itemNSArray = (NSArray) (rootDict .objectForKey(ITEM_ARRAY)); NSDictionary resultDict = null; for (NSObject item : itemNSArray.getArray()) { final NSDictionary dict = (NSDictionary) item; final String itemName = NSDictionaryHelper.stringForKey(dict, CoffeeName.ITEM_NAME); if (TextUtils.equals(targetName.getCoffeeName(), itemName)) { return dict; } } return resultDict; }
Source:
public static String docsVersion() { if (Version.VERSION.matches("^\\d*\\.\\d*\\.\\d*$")) { //FIXME once we know how readthedocs handles version tags return Version.VERSION; } else { return "latest"; } }

Target:
public static String docsVersion() { //FIXME once we know how readthedocs handles version tags // if (Version.VERSION.matches("^\\d*\\.\\d*\\.\\d*$")) { // return Version.VERSION; // } else { return "latest"; // } }
Source:
public void addQc(Library library, LibraryQC qc) throws IOException { Library managed = libraryDao.get(library.getId()); authorizationManager.throwIfNotWritable(managed); qc.setQcCreator(authorizationManager.getCurrentUsername()); // update concentration if QC is of relevant type if ("QuBit".equals(qc.getQcType().getName())) { managed.setInitialConcentration(qc.getResults()); } libraryQcDao.save(qc); libraryDao.save(library); }

Target:
public void addQc(Library library, LibraryQC qc) throws IOException { Library managed = libraryDao.get(library.getId()); authorizationManager.throwIfNotWritable(managed); qc.setQcCreator(authorizationManager.getCurrentUsername()); // TODO: update concentration if QC is of relevant type libraryQcDao.save(qc); libraryDao.save(library); }
Source:
public void setDefaultProjectDao() { HibernateProjectDao dao = new HibernateProjectDao(); dao.setJdbcTemplate(jdbcTemplate); dao.setSecurityManager(securityManager); dao.setSecurityProfileDAO(securityProfileDao); dao.setNamingScheme(getNamingScheme()); dao.setDataObjectFactory(dataObjectFactory); dao.setReferenceGenomeDao(referenceGenomeDao); setProjectDao(dao); }

Target:
public void setDefaultProjectDao() { HibernateProjectDao dao = new HibernateProjectDao(); dao.setJdbcTemplate(jdbcTemplate); setProjectDao(dao); }
Source:
public void setIpAddress(String ip) { if (ip == null) { this.ip = null; } else { try { InetAddress inet = InetAddress.getByName(ip); this.ip = (inet != null ? inet.getHostAddress() : null); } catch (IOException e) { log.error("Error getting InetAddress from given ip " + ip, e); this.ip = null; } } }

Target:
public void setIpAddress(String ip) { if (ip == null) { this.ip = null; } else { try { InetAddress inet = InetAddress.getByName(ip); this.ip = (inet != null ? inet.getHostAddress() : null); } catch (IOException e) { log.error("Error getting InetAddress from given ip " + ip, e); throw new IllegalArgumentException("Error getting InetAddress from given ip " + ip, e); } } }
Source:
private static Activity getActivity(final Context context) { if (context == null) { // TODO Mapsme API will do a hard cast. We could locally fix this by re-declaring all API methods return null; } else if (context instanceof Activity) { return (Activity) context; } else if (context instanceof ContextWrapper) { return getActivity(((ContextWrapper) context).getBaseContext()); } return null; }

Target:
private static Activity getActivity(final Context context) { // TODO Mapsme API will do a hard cast. We could locally fix this by re-declaring all API methods if (context instanceof Activity) { return (Activity) context; } else if (context instanceof ContextWrapper) { return getActivity(((ContextWrapper) context).getBaseContext()); } return null; }
Source:
public void increaseActualCachesFound() { if (actualCachesFound >= 0) { setActualCachesFound(actualCachesFound + 1); } }

Target:
public void increaseActualCachesFound() { if (actualCachesFound >= 0) { actualCachesFound++; } }
Source:
public void testShouldRemoveNoCache() throws Exception { // GIVEN lists1.add(LIST_ID1); lists2.add(LIST_ID3); lists3.add(LIST_ID3); final Set<Geocache> toBeRemoved = RemoveNotUniqueHelper.removeNonUniqueCaches(geoCaches); assertThat(toBeRemoved.size()).isEqualTo(0); assertThat(toBeRemoved.contains(gc1)).isFalse(); assertThat(toBeRemoved.contains(gc2)).isFalse(); assertThat(toBeRemoved.contains(gc3)).isFalse(); }

Target:
public void testShouldRemoveNoCache() { // GIVEN lists1.add(LIST_ID1); lists2.add(LIST_ID3); lists3.add(LIST_ID3); // WHEN final Set<Geocache> toBeRemoved = RemoveNotUniqueHelper.removeNonUniqueCaches(geoCaches); // THEN assertThat(toBeRemoved.size()).isEqualTo(0); assertThat(toBeRemoved.contains(gc1)).isFalse(); assertThat(toBeRemoved.contains(gc2)).isFalse(); assertThat(toBeRemoved.contains(gc3)).isFalse(); }
Source:
private void initializeCommonFields() { supportRequestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); AndroidBeam.disable(this); // initialize commonly used members res = this.getResources(); app = (CgeoApplication) this.getApplication(); // only needed in some activities, but implemented in super class nonetheless Cookies.restoreCookieStore(Settings.getCookieStore()); ActivityMixin.onCreate(this, keepScreenOn); }

Target:
private void initializeCommonFields() { // initialize commonly used members res = this.getResources(); app = (CgeoApplication) this.getApplication(); // only needed in some activities, but implemented in super class nonetheless Cookies.restoreCookieStore(Settings.getCookieStore()); ActivityMixin.onCreate(this, keepScreenOn); }
Source:
protected InputStream getInputStream() throws IOException { try { return contentResolver.openInputStream(uri); } catch (final FileNotFoundException e) { // for http links, we may need to download the content ourself, if it has no mime type announced by the browser if (uri.toString().startsWith("http")) { return Network.getResponseStream(Network.getRequest(uri.toString())); } // only log error for non-http URI Log.e("GpxZip import cannot resolve " + uri); } return null; }

Target:
protected InputStream getInputStream() throws IOException { try { return contentResolver.openInputStream(uri); } catch (final FileNotFoundException e) { // for http links, we may need to download the content ourself, if it has no mime type announced by the browser if (uri.toString().startsWith("http")) { return Network.getResponseStream(Network.getRequest(uri.toString())); } } Log.e("GpxZip import cannot resolve " + uri); return null; }
Source:
public void addInventoryItem(final Trackable newTrackable) { if (inventory == null) { inventory = new ArrayList<Trackable>(); } Boolean foundTrackable = false; for (final Trackable trackable: inventory) { if (trackable.getUniqueID().equals(newTrackable.getUniqueID())) { // Trackable already present, merge data foundTrackable = true; trackable.mergeTrackable(newTrackable); break; } } if (!foundTrackable) { inventory.add(newTrackable); } inventoryItems = inventory.size(); }

Target:
public void addInventoryItem(final Trackable newTrackable) { if (inventory == null) { inventory = new ArrayList<>(); } Boolean foundTrackable = false; for (final Trackable trackable: inventory) { if (trackable.getUniqueID().equals(newTrackable.getUniqueID())) { // Trackable already present, merge data foundTrackable = true; trackable.mergeTrackable(newTrackable); break; } } if (!foundTrackable) { inventory.add(newTrackable); } inventoryItems = inventory.size(); }
Source:
public DistanceComparator() { this.coords = null; this.list = null; }

Target:
public DistanceComparator() { // This constructor should not be used as a comparator as distances will not be updated. // It is needed in order to really know we are sorting by Distances in the sort menu. // If you need it for sorting, please use the second construtor coords = null; list = new ArrayList<>(); }
Source:
public static List<Trackable> parse(final InputSource page) { try { // Create a new instance of the SAX parser SAXParserFactory saxPF = SAXParserFactory.newInstance(); SAXParser saxP = saxPF.newSAXParser(); XMLReader xmlR = saxP.getXMLReader(); // Create the Handler to handle each of the XML tags. final GeokretyHandler gkXMLHandler = new GeokretyHandler(); xmlR.setContentHandler(gkXMLHandler); xmlR.parse(page); return gkXMLHandler.getTrackables(); } catch (final Exception e) { Log.w("Cannot parse geokrety", e); } return null; }

Target:
public static List<Trackable> parse(final InputSource page) { try { // Create a new instance of the SAX parser final SAXParserFactory saxPF = SAXParserFactory.newInstance(); final SAXParser saxP = saxPF.newSAXParser(); final XMLReader xmlR = saxP.getXMLReader(); // Create the Handler to handle each of the XML tags. final GeokretyHandler gkXMLHandler = new GeokretyHandler(); xmlR.setContentHandler(gkXMLHandler); xmlR.parse(page); return gkXMLHandler.getTrackables(); } catch (final Exception e) { Log.w("Cannot parse geokrety", e); } return null; }
Source:
public SearchResult loadInBackground() { loading = true; if (search == null) { search = runSearch(); } else { //Unless we make a new Search the Loader framework won't deliver results. It does't do equals only identity SearchResult newSearch = new SearchResult(search); newSearch.setUrl(search.getUrl()); newSearch.setViewstates(search.getViewstates()); search = GCParser.searchByNextPage(newSearch, Settings.isShowCaptcha(), this); } loading = false; return search; }

Target:
public SearchResult loadInBackground() { loading = true; if (search == null) { search = runSearch(); } else { // Unless we make a new Search the Loader framework won't deliver results. It does't do equals only identity search = GCParser.searchByNextPage(new SearchResult(search), Settings.isShowCaptcha(), this); } loading = false; return search; }
Source:
public boolean isMapDatabaseSwitchSupported() { return !getMapGenerator().requiresInternetConnection() && null != Settings.getMapFile(); //if no file is specified in settings then disable the switch map option }

Target:
public boolean isMapDatabaseSwitchSupported() { if (getMapGenerator().requiresInternetConnection()) { return false; } if (null == Settings.getMapFile()) { //if no file is specified in settings then disable the switch map option return false; } return true; }
Source:
public void failToFindNonExistentElement() { WebDriver d = getDriver(); d.get("http://www.google.com"); try { WebElement inputField = d.findElement(By.cssSelector("input[name='idontexist']")); fail(); } catch (NoSuchElementException e) { // expected } }

Target:
public void failToFindNonExistentElement() { WebDriver d = getDriver(); d.get("http://www.google.com"); WebElement inputField = d.findElement(By.cssSelector("input[name='idontexist']")); }
Source:
public void peopleMessage(final PeopleDescription peopleDescription) { try { peopleDescription.getMessage().toString(); final Message m = Message.obtain(); m.what = ENQUEUE_PEOPLE; m.obj = peopleDescription; mWorker.runMessage(m); } catch (AssertionError e) { MPLog.e(LOGTAG, "Could not record people update (see https://github.com/mixpanel/mixpanel-android/issues/567)", e); } }

Target:
public void peopleMessage(final PeopleDescription peopleDescription) { final Message m = Message.obtain(); m.what = ENQUEUE_PEOPLE; m.obj = peopleDescription; mWorker.runMessage(m); }
Source:
protected Intent buildIntentForUri(Uri uri) { return new Intent(Intent.ACTION_VIEW, uri); }

Target:
/* package */ Intent buildIntentForUri(Uri uri) { return new Intent(Intent.ACTION_VIEW, uri); }
Source:
public String getStringValue() { String ret = null; try { ret = (String) defaultValue; } catch (ClassCastException e2) { ; // ok } try { ret = (String) value; } catch (ClassCastException e) { ; // ok } return ret; }

Target:
public String getStringValue() { String ret = null; try { ret = (String) defaultValue; } catch (ClassCastException e) { ; // ok } try { ret = (String) value; } catch (ClassCastException e) { ; // ok } return ret; }
Source:
public void run() { if (!mAlive) { return; } final View viewRoot = mViewRoot.get(); if (null == viewRoot || mDying) { cleanUp(); return; } // ELSE View is alive and we are alive try { mEdit.visit(viewRoot); } catch (ViewVisitor.LayoutUpdateException e) { cleanUp(); throw e; } mHandler.removeCallbacks(this); mHandler.postDelayed(this, 1000); }

Target:
public void run() { if (!mAlive) { return; } final View viewRoot = mViewRoot.get(); if (null == viewRoot || mDying) { cleanUp(); return; } // ELSE View is alive and we are alive mEdit.visit(viewRoot); mHandler.removeCallbacks(this); mHandler.postDelayed(this, 1000); }
Source:
private CompletableFuture<Void> rollbackLocks(CommitData cd) throws Exception { CommitStep firstStep = new RollbackOtherLocks(); firstStep.andThen(new RollbackPrimaryLock()); return firstStep.compose(cd) .thenRun(() -> cd.commitObserver.commitFailed(cd.getShortCollisionMessage())); }

Target:
private CompletableFuture<Void> rollbackLocks(CommitData cd) { CommitStep firstStep = new RollbackOtherLocks(); firstStep.andThen(new RollbackPrimaryLock()); return firstStep.compose(cd) .thenRun(() -> cd.commitObserver.commitFailed(cd.getShortCollisionMessage())); }
Source:
public void beginSecondCommitPhase(CommitData cd, Stamp commitStamp) throws Exception { if (startTs < commitStamp.getGcTimestamp()) { rollbackOtherLocks(cd); } else { // Notification are written here for the following reasons : // * At this point all columns are locked, this guarantees that anything triggering as a // result of this transaction will see all of this transactions changes. // * The transaction is not yet committed. If the process dies at this point whatever // was running this transaction should rerun and recreate all of the notifications. // The next transactions will rerun because this transaction will have to be rolled back. // * If notifications are written in the 2nd phase of commit, then when the 2nd phase // partially succeeds notifications may never be written. Because in the case of failure // notifications would not be written until a column is read and it may never be read. // See https://github.com/fluo-io/fluo/issues/642 // // Its very important the notifications which trigger an observer are deleted after the 2nd // phase of commit finishes. getStats().setCommitTs(commitStamp.getTxTimestamp()); writeNotificationsAsync(cd, commitStamp.getTxTimestamp()); } }

Target:
private void beginSecondCommitPhase(CommitData cd, Stamp commitStamp) throws Exception { if (startTs < commitStamp.getGcTimestamp()) { rollbackOtherLocks(cd); } else { // Notification are written here for the following reasons : // * At this point all columns are locked, this guarantees that anything triggering as a // result of this transaction will see all of this transactions changes. // * The transaction is not yet committed. If the process dies at this point whatever // was running this transaction should rerun and recreate all of the notifications. // The next transactions will rerun because this transaction will have to be rolled back. // * If notifications are written in the 2nd phase of commit, then when the 2nd phase // partially succeeds notifications may never be written. Because in the case of failure // notifications would not be written until a column is read and it may never be read. // See https://github.com/fluo-io/fluo/issues/642 // // Its very important the notifications which trigger an observer are deleted after the 2nd // phase of commit finishes. getStats().setCommitTs(commitStamp.getTxTimestamp()); writeNotificationsAsync(cd, commitStamp.getTxTimestamp()); } }
Source:
public Long allocateTimestamp() { synchronized(status) { Preconditions.checkState(status != TrackerStatus.CLOSED, "tracker is closed"); if ((status == TrackerStatus.IDLE) && (node == null)) { // initialize zookeeper node first with a timestamp Long initialTs = getTimestamp(); if (node == null) { updateZkNode(initialTs); } } // retrieve timestamp to return Long ts = getTimestamp(); timestamps.add(ts); status = TrackerStatus.BUSY; //System.out.println("allocated "+ts); return ts; } }

Target:
public synchronized long allocateTimestamp() { // initialize zookeeper if idle and node does not exist Preconditions.checkState(status != TrackerStatus.CLOSED, "tracker is closed"); if ((status == TrackerStatus.IDLE) && (node == null)) { // initialize zookeeper node first with a timestamp long initialTs = getTimestamp(); if (node == null) { updateZkNode(initialTs); } } // retrieve timestamp to return long ts = getTimestamp(); // update timestamp set and status timestamps.add(ts); status = TrackerStatus.BUSY; return ts; }
Source:
public long allocateTimestamp() { // initialize zookeeper if idle and node does not exist synchronized(this) { Preconditions.checkState(status != TrackerStatus.CLOSED, "tracker is closed"); if ((status == TrackerStatus.IDLE) && (node == null)) { // initialize zookeeper node first with a timestamp Long initialTs = getTimestamp(); if (node == null) { updateZkNode(initialTs); } } } // retrieve timestamp to return long ts = getTimestamp(); // update timestamp set and status synchronized(this) { timestamps.add(ts); status = TrackerStatus.BUSY; } return ts; }

Target:
public synchronized long allocateTimestamp() { // initialize zookeeper if idle and node does not exist Preconditions.checkState(status != TrackerStatus.CLOSED, "tracker is closed"); if ((status == TrackerStatus.IDLE) && (node == null)) { // initialize zookeeper node first with a timestamp long initialTs = getTimestamp(); if (node == null) { updateZkNode(initialTs); } } // retrieve timestamp to return long ts = getTimestamp(); // update timestamp set and status timestamps.add(ts); status = TrackerStatus.BUSY; return ts; }
Source:
public boolean checkExists(Long transactorId) { // once a transactor has timed out, act like it does not exist even if still in zookeeper if (timeoutCache.getIfPresent(transactorId) != null) return false; return cache.getCurrentData(TransactorID.getNodePath(config, transactorId)) != null; }

Target:
public boolean checkExists(Long transactorId) { return cache.getCurrentData(TransactorID.getNodePath(config, transactorId)) != null; }
Source:
public void validateAllSupportedCiphers() throws IOException, DecoderException { /* Loop through each Supported Cipher for All Supported Providers*/ final Iterator<SupportedCipherDetails> i = CIPHERS_TO_TEST.iterator(); while (i.hasNext()) { final SupportedCipherDetails cipherDetails = i.next(); validateEncryptedFileWithHeaderValues(cipherDetails); } }

Target:
public void validateAllSupportedCiphers() throws IOException, DecoderException { /* Loop through each Supported Cipher for All Supported Providers*/ for (final SupportedCipherDetails cipherDetails : CIPHERS_TO_TEST) { validateEncryptedFileWithHeaderValues(cipherDetails); } }
Source:
public void testItValidatesMaxSizeOfPhotoShareByMessage() throws MalformedURLException { SharePhotoContent sharePhotoContent = new SharePhotoContent.Builder().addPhoto(buildSharePhoto("https://facebook.com/awesome-1.gif")) .addPhoto(buildSharePhoto("https://facebook.com/awesome-2.gif")) .addPhoto(buildSharePhoto("https://facebook.com/awesome-3.gif")) .addPhoto(buildSharePhoto("https://facebook.com/awesome-4.gif")) .addPhoto(buildSharePhoto("https://facebook.com/awesome-5.gif")) .addPhoto(buildSharePhoto("https://facebook.com/awesome-6.gif")) .addPhoto(buildSharePhoto("https://facebook.com/awesome-7.gif")) .build(); ShareContentValidation.validateForMessage(sharePhotoContent); }

Target:
public void testItValidatesMaxSizeOfPhotoShareByMessage() { SharePhotoContent sharePhotoContent = new SharePhotoContent.Builder() .addPhoto(buildSharePhoto("https://facebook.com/awesome-1.gif")) .addPhoto(buildSharePhoto("https://facebook.com/awesome-2.gif")) .addPhoto(buildSharePhoto("https://facebook.com/awesome-3.gif")) .addPhoto(buildSharePhoto("https://facebook.com/awesome-4.gif")) .addPhoto(buildSharePhoto("https://facebook.com/awesome-5.gif")) .addPhoto(buildSharePhoto("https://facebook.com/awesome-6.gif")) .addPhoto(buildSharePhoto("https://facebook.com/awesome-7.gif")) .build(); ShareContentValidation.validateForMessage(sharePhotoContent); }
Source:
public List<String> getStrings() { if (null == strings) { synchronized (this) { if (null == this.strings) { strings = new ArrayList<>(); // Noncompliant [[sc=11;ec=38;secondary=25,27]] {{Fully initialize "strings" before assigning it.}} strings.add("Hello"); System.out.println(); strings.add("World"); } } } return strings; }

Target:
public List<String> getStrings() { if (strings == null) { synchronized (this) { if (strings == null) { strings = new ArrayList<>(); // Noncompliant [[sc=11;ec=38;secondary=15,16]] {{Fully initialize "strings" before assigning it.}} strings.add("Hello"); strings.add("World"); } } } return strings; }
Source:
private boolean isMessageLoggedWithAdditionalContext() { if (loggingMethodInvocations.isEmpty()) { return false; } return loggingMethodInvocations.stream().anyMatch(mit -> hasGetMessageInvocation(mit) && hasDynamicExceptionMessageUsage(mit)); }

Target:
private boolean isMessageLoggedWithAdditionalContext() { return loggingMethodInvocations.stream().anyMatch(mit -> hasGetMessageInvocation(mit) && hasDynamicExceptionMessageUsage(mit)); }
Source:
void HttpCookie(String domain) { HttpCookie myCookie = new Cookie("name", "val"); myCookie.setDomain(".com"); // Noncompliant myCookie.setDomain(".myDomain.com"); // Compliant myCookie.setDomain(domain); // Compliant }

Target:
void HttpCookie(String domain) { HttpCookie myCookie = new HttpCookie("name", "val"); myCookie.setDomain(".com"); // Noncompliant myCookie.setDomain(".myDomain.com"); // Compliant myCookie.setDomain(domain); // Compliant }
Source:
protected static boolean isBot(Type type) { return ((JavaType) type).isTagged(JavaType.BOT); }

Target:
private static boolean isBot(Type type) { return ((JavaType) type).isTagged(JavaType.BOT); }
Source:
void testRecursion() { Math f = new Math() { // Compliant, recursion @Override public String powerOfTwo(int n) { return n == 0 ? 1 : 2 * powerOfTwo(n -1); } }; }

Target:
void testRecursion() { Math f = new Math() { // Compliant, recursion @Override public int powerOfTwo(int n) { return n == 0 ? 1 : 2 * powerOfTwo(n -1); } }; }
Source:
public void method_with_unknown_symbol_should_not_produce_ucfg() { CompilationUnitTree cut = getCompilationUnitTreeWithSemantics("class A {void foo(UnkownType t) {return t;}}"); UCFGJavaVisitor UCFGJavaVisitor = new UCFGJavaVisitor(tmp.getRoot()) { @Override protected void serializeUCFG(MethodTree tree, CFG cfg) { fail("should not serialize a UCFG of a method with unknown parameters"); } }; UCFGJavaVisitor.fileKey = FILE_KEY; UCFGJavaVisitor.visitCompilationUnit(cut); cut = getCompilationUnitTreeWithSemantics("class A {UnkownType foo(String t) {return t;}}"); UCFGJavaVisitor.visitCompilationUnit(cut); }

Target:
public void method_with_unknown_symbol_should_not_produce_ucfg() { UCFGJavaVisitor UCFGJavaVisitor = new UCFGJavaVisitor(tmp.getRoot()) { @Override protected void serializeUCFG(MethodTree tree, CFG cfg) { fail("should not serialize a UCFG of a method with unknown parameters"); } }; UCFGJavaVisitor.fileKey = FILE_KEY; // method with unknown arg CompilationUnitTree cut = getCompilationUnitTreeWithSemantics("class A {void foo(UnkownType t) {return t;}}"); UCFGJavaVisitor.visitCompilationUnit(cut); // method with unkown return type cut = getCompilationUnitTreeWithSemantics("class A {UnkownType foo(String t) {return t;}}"); UCFGJavaVisitor.visitCompilationUnit(cut); }
Source:
private static ExpressionTree instanceofFound(ExpressionTree expressionTree, Tree.Kind kind) { if (Tree.Kind.CONDITIONAL_OR.equals(kind)) { /* if CONDITIONAL_OR we want LOGICAL COMPLEMENT before instanceof */ if (expressionTree.is(Tree.Kind.LOGICAL_COMPLEMENT)) { return instanceofLHS(ExpressionUtils.skipParentheses(((UnaryExpressionTree) expressionTree).expression())); } else { return null; } } else { return instanceofLHS(expressionTree); } }

Target:
private static ExpressionTree instanceofFound(ExpressionTree expressionTree, Tree.Kind kind) { if (kind == Tree.Kind.CONDITIONAL_OR) { /* if CONDITIONAL_OR we want LOGICAL COMPLEMENT before instanceof */ if (expressionTree.is(Tree.Kind.LOGICAL_COMPLEMENT)) { return instanceofLHS(ExpressionUtils.skipParentheses(((UnaryExpressionTree) expressionTree).expression())); } else { return null; } } else { return instanceofLHS(expressionTree); } }
Source:
public void visitNewClass(NewClassTree tree) { super.visitNewClass(tree); ClassTree classBody = tree.classBody(); if (classBody != null) { TypeTree identifier = tree.identifier(); if (!useThisIdentifier(classBody) && !enumConstants.contains(identifier) && isSAM(classBody, identifier)) { context.reportIssue(this, identifier, "Make this anonymous inner class a lambda" + context.getJavaVersion().java8CompatibilityMessage()); } } }

Target:
public void visitNewClass(NewClassTree tree) { super.visitNewClass(tree); ClassTree classBody = tree.classBody(); if (classBody != null) { TypeTree identifier = tree.identifier(); if (!useThisIdentifier(classBody) && !enumConstants.contains(identifier) && isSAM(classBody)) { context.reportIssue(this, identifier, "Make this anonymous inner class a lambda" + context.getJavaVersion().java8CompatibilityMessage()); } } }
Source:
public void visitNode(Tree tree) { IfStatementTree treeIfStmt = (IfStatementTree) tree; StatementTree elseStmt = treeIfStmt.elseStatement(); IfStatementTree ifStmt = null; if (elseStmt != null && elseStmt.is(Tree.Kind.IF_STATEMENT)) { ifStmt = (IfStatementTree) elseStmt; } if (ifStmt != null && ifStmt.elseStatement() == null) { reportIssue(treeIfStmt.elseKeyword(), ifStmt.ifKeyword(), "\"if ... else if\" constructs should end with \"else\" clauses."); } }

Target:
public void visitNode(Tree tree) { IfStatementTree treeIfStmt = (IfStatementTree) tree; StatementTree elseStmt = treeIfStmt.elseStatement(); if (elseStmt != null && elseStmt.is(Tree.Kind.IF_STATEMENT)) { IfStatementTree ifStmt = (IfStatementTree) elseStmt; if (ifStmt.elseStatement() == null) { reportIssue(treeIfStmt.elseKeyword(), ifStmt.ifKeyword(), "\"if ... else if\" constructs should end with \"else\" clauses."); } } }
Source:
public List<Tree.Kind> nodesToVisit() { return Collections.singletonList((Tree.Kind.CONSTRUCTOR)); }

Target:
public List<Tree.Kind> nodesToVisit() { return Collections.singletonList(Tree.Kind.CONSTRUCTOR); }
Source:
public void visitMethodInvocation(MethodInvocationTree tree) { if (SUPER_THREAD.matches(tree) && ThreadOverridesRunCheck.hasRunnableArgument(tree.arguments())) { callSuperWithRunnable = true; } super.visitMethodInvocation(tree); }

Target:
public void visitMethodInvocation(MethodInvocationTree tree) { if (SUPER_THREAD.matches(tree) && ThreadOverridesRunCheck.hasRunnableArgument(tree.arguments())) { callSuperWithRunnable = true; // no need to visit further return; } super.visitMethodInvocation(tree); }
Source:
private ExecutorService createExecutor() { int numThreads = Runtime.getRuntime().availableProcessors() + 1; return Executors.newFixedThreadPool(numThreads, new ThreadFactoryBuilder().setNameFormat("SonarJava-parallel-analysis-%d").build()); }

Target:
private ExecutorService createExecutor() { // int numThreads = Runtime.getRuntime().availableProcessors() + 1; int numThreads = 2; return Executors.newFixedThreadPool(numThreads, new ThreadFactoryBuilder().setNameFormat("SonarJava-parallel-analysis-%d").build()); }
Source:
void fun() { Object test = new Object[]{"1"}; String[] test2 = new Object[]{"1"}; Object[] test3 = new String[]{"1"}; System.out.println(((Object[])test)[0]); // compliant : target type is array access System.out.println(((Object[])test2)[0]); // Noncompliant System.out.println(((String[])test3)[0]); // compliant }

Target:
void fun() { Object test = new Object[]{"1"}; String[] test2 = new String[]{"1"}; Object[] test3 = new String[]{"1"}; System.out.println(((Object[])test)[0]); // compliant : target type is array access System.out.println(((Object[])test2)[0]); // Noncompliant System.out.println(((String[])test3)[0]); // compliant }
Source:
void f() { if (this == null) { // Noncompliant {{Change this condition so that it does not always evaluate to "false"}} } if (super == null) { // Noncompliant {{Change this condition so that it does not always evaluate to "false"}} } }

Target:
void f() { if (this == null) { // Noncompliant {{Change this condition so that it does not always evaluate to "false"}} } super.toString(); // Compliant, as super is never null }
Source:
private void enqueueThrownExceptionalPaths(Symbol symbol) { if (symbol.isMethodSymbol()) { ProgramState ps = programState.clearStack(); ((Symbol.MethodSymbol) symbol).thrownTypes().stream() .map(constraintManager::createExceptionalSymbolicValue) .forEach(exceptionSV -> enqueueExceptionalPaths(ps, exceptionSV)); } }

Target:
private void enqueueThrownExceptionalPaths(Symbol symbol) { if (!symbol.isMethodSymbol()) { // do nothing for unknown methods return; } ProgramState ps = programState.clearStack(); ((Symbol.MethodSymbol) symbol).thrownTypes().stream() .map(constraintManager::createExceptionalSymbolicValue) .forEach(exceptionSV -> enqueueExceptionalPaths(ps, exceptionSV)); }
Source:
public void while_statement() { Lock lock = new ReentrantLock(); while (foo) { lock.tryLock(); } lock.unlock(); while (Random.nextBoolean()) { lock.tryLock(); // Noncompliant lock = new ReentrantLock(); } lock.unlock(); }

Target:
public void while_statement() { Lock lock = new ReentrantLock(); while (foo) { lock.tryLock(); } lock.unlock(); while (foo) { lock.tryLock(); // Noncompliant lock = new ReentrantLock(); } lock.unlock(); }
Source:
private static boolean isEnclosingClassFinal(ExpressionTree expressionTree) { //if it's identifier we go up the tree to get the method and check if owner of the method is final if (expressionTree.is(IDENTIFIER)) { Tree parent = expressionTree.parent(); while (!parent.is(METHOD)) { parent = parent.parent(); } return ((MethodTree) parent).symbol().owner().isFinal(); } else { //if it's member select, we check the type of the member select expression return ((MemberSelectExpressionTree) expressionTree).expression().symbolType().symbol().isFinal(); } }

Target:
private static boolean isEnclosingClassFinal(ExpressionTree expressionTree) { if (expressionTree.is(IDENTIFIER)) { Tree parent = expressionTree.parent(); while (!parent.is(METHOD)) { parent = parent.parent(); } return ((MethodTree) parent).symbol().owner().isFinal(); } return ((MemberSelectExpressionTree) expressionTree).expression().symbolType().symbol().isFinal(); }
Source:
protected static boolean isSerializableAndValueBased(Type type) { // we check first the ParametrizedTypeJavaType, in order to filter out the non-serializable // generic value-based class Optional<T> JavaType javaType = (JavaType)type; if (javaType.isParameterized()) { ParametrizedTypeJavaType parameterizedType = (ParametrizedTypeJavaType)javaType; return isSubtypeOfCollectionApi(parameterizedType) && parameterizedType.typeParameters().stream() .anyMatch(t -> isSerializableAndValueBased(parameterizedType.substitution(t))); } else { return ValueBasedUtils.isValueBased(javaType); } }

Target:
private static boolean isSerializableAndValueBased(Type type) { // we check first the ParametrizedTypeJavaType, in order to filter out the non-serializable // generic value-based class Optional<T> JavaType javaType = (JavaType) type; if (javaType.isParameterized()) { ParametrizedTypeJavaType parameterizedType = (ParametrizedTypeJavaType) javaType; return isSubtypeOfCollectionApi(parameterizedType) && parameterizedType.typeParameters().stream() .anyMatch(t -> isSerializableAndValueBased(parameterizedType.substitution(t))); } return ValueBasedUtils.isValueBased(javaType); }
Source:
public void visitBinaryExpression(BinaryExpressionTree binaryExpression) { String message = "Remove this null-check of an \"Optional\"."; if (binaryExpression.is(Tree.Kind.EQUAL_TO, Tree.Kind.NOT_EQUAL_TO)) { ExpressionTree left = binaryExpression.leftOperand(); ExpressionTree right = binaryExpression.rightOperand(); if ((isOptional(left) && isNull(right)) || (isNull(left) && isOptional(right))) { context.reportIssue(this, binaryExpression, message); } } super.visitBinaryExpression(binaryExpression); }

Target:
public void visitBinaryExpression(BinaryExpressionTree binaryExpression) { // check that an @Optional is not compared to "null" if (binaryExpression.is(Tree.Kind.EQUAL_TO, Tree.Kind.NOT_EQUAL_TO)) { ExpressionTree left = binaryExpression.leftOperand(); ExpressionTree right = binaryExpression.rightOperand(); if ((isOptional(left) && isNull(right)) || (isNull(left) && isOptional(right))) { context.reportIssue(this, binaryExpression, "Remove this null-check of an \"Optional\"."); } } super.visitBinaryExpression(binaryExpression); }
Source:
public ProgramState addConstraint(SymbolicValue symbolicValue, Constraint constraint) { PMap<SymbolicValue, Constraint> newConstraints = constraints.put(symbolicValue, constraint); if (newConstraints != constraints && !isSymbolicValueOfVolatileField(symbolicValue)) { return new ProgramState(this, newConstraints); } return this; }

Target:
public ProgramState addConstraint(SymbolicValue symbolicValue, Constraint constraint) { PMap<SymbolicValue, Constraint> newConstraints = constraints.put(symbolicValue, constraint); if (newConstraints != constraints) { return new ProgramState(this, newConstraints); } return this; }
Source:
ClassJavaType(int tag, JavaSymbol.TypeJavaSymbol symbol) { super(tag, symbol); }

Target:
protected ClassJavaType(int tag, JavaSymbol.TypeJavaSymbol symbol) { super(tag, symbol); }