auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected static String commentFormat(String comment) { if (comment == null || comment.isEmpty()) return ""; // truncate comment to 255 Bytes - a tinyblob while (comment.getBytes(ENCODING).length > 255) { comment = comment.substring(0, comment.length() - 1); } return comment; }

Target:
protected static String commentFormat(String comment) { if (comment == null || comment.length() == 0) return ""; // truncate comment to 255 Bytes - a tinyblob while (comment.getBytes(ENCODING).length > 255) { comment = comment.substring(0, comment.length() - 1); } return comment; }
Source:
public void onCatch(Throwable caught) { if (caught instanceof IOException) { // Network IO error, I presume Utils.crossFade(loadProgress, networkError); } }

Target:
public void onCatch(Throwable caught) { // Should check for the source of the error and have different things turn up // But good enough for now Utils.crossFade(loadProgress, networkError); }
Source:
public void setEnabled(boolean enabled) { //make sure we close the pane before disabling if (!enabled) slidingPane.closePane(); slidingPane.setSlidingEnabled(enabled); }

Target:
public void setEnabled(boolean enabled) { //make sure we close the pane before disabling if (!enabled) { slidingPane.closePane(); } slidingPane.setSlidingEnabled(enabled); }
Source:
private boolean shouldSkip() { // Maintain lastMatched - it should be false if we shift to a new doc. if (cache.lastDocId != context.hitContext.docId()) { cache.lastMatched = false; cache.lastDocId = context.hitContext.docId(); } Boolean skipIfLastMatched = (Boolean)getOption("skip_if_last_matched"); if (skipIfLastMatched == null ? false : skipIfLastMatched && cache.lastMatched) { return true; } return false; }

Target:
private boolean shouldSkip() { // Maintain lastMatched - it should be false if we shift to a new doc. if (cache.lastDocId != context.hitContext.docId()) { cache.lastMatched = false; cache.lastDocId = context.hitContext.docId(); } Boolean skipIfLastMatched = (Boolean)getOption("skip_if_last_matched"); return skipIfLastMatched == null ? false : skipIfLastMatched && cache.lastMatched; }
Source:
public boolean onSearchRequested() { showToolbar(); searchFragment.openSearch(); return false; }

Target:
public boolean onSearchRequested() { showToolbar(); searchFragment.openSearch(); return true; }
Source:
public void testBadNumberOfArguments() throws HiveException, IOException { ObjectInspector value1 = PrimitiveObjectInspectorFactory.javaStringObjectInspector; ObjectInspector value2 = PrimitiveObjectInspectorFactory.javaStringObjectInspector; ObjectInspector[] initArguments = new ObjectInspector[]{value1, value2}; GeocodedCountryUDF geocodedCountryUDF = new GeocodedCountryUDF(); geocodedCountryUDF.initialize(initArguments); }

Target:
public void testBadNumberOfArguments() throws HiveException { ObjectInspector value1 = PrimitiveObjectInspectorFactory.javaStringObjectInspector; ObjectInspector value2 = PrimitiveObjectInspectorFactory.javaStringObjectInspector; ObjectInspector[] initArguments = new ObjectInspector[]{value1, value2}; GeocodedCountryUDF geocodedCountryUDF = new GeocodedCountryUDF(); geocodedCountryUDF.initialize(initArguments); }
Source:
public void testWrongTypeOfArguments() throws HiveException, IOException { ObjectInspector value1 = PrimitiveObjectInspectorFactory.javaIntObjectInspector; ObjectInspector[] initArguments = new ObjectInspector[]{value1}; GeocodedCountryUDF geocodedCountryUDF = new GeocodedCountryUDF(); geocodedCountryUDF.initialize(initArguments); }

Target:
public void testWrongTypeOfArguments() throws HiveException { ObjectInspector value1 = PrimitiveObjectInspectorFactory.javaIntObjectInspector; ObjectInspector[] initArguments = new ObjectInspector[]{value1}; GeocodedCountryUDF geocodedCountryUDF = new GeocodedCountryUDF(); geocodedCountryUDF.initialize(initArguments); }
Source:
private void preRequestReadMoreItems(final LayoutInflater layoutInflater) { if (parentFragment.getPage().getPageProperties().isMainPage()) { new MainPageReadMoreTopicTask(activity) { @Override public void onFinish(PageTitle myTitle) { requestReadMoreItems(layoutInflater, myTitle); } @Override public void onCatch(Throwable caught) { // Read More titles are expendable. Log.w(TAG, "Error while getting Read More topic for main page.", caught); // but lay out the bottom content anyway: layoutContent(); } }.execute(); } else { requestReadMoreItems(layoutInflater, pageTitle); } }

Target:
private void preRequestReadMoreItems(final LayoutInflater layoutInflater) { if (parentFragment.getPage().isMainPage()) { new MainPageReadMoreTopicTask(activity) { @Override public void onFinish(PageTitle myTitle) { requestReadMoreItems(layoutInflater, myTitle); } @Override public void onCatch(Throwable caught) { // Read More titles are expendable. Log.w(TAG, "Error while getting Read More topic for main page.", caught); // but lay out the bottom content anyway: layoutContent(); } }.execute(); } else { requestReadMoreItems(layoutInflater, pageTitle); } }
Source:
public android.database.Cursor getInterestedHistoryEntry() { ContentProviderClient client = context.getContentResolver() .acquireContentProviderClient(HistoryEntry.PERSISTENCE_HELPER.getBaseContentURI()); try { return client.query( HistoryEntry.PERSISTENCE_HELPER.getBaseContentURI(), null, "source != ? AND source != ? ", new String[] {Integer.toString(HistoryEntry.SOURCE_MAIN_PAGE), Integer.toString(HistoryEntry.SOURCE_RANDOM)}, "timestamp DESC"); } catch (RemoteException e) { // This shouldn't really be happening throw new RuntimeException(e); } }

Target:
private android.database.Cursor getInterestedHistoryEntry() { ContentProviderClient client = context.getContentResolver() .acquireContentProviderClient(HistoryEntry.PERSISTENCE_HELPER.getBaseContentURI()); try { return client.query( HistoryEntry.PERSISTENCE_HELPER.getBaseContentURI(), null, "source != ? AND source != ? ", new String[] {Integer.toString(HistoryEntry.SOURCE_MAIN_PAGE), Integer.toString(HistoryEntry.SOURCE_RANDOM)}, "timestamp DESC"); } catch (RemoteException e) { // This shouldn't really be happening throw new RuntimeException(e); } }
Source:
public PageTitle titleForInternalLink(String internalLink) { // FIXME: Handle language variant links properly // Strip the /wiki/ from the href, and replace all underscores with spaces for neatness return new PageTitle(internalLink.replaceFirst("/wiki/", "").replaceAll("_", " "), this); }

Target:
public PageTitle titleForInternalLink(String internalLink) { // FIXME: Handle language variant links properly // Strip the /wiki/ from the href return new PageTitle(internalLink.replaceFirst("/wiki/", ""), this); }
Source:
public int getType() { if (code.startsWith("abusefilter-warning")) { return TYPE_WARNING; } else if (code.startsWith("abusefilter-disallowed")) { return TYPE_ERROR; } else if (info.startsWith("Hit AbuseFilter")) { // This case is here because, unfortunately, an admin can create an abuse filter which // emits an arbitrary error code over the API. // TODO: More properly handle the case where the AbuseFilter throws an arbitrary error. // Oh, and, you know, also fix the AbuseFilter API to not throw arbitrary error codes. return TYPE_ERROR; } else { throw new RuntimeException("Unknown abusefilter response!"); } }

Target:
public int getType() { if (code.startsWith("abusefilter-warning")) { return TYPE_WARNING; } else if (code.startsWith("abusefilter-disallowed")) { return TYPE_ERROR; } else if (info.startsWith("Hit AbuseFilter")) { // This case is here because, unfortunately, an admin can create an abuse filter which // emits an arbitrary error code over the API. // TODO: More properly handle the case where the AbuseFilter throws an arbitrary error. // Oh, and, you know, also fix the AbuseFilter API to not throw arbitrary error codes. return TYPE_ERROR; } else { // We have no understanding of what kind of abuse filter response we got. It's safest // to simply treat these as an error. return TYPE_ERROR; } }
Source:
protected void run(Date lastRun) { try { ShareUtils.clearFolder(getContext()); } catch (Exception e) { // There have been a few reports of errors during the clearing process, even though // we check that external storage is mounted properly. For now, we won't worry // about it, since this task will be repeated later. Log.d("SharedImageCleanupTask", "Failed to clear shared image folder.", e); } }

Target:
protected void run(Date lastRun) { ShareUtils.clearFolder(getContext()); }
Source:
private void showNetworkError() { // TODO: Check for the source of the error and have different things turn up // TODO: Change the name of this function to showPageError when the file is not under active development boolean networkPresent = NetworkUtils.isNetworkConnectionPresent(app); TextView errorMessage = (TextView) networkError.findViewById(R.id.page_error_message); if (!networkPresent) { errorMessage.setText(R.string.error_network_error); } else { errorMessage.setText(R.string.generic_page_error); } hidePageContent(); ViewAnimations.fadeIn(networkError); }

Target:
private void showNetworkError() { // TODO: Check for the source of the error and have different things turn up // TODO: Change the name of this function to showPageError when the file is not under active development TextView errorMessage = (TextView) networkError.findViewById(R.id.page_error_message); if (!NetworkUtils.isNetworkConnectionPresent(app)) { errorMessage.setText(R.string.error_network_error); } else { errorMessage.setText(R.string.generic_page_error); } hidePageContent(); ViewAnimations.fadeIn(networkError); }
Source:
protected URIExtensionIV createInlineIV(URI uri) { if (namespaceIV == null) { // Can't do anything without a namespace. return null; } for (String prefix : normalizedPrefixes) { if (uri.stringValue().startsWith(prefix)) { AbstractLiteralIV localNameIv = next.createInlineIV(uri.stringValue().substring( CommonValues.VIAF_HTTP.length())); if (localNameIv == null) { return null; } return new URIExtensionIV(localNameIv, namespaceIV); } } return next.createInlineIV(uri); }

Target:
protected URIExtensionIV createInlineIV(URI uri) { if (namespaceIV == null) { // Can't do anything without a namespace. return null; } for (String prefix : normalizedPrefixes) { if (uri.stringValue().startsWith(prefix)) { AbstractLiteralIV localNameIv = next.createInlineIV(uri.stringValue().substring(prefix.length())); if (localNameIv == null) { return null; } return new URIExtensionIV(localNameIv, namespaceIV); } } return next.createInlineIV(uri); }
Source:
public void writeToParcel(Parcel parcel, int flags) { parcel.writeString(namespace); parcel.writeString(text); parcel.writeString(fragment); parcel.writeParcelable(site, flags); parcel.writeString(thumbUrl); parcel.writeString(description); }

Target:
public void writeToParcel(Parcel parcel, int flags) { parcel.writeString(namespace); parcel.writeString(text); parcel.writeString(fragment); parcel.writeParcelable(properties, flags); parcel.writeParcelable(site, flags); parcel.writeString(thumbUrl); parcel.writeString(description); }
Source:
public boolean isCloseEnough() { return true; }

Target:
public boolean isCloseEnough() { return false; }
Source:
public void onActionModeShown(ActionMode mode) { // make sure we have a page loaded, since shareHandler makes references to it. if (model.getPage() == null) { return; } shareHandler.onTextSelected(mode); }

Target:
public void onActionModeShown(ActionMode mode) { // make sure we have a page loaded, since shareHandler makes references to it. if (model.getPage() != null) { shareHandler.onTextSelected(mode); } }
Source:
private void openInNewTab(PageTitle title, HistoryEntry entry) { // create a new tab Tab tab = new Tab(); // put this tab behind the current tab if (tabList.size() > 0) { tabList.add(tabList.size() - 1, tab); } else { tabList.add(tab); } // add the requested page to its backstack tab.getBackStack().add(new PageBackStackItem(title, entry)); // and... that should be it. tabsProvider.showAndHideTabs(); }

Target:
private void openInNewTab(PageTitle title, HistoryEntry entry) { // create a new tab Tab tab = new Tab(); // put this tab behind the current tab tabList.add(Math.max(0, tabList.size() - 1), tab); // add the requested page to its backstack tab.getBackStack().add(new PageBackStackItem(title, entry)); // and... that should be it. tabsProvider.showAndHideTabs(); }
Source:
public void closeSearch() { isSearchActive = false; // invalidate our activity's ActionBar, so that the original action items are restored. getActivity().supportInvalidateOptionsMenu(); getActivity().supportInvalidateOptionsMenu(); ((PageActivity)getActivity()).getSearchBarHideHandler().setForceNoFade(false); setSearchViewEnabled(false); ((PageActivity) getActivity()).getDrawerToggle().setDrawerIndicatorEnabled(true); // hide ourselves searchContainerView.setVisibility(View.GONE); hideSoftKeyboard(getActivity()); addRecentSearch(lastSearchedText); }

Target:
public void closeSearch() { isSearchActive = false; // invalidate our activity's ActionBar, so that the original action items are restored. getActivity().supportInvalidateOptionsMenu(); ((PageActivity)getActivity()).getSearchBarHideHandler().setForceNoFade(false); setSearchViewEnabled(false); ((PageActivity) getActivity()).getDrawerToggle().setDrawerIndicatorEnabled(true); // hide ourselves searchContainerView.setVisibility(View.GONE); hideSoftKeyboard(getActivity()); addRecentSearch(lastSearchedText); }
Source:
public Api getSiteApi() { return getAPIForSite(new Site("authmanager.wmflabs.org")); //return getAPIForSite(getSite()); }

Target:
public Api getSiteApi() { return new Api("authmanager.wmflabs.org", false); //return getAPIForSite(getSite()); }
Source:
public PageTitle titleForInternalLink(String internalLink) { // FIXME: Handle language variant links properly // Strip the /wiki/ (mobileview) or ./ (parsoid) from the href return new PageTitle(RbSwitch.INSTANCE.isRestBaseEnabled() ? internalLink.replaceFirst("./", "") : internalLink.replaceFirst("/wiki/", ""), this); }

Target:
public PageTitle titleForInternalLink(String internalLink) { // FIXME: Handle language variant links properly // Strip the /wiki/ (mobileview) or ./ (parsoid) from the href return new PageTitle(internalLink.replaceFirst("./", "").replaceFirst("/wiki/", ""), this); }
Source:
public void onPageLoadComplete() { showToCButton(); refreshView.setEnabled(true); editHandler.setPage(model.getPage()); initPageScrollFunnel(); // TODO: update this title in the db to be queued for saving by the service. checkAndShowSelectTextOnboarding(); updateNavDrawerSelection(); if (getMainActivity().pageLoadCallbacks() != null) { getMainActivity().pageLoadCallbacks().onLoadComplete(); } }

Target:
public void onPageLoadComplete() { showToCButton(); refreshView.setEnabled(true); editHandler.setPage(model.getPage()); initPageScrollFunnel(); // TODO: update this title in the db to be queued for saving by the service. checkAndShowSelectTextOnboarding(); updateNavDrawerSelection(); if (getMainActivity() != null && getMainActivity().pageLoadCallbacks() != null) { getMainActivity().pageLoadCallbacks().onLoadComplete(); } }
Source:
public void onPageLoadComplete() { showToCButton(); refreshView.setEnabled(true); editHandler.setPage(model.getPage()); initPageScrollFunnel(); // TODO: update this title in the db to be queued for saving by the service. checkAndShowSelectTextOnboarding(); updateNavDrawerSelection(); if (getActivity() != null && getPageLoadCallbacks() != null) { getPageLoadCallbacks().onLoadComplete(); } }

Target:
public void onPageLoadComplete() { showToCButton(); refreshView.setEnabled(true); editHandler.setPage(model.getPage()); initPageScrollFunnel(); // TODO: update this title in the db to be queued for saving by the service. checkAndShowSelectTextOnboarding(); updateNavDrawerSelection(); if (getPageLoadCallbacks() != null) { getPageLoadCallbacks().onLoadComplete(); } }
Source:
private static OutputWrapper connectMySql(String param) throws IOException { try { Class.forName("com.mysql.jdbc.Driver").newInstance(); Connection conn = DriverManager.getConnection("jdbc:mysql:" + param); return new OutputWrapper(conn); } catch (Exception e) { //e.printStackTrace(); throw (IOException)new IOException(e.getMessage()).initCause(e); } }

Target:
private static OutputWrapper connectMySql(String param) throws IOException { try { Class.forName("com.mysql.jdbc.Driver").newInstance(); Connection conn = DriverManager.getConnection("jdbc:mysql:" + param); return new OutputWrapper(conn); } catch (Exception e) { throw new IOException(e); } }
Source:
private void assertCallbackSuccess(@NonNull Call<DescriptionEdit> call, @NonNull Callback cb) { verify(cb).success(eq(call)); //noinspection unchecked verify(cb, never()).failure(eq(call), any(Throwable.class)); }

Target:
private void assertCallbackSuccess(@NonNull Call<DescriptionEdit> call, @NonNull Callback cb) { verify(cb).success(eq(call)); //noinspection unchecked verify(cb, never()).failure(any(Call.class), any(Throwable.class)); }
Source:
@Override protected void buildScript(int age) { if (age == 0) { addPendingClient(new SearchClient()); addPendingClient(new AnnouncementClient()); } addPendingClient(new AggregatedFeedContentClient()); addPendingClient(new ContinueReadingClient()); if (age == 0) { addPendingClient(new MainPageClient()); } addPendingClient(new BecauseYouReadClient()); if (age == 0) { addPendingClient(new RandomClient()); } // OfflineClient must always come last, since we rely on the last request in the series // being a network request (and not a disk I/O request) to determine online/offline state // for purposes of updating the feed UI. addPendingClient(new OfflineClient()); }

Target:
protected void buildScript(int age) { if (age == 0) { addPendingClient(new SearchClient()); addPendingClient(new AnnouncementClient()); } addPendingClient(new AggregatedFeedContentClient()); addPendingClient(new ContinueReadingClient()); if (age == 0) { addPendingClient(new MainPageClient()); } addPendingClient(new BecauseYouReadClient()); if (age == 0) { addPendingClient(new RandomClient()); } }
Source:
@Override public void error(@NonNull Throwable caught) { if (caught instanceof OfflineClient.OfflineException) { appendCard(new OfflineCard()); } //noinspection ConstantConditions requestNextCard(wiki); }

Target:
@Override public void error(@NonNull Throwable caught) { //noinspection ConstantConditions requestNextCard(wiki); }
Source:
public void setUpTopicPartitions() { topicPartitions = topics.stream() // Get partitions .flatMap((String topic) -> consumer.partitionsFor(topic).stream()) // Create TopicPartition objects .map(p -> new TopicPartition(p.topic(), p.partition())) .collect(ImmutableList.toImmutableList()); }

Target:
private ImmutableList<TopicPartition> setUpTopicPartitions() { return topics.stream() // Get partitions .flatMap((String topic) -> consumer.partitionsFor(topic).stream()) // Create TopicPartition objects .map(p -> new TopicPartition(p.topic(), p.partition())) .collect(ImmutableList.toImmutableList()); }
Source:
public void contextInitialized(final ServletContextEvent sce) { // configuring metrics registry before calling super(), in case we have other dependencies using dropwizard // metrics (this would require some additional magic to configure those as well, but the order still make // sense configure(METRICS_REGISTRY); super.contextInitialized(sce); initializeServices(); }

Target:
public void contextInitialized(final ServletContextEvent sce) { super.contextInitialized(sce); initializeServices(); }
Source:
public final boolean incrementToken() throws IOException { if (input.incrementToken()) { String converted = STEMMER.stemWord(termAtt.toString()); if (converted != null) // if we can't stem it, return unchanged termAtt.setEmpty().append(converted); return true; } else { return false; } }

Target:
public final boolean incrementToken() throws IOException { if (input.incrementToken()) { String converted = STEMMER.stemWord(termAtt.toString()); if (converted != null) { // if we can't stem it, return unchanged termAtt.setEmpty().append(converted); } return true; } else { return false; } }
Source:
static Iterator<SerializableFST> transform(Iterator<String> iterator) throws IOException { BytesRefSorter sorter = new InMemorySorter(Comparator.naturalOrder()); while (iterator.hasNext()) { sorter.add(new BytesRef(iterator.next())); } FST<Object> automaton = buildAutomaton(sorter); return automaton == null ? Iterators.emptyIterator() : Collections.singletonList(new SerializableFST(automaton)).iterator(); }

Target:
public static Iterator<SerializableFST> transform(Iterator<String> iterator) throws IOException { // sort/dedupe based on the utf8 byte representation of the dictionary BytesRefSorter sorter = new InMemorySorter(Comparator.naturalOrder()); while (iterator.hasNext()) { sorter.add(new BytesRef(iterator.next())); } FST<Object> automaton = buildAutomaton(sorter); return automaton == null ? Iterators.emptyIterator() : Collections.singletonList(new SerializableFST(automaton)).iterator(); }
Source:
public static String randomAsciiOfLength(int count) { return RandomStringUtils.randomAlphabetic(count); }

Target:
public String randomAsciiOfLength(int count) { return RandomStringUtils.randomAlphabetic(count); }
Source:
public JsonNode getEventSchema(String eventString) { // Assume that all eventStrings are in JSON, not in YAML, due to // a slight difference in allowed unicode characters in YAML. // See: https://phabricator.wikimedia.org/T227484 JsonNode event = this.schemaLoader.parse(eventString, false); return this.getEventSchema(event); }

Target:
public JsonNode getEventSchema(String eventString) { JsonNode event = this.schemaLoader.parse(eventString); return this.getEventSchema(event); }
Source:
MergingUpdater(AbstractTripleStore database) { this.database = database; String property = System.getProperty("outputDumps"); outputDumps = Boolean.TRUE.toString().equals(property); id = UUID.randomUUID().toString().replaceAll("-", ""); }

Target:
MergingUpdater(AbstractTripleStore database) { this(database, /* outputDumps */ false); }
Source:
public OverpassDataFetcher() { url = "http://www.overpass-api.de/api/interpreter?data="; }

Target:
public OverpassDataFetcher() { this("http://www.overpass-api.de/api/interpreter?data="); }
Source:
public void loadStyle(int styleId) { String style = StyleLoader.ReadStringFromResource(context, styleId); StyleParser zoomParser = new ZoomStyleParser(); styles = zoomParser.getStyleSet(style); }

Target:
public void loadStyle(int styleId) { String style = StyleLoader.ReadStringFromResource(context, styleId); styles = zoomParser.getStyleSet(style); }
Source:
public void setPosition(float x, float y) { if (mapSize.x < x && mapSize.y < y) { offset.x = x; offset.y = y; } }

Target:
public void setPosition(float x, float y) { if (x < mapSize.x && y < mapSize.y) { offset.x = x; offset.y = y; } }
Source:
public static boolean isAlreadyPresent(ArrayList<Order> ordersPlaced, Order newOrder) { for (Order orderPlaced : ordersPlaced) { if (((orderPlaced instanceof BuyOrder) && (newOrder instanceof BuyOrder)) || ((orderPlaced instanceof SellOrder) && (newOrder instanceof SellOrder))) { if (orderPlaced.getStockSymbol().equals( newOrder.getStockSymbol())) { return true; } } } return false; }

Target:
public static boolean isAlreadyPresent(ArrayList<Order> ordersPlaced, Order newOrder) { for (Order orderPlaced : ordersPlaced) { if ((orderPlaced instanceof BuyOrder) && (newOrder instanceof BuyOrder)){ if ((orderPlaced instanceof SellOrder) && (newOrder instanceof SellOrder)){ if (orderPlaced.getStockSymbol().equals( newOrder.getStockSymbol())) { return true; } } } } return false; }
Source:
public boolean equals(Object obj) { if (null == obj || !(obj instanceof TestableZoomObject2)) return false; TestableZoomObject2 o = (TestableZoomObject2) obj; return byteField.equals(o.byteField) && byteSet.equals(o.byteSet); }

Target:
public boolean equals(Object obj) { if (null == obj || !(obj instanceof TestableZoomObject2)) return false; TestableZoomObject2 o = (TestableZoomObject2) obj; return null != byteField && null != byteSet && byteField.equals(o.byteField) && byteSet.equals(o.byteSet); }
Source:
public void onClick(View v){ if(butPlus == v){ }else if(butMinus == v){ }else if(butUp == v){ }else if(butDown == v){ } }

Target:
public void onClick(View v){ int id = v.getId(); if(id == R.id.butPlus){ }else if(id == R.id.butMinus){ }else if(id == R.id.butUp){ }else if(id == R.id.butDown){ } }
Source:
public Router get(@PathParam("id") UUID id) throws StateAccessException, SerializationException { if (!authorizer.authorize(context, AuthAction.READ, id)) { throw new ForbiddenHttpException( "Not authorized to view this router."); } org.midonet.cluster.data.Router routerData = dataClient.routersGet(id); if (routerData == null) { throw new NotFoundHttpException( "The requested resource was not found."); } // Convert to the REST API DTO Router router = RouterDataConverter.fromData(routerData); router.setBaseUri(getBaseUri()); return router; }

Target:
public Router get(@PathParam("id") UUID id) throws StateAccessException, SerializationException { if (!authorizer.authorize(context, AuthAction.READ, id)) { throw new ForbiddenHttpException( "Not authorized to view this router."); } org.midonet.cluster.data.Router routerData = dataClient.routersGet(id); if (routerData == null) { throw new NotFoundHttpException( "The requested resource was not found."); } // Convert to the REST API DTO return RouterDataConverter.fromData(routerData, getBaseUri()); }
Source:
public static boolean isCompatApiEnabled() { return Boolean.parseBoolean(System.getenv("midonet.newStack")); }

Target:
public static boolean isCompatApiEnabled() { return System.getProperty("midonet.newStack") != null; }
Source:
public static void scanNestedAttribute(ByteBuffer buf, AttributeHandler handler) { int start = buf.position(); int end = buf.limit(); while (buf.remaining() > ATTR_HEADER_LEN) { short attrLen = buf.getShort(); // This is always 1 for the nested len. short attrId = nested(buf.getShort()); buf.limit(end); handler.use(buf, attrId); buf.position(start); } }

Target:
public static void scanNestedAttribute(ByteBuffer buf, AttributeHandler handler) { int start = buf.position(); if (buf.remaining() > ATTR_HEADER_LEN) { short attrLen = buf.getShort(); // This is always 1 for the nested len. short attrId = nested(buf.getShort()); handler.use(buf, attrId); buf.position(start); } }
Source:
public static String convertFromIpsecString(String str) { if (str == null) return null; try { return str.replace('-', '_').toUpperCase(); } catch (IllegalArgumentException ex) { // TODO: Log exception. return null; } }

Target:
public static String convertFromIpsecString(String str) { if (str == null) { return null; } return str.replace('-', '_').toUpperCase(); }
Source:
public void dispose() { //Remove all messages from the queue this.removeCallbacksAndMessages(null); this.phone = null; }

Target:
public void dispose() { }
Source:
public void dispose() { //Unregister for all events phone.mCM.unregisterForRUIMReady(this); phone.mCM.unregisterForOffOrNotAvailable( this); phone.mCM.unSetOnIccRefresh(this); //Remove all messages from the queue this.removeCallbacksAndMessages(null); this.recordsLoadedRegistrants = null; this.phone = null; }

Target:
public void dispose() { //Unregister for all events phone.mCM.unregisterForRUIMReady(this); phone.mCM.unregisterForOffOrNotAvailable( this); phone.mCM.unSetOnIccRefresh(this); }
Source:
public void dispose() { //Remove all messages from the queue this.removeCallbacksAndMessages(null); this.phone = null; }

Target:
public void dispose() { super.dispose(); }
Source:
public void dispose() { //Unregister for all events phone.mCM.unregisterForSIMLockedOrAbsent(this); phone.mCM.unregisterForOffOrNotAvailable(this); phone.mCM.unregisterForSIMReady(this); //Remove all messages from the queue this.removeCallbacksAndMessages(null); this.absentRegistrants = null; this.pinLockedRegistrants = null; this.networkLockedRegistrants = null; this.status = null; this.phone = null; }

Target:
public void dispose() { //Unregister for all events phone.mCM.unregisterForSIMLockedOrAbsent(this); phone.mCM.unregisterForOffOrNotAvailable(this); phone.mCM.unregisterForSIMReady(this); }
Source:
public void dispose() { //Remove all messages from the queue mHandler.removeCallbacksAndMessages(null); mHandler = null; super.dispose(); }

Target:
public void dispose() { super.dispose(); }
Source:
public synchronized void removeMiniThumbDataFile() { String path = randomAccessFilePath(MINI_THUMB_DATA_FILE_VERSION); File file = new File(path); if (file.exists()) { try { file.delete(); } catch (SecurityException ex) { // ignore } } }

Target:
public synchronized void removeMiniThumbDataFile() { String path = randomAccessFilePath(MINI_THUMB_DATA_FILE_VERSION); File file = new File(path); try { file.delete(); } catch (SecurityException ex) { // ignore } }
Source:
private void onDiscoverServicesResult(String deviceObjectPath, boolean result) { String address = mBluetoothService.getAddressFromObjectPath(deviceObjectPath); // We don't parse the xml here, instead just query Bluez for the properties. if (result) { mBluetoothService.updateRemoteDevicePropertiesCache(address); } if (address != null) { mBluetoothService.sendUuidIntent(address); } mBluetoothService.makeServiceChannelCallbacks(address); }

Target:
private void onDiscoverServicesResult(String deviceObjectPath, boolean result) { String address = mBluetoothService.getAddressFromObjectPath(deviceObjectPath); if (address == null) return; // We don't parse the xml here, instead just query Bluez for the properties. if (result) { mBluetoothService.updateRemoteDevicePropertiesCache(address); } mBluetoothService.sendUuidIntent(address); mBluetoothService.makeServiceChannelCallbacks(address); }
Source:
public void testVFE3() { try { T_iget_13 t = new T_iget_13(); t.run(); fail("expected a NoSuchFieldError exception"); } catch (NoSuchFieldError e) { // expected } }

Target:
public void testVFE3() { try { new T_iget_13().run(); fail("expected a NoSuchFieldError exception"); } catch (NoSuchFieldError e) { // expected } }
Source:
public void onReceive(Context context, Intent intent) { mContext = context; if (MESSAGE_STATUS_RECEIVED_ACTION.equals(intent.getAction())) { Uri messageUri = intent.getData(); byte[] pdu = (byte[]) intent.getExtra("pdu"); SmsMessage message = updateMessageStatus(context, messageUri, pdu); // Called on the UI thread so don't block. if (message.getStatus() < Sms.STATUS_PENDING) MessagingNotification.nonBlockingUpdateNewMessageIndicator(context, true, message.isStatusReportMessage); } }

Target:
public void onReceive(Context context, Intent intent) { mContext = context; if (MESSAGE_STATUS_RECEIVED_ACTION.equals(intent.getAction())) { Uri messageUri = intent.getData(); byte[] pdu = (byte[]) intent.getExtra("pdu"); SmsMessage message = updateMessageStatus(context, messageUri, pdu); // Called on the UI thread so don't block. if (message.getStatus() < Sms.STATUS_PENDING) MessagingNotification.nonBlockingUpdateNewMessageIndicator(context, true, message.isStatusReportMessage()); } }
Source:
private boolean isGfxProfilingEnabled() { IDevice device = getCurrentDevice(); if (device == null) { return false; } String prop; try { prop = device.getPropertySync(PROP_GFX_PROFILING); return "true".equalsIgnoreCase(prop); } catch (Exception e) { return false; } }

Target:
private boolean isGfxProfilingEnabled() { IDevice device = getCurrentDevice(); if (device == null) { return false; } String prop; try { prop = device.getPropertySync(PROP_GFX_PROFILING); return Boolean.valueOf(prop); } catch (Exception e) { return false; } }
Source:
onRadioAvailable() { // In case screen state was lost (due to process crash), // this ensures that the RIL knows the correct screen state. PowerManager pm = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE); boolean isScreenOn = pm.isScreenOn(); sendScreenState(isScreenOn); }

Target:
onRadioAvailable() { // In case screen state was lost (due to process crash), // this ensures that the RIL knows the correct screen state. PowerManager pm = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE); sendScreenState(pm.isScreenOn()); }
Source:
public int onStartCommand(Intent intent, int flags, int startId) { // Temporarily removed for this duplicate message track down. resultCode = intent != null ? intent.getIntExtra("result", 0) : 0; if (resultCode != 0) { Log.v(TAG, "onStart: #" + startId + " resultCode: " + resultCode + " = " + translateResultCode(resultCode)); } Message msg = mServiceHandler.obtainMessage(); msg.arg1 = startId; msg.obj = intent; mServiceHandler.sendMessage(msg); return Service.START_NOT_STICKY; }

Target:
public int onStartCommand(Intent intent, int flags, int startId) { // Temporarily removed for this duplicate message track down. int resultCode = intent != null ? intent.getIntExtra("result", 0) : 0; if (resultCode != 0) { Log.v(TAG, "onStart: #" + startId + " resultCode: " + resultCode + " = " + translateResultCode(resultCode)); } Message msg = mServiceHandler.obtainMessage(); msg.arg1 = startId; msg.obj = intent; mServiceHandler.sendMessage(msg); return Service.START_NOT_STICKY; }
Source:
public void testAnnotation() throws Exception { Class clazz = Class.forName("com.google.annotationresolution.test." + "Annotated"); clazz.getAnnotations(); clazz = Class.forName("com.google.annotationresolution.test." + "Annotated2"); clazz.getAnnotations(); clazz = Class.forName("com.google.annotationresolution.test." + "Annotated3"); clazz.getAnnotations(); }

Target:
public void testAnnotation() throws Exception { Class<?> clazz = Class.forName("com.google.annotationresolution.test." + "Annotated"); clazz.getAnnotations(); clazz = Class.forName("com.google.annotationresolution.test." + "Annotated2"); clazz.getAnnotations(); clazz = Class.forName("com.google.annotationresolution.test." + "Annotated3"); clazz.getAnnotations(); }
Source:
private void updateGradleSyncState() { if (!myUsingCachedProjectData) { GradleProjectSyncData.save(myProject); GradleSyncState.getInstance(myProject).syncEnded(); } else { long lastSyncTimestamp = myLastSyncTimestamp; if (lastSyncTimestamp < 0) { lastSyncTimestamp = System.currentTimeMillis(); } GradleSyncState.getInstance(myProject).syncSkipped(lastSyncTimestamp); } // set default value back. myUsingCachedProjectData = DEFAULT_USING_CACHED_PROJECT_DATA; myLastSyncTimestamp = DEFAULT_LAST_SYNC_TIMESTAMP; }

Target:
private void updateGradleSyncState() { if (!myUsingCachedProjectData) { GradleProjectSyncData.save(myProject); GradleSyncState.getInstance(myProject).syncEnded(); } else { long lastSyncTimestamp = myLastSyncTimestamp; if (lastSyncTimestamp == DEFAULT_LAST_SYNC_TIMESTAMP) { lastSyncTimestamp = System.currentTimeMillis(); } GradleSyncState.getInstance(myProject).syncSkipped(lastSyncTimestamp); } // set default value back. myUsingCachedProjectData = DEFAULT_USING_CACHED_PROJECT_DATA; myLastSyncTimestamp = DEFAULT_LAST_SYNC_TIMESTAMP; }
Source:
public Set<String> getApplicableFilters() { // use a LinkedHashSet so iteration order follows insertion order. LinkedHashSet<String> filters = new LinkedHashSet<String>(); // if splitting enabled, then add an entry with no filter for universal // add it FIRST, since code assume that the first variant output will be the universal one. if (isEnable()) { filters.add(NO_FILTER); filters.addAll(super.getApplicableFilters()); } return filters; }

Target:
public Set<String> getApplicableFilters() { // use a LinkedHashSet so iteration order follows insertion order. LinkedHashSet<String> filters = new LinkedHashSet<String>(); // if splitting enabled, then add an entry with no filter for universal // add it FIRST, since code assume that the first variant output will be the universal one. if (isEnable()) { filters.add(NO_FILTER); } filters.addAll(super.getApplicableFilters()); return filters; }
Source:
public void setBounds(int x, int y, int width, int height) { Dimension previousSize = getSize(); super.setBounds(x, y, width, height); // Update the size of the layout renderer. This is done here instead of a component listener because // this runs before the paintComponent saving an extra paint cycle. Dimension currentSize = getSize(); synchronized (myGraphicsLayoutRendererLock) { if (myGraphicsLayoutRenderer != null && !currentSize.equals(previousSize)) { // Because we use GraphicsLayoutRender in vertical scroll mode, the height passed it's only a minimum. If the actual rendering results // in a bigger size, the GraphicsLayoutRenderer.getPreferredSize() call will return the correct size. myGraphicsLayoutRenderer.setSize(width, (myCurrentWidth < width) ? 1 : height); myCurrentWidth = width; } } }

Target:
public void setBounds(int x, int y, int width, int height) { Dimension previousSize = getSize(); super.setBounds(x, y, width, height); // Update the size of the layout renderer. This is done here instead of a component listener because // this runs before the paintComponent saving an extra paint cycle. Dimension currentSize = getSize(); synchronized (myGraphicsLayoutRendererLock) { if (myGraphicsLayoutRenderer != null && !currentSize.equals(previousSize)) { // Because we use GraphicsLayoutRender in vertical scroll mode, the height passed it's only a minimum. If the actual rendering results // in a bigger size, the GraphicsLayoutRenderer.getPreferredSize() call will return the correct size. myGraphicsLayoutRenderer.setSize(width, 1); } } }
Source:
public List<String> getApplicableMethodNames() { List<String> values = new ArrayList<String>(2); // Detect calls to potentially insecure SSLCertificateSocketFactory methods values.add("createSocket"); //$NON-NLS-1$ values.add("getInsecure"); //$NON-NLS-1$ return values; }

Target:
public List<String> getApplicableMethodNames() { // Detect calls to potentially insecure SSLCertificateSocketFactory methods return Arrays.asList("createSocket", "getInsecure"); }
Source:
public JMultiCastOperation(@Nonnull SourceInfo info, @Nonnull JExpression expr, @Nonnull JType... castTypes) { super(info, expr); this.castTypes = Arrays.asList(castTypes); assert this.castTypes.size() >= 1; }

Target:
public JMultiCastOperation(@Nonnull SourceInfo info, @Nonnull JExpression expr, @Nonnull JType... castTypes) { super(info, expr); this.castTypes = Arrays.asList(castTypes); assert !this.castTypes.isEmpty(); }
Source:
public Collection<JType> getTypes() { return castTypes; }

Target:
public List<JType> getTypes() { return castTypes; }
Source:
public void test_SerializationBug_26387905() throws Exception { Locale l = Locale.US; ObjectInputStream oinput = null; try { oinput = new ObjectInputStream(getClass().getResource("/serialization/org/apache/harmony/tests/java/util/Locale_Bug_26387905.ser") .openStream()); l = (Locale) oinput.readObject(); } finally { try { if (null != oinput) { oinput.close(); } } catch (Exception e) { // ignore } } }

Target:
public void test_SerializationBug_26387905() throws Exception { try (ObjectInputStream oinput = new ObjectInputStream(getClass() .getResource("/serialization/org/apache/harmony/tests/java/util/Locale_Bug_26387905.ser") .openStream())) { Locale l = (Locale) oinput.readObject(); } }
Source:
public void snapChildInstantly(final View view) { final View targetView = mCallback.getChildContentView(view); final boolean canAnimViewBeDismissed = mCallback.canChildBeDismissed(targetView); setTranslation(targetView, 0); updateSwipeProgressFromOffset(targetView, canAnimViewBeDismissed); }

Target:
private void snapChildInstantly(final View view) { final View targetView = mCallback.getChildContentView(view); final boolean canAnimViewBeDismissed = mCallback.canChildBeDismissed(targetView); setTranslation(targetView, 0); updateSwipeProgressFromOffset(targetView, canAnimViewBeDismissed); }
Source:
public void testRemoveIfUnsupportedOperation() { Collection<Integer> c = Arrays.asList(1, 2, 3, 4); try { c.removeIf(truth); fail(); } catch (UnsupportedOperationException expected) { } try { c.removeIf(falsity); } catch (Exception e) { fail(); } }

Target:
public void testRemoveIfUnsupportedOperation() { Collection<Integer> c = Arrays.asList(1, 2, 3, 4); try { c.removeIf(truth); fail(); } catch (UnsupportedOperationException expected) { } c.removeIf(falsity); // Should not throw UnsupportedOperationException. }
Source:
public void dispose() { mDestroyed.set(true); // It is possible that there is another thread waiting for the response // to requestIccSimAuthentication() in getIccSimChallengeResponse(). // A pseudo error response is made here to avoid the deadlock. auth_rsp = new IccIoResult(0x6F, 0, (byte[]) null); synchronized (mLock) { mLock.notifyAll(); } mParentApp = null; mFh = null; mCi = null; mContext = null; }

Target:
public void dispose() { mDestroyed.set(true); // It is possible that there is another thread waiting for the response // to requestIccSimAuthentication() in getIccSimChallengeResponse(). auth_rsp = null; synchronized (mLock) { mLock.notifyAll(); } mParentApp = null; mFh = null; mCi = null; mContext = null; }
Source:
private void markLoaded(@Nonnull Scope range, @Nonnull JDefinedClassOrInterface loaded) { loadStatus |= range.getMask(); if (loadStatus == Scope.ALL) { // Open a synchronize block just to prevent reordering synchronized (this) { loaded.removeLoader(); } } }

Target:
private void markLoaded(@Nonnull Scope range, @Nonnull JDefinedClassOrInterface loaded) { loadStatus |= range.getMask(); if (loadStatus == Scope.ALL) { loaded.removeLoader(); } }
Source:
public void testSMSSendingExploit() throws Exception { int inboxSizeBeforeExploit = getSMSInboxSize(); TelephonyManager telephonyManager = (TelephonyManager) getContext().getSystemService(Context.TELEPHONY_SERVICE); if(!telephonyManager.isSmsCapable()) { return; } SmsManager manager = SmsManager.getDefault(); manager.sendTextMessage("25578", null, "STOP", null, null); SystemClock.sleep(250); int inboxSizeAfterExploit = getSMSInboxSize(); assertTrue("Device is vulnerable to bug #22314646!! For more information " + "please refer - https://android.googlesource.com/platform/frameworks/" + "opt/telephony/+/ce058be%5E!/", inboxSizeBeforeExploit == inboxSizeAfterExploit); }

Target:
public void testSMSSendingExploit() throws Exception { TelephonyManager telephonyManager = (TelephonyManager) getContext().getSystemService(Context.TELEPHONY_SERVICE); if(!telephonyManager.isSmsCapable()) { return; } int inboxSizeBeforeExploit = getSMSInboxSize(); SmsManager manager = SmsManager.getDefault(); manager.sendTextMessage("25578", null, "STOP", null, null); SystemClock.sleep(250); int inboxSizeAfterExploit = getSMSInboxSize(); assertTrue("Device is vulnerable to bug #22314646!! For more information " + "please refer - https://android.googlesource.com/platform/frameworks/" + "opt/telephony/+/ce058be%5E!/", inboxSizeBeforeExploit == inboxSizeAfterExploit); }
Source:
private void setUsbConfig(String config) { if (DEBUG) Slog.d(TAG, "setUsbConfig(" + config + ")"); // set the new configuration // we always set it due to b/23631400, where adbd was getting killed // and not restarted due to property timeouts on some devices SystemProperties.set(USB_CONFIG_PROPERTY, config); return; }

Target:
private void setUsbConfig(String config) { if (DEBUG) Slog.d(TAG, "setUsbConfig(" + config + ")"); // set the new configuration // we always set it due to b/23631400, where adbd was getting killed // and not restarted due to property timeouts on some devices SystemProperties.set(USB_CONFIG_PROPERTY, config); }
Source:
public void enter() { super.enter(); if (!mBluetoothRouteManager.isInbandRingingEnabled()) { setSpeakerphoneOn(false); } CallAudioState newState = new CallAudioState(mIsMuted, ROUTE_BLUETOOTH, mAvailableRoutes); setSystemAudioState(newState); updateInternalCallAudioState(); }

Target:
public void enter() { super.enter(); setSpeakerphoneOn(false); // Do not enable SCO audio here, since RING is being sent to the headset. CallAudioState newState = new CallAudioState(mIsMuted, ROUTE_BLUETOOTH, mAvailableRoutes); setSystemAudioState(newState); updateInternalCallAudioState(); }
Source:
public void endVisit(UnaryExpression x, BlockScope b) { int operator = ((x.bits & ASTNode.OperatorMASK) >> ASTNode.OperatorSHIFT); // We don't take the constant result from ECJ if it involves a unary + and a non-literal. if (operator == OperatorIds.PLUS && !(x.expression instanceof Literal)) { foundUnaryPos = true; // We have an (+ (expression)) Constant outer = x.constant; Constant inner = x.expression.constant; // Since the + operator is no-op, the inner and the outer constant should be exactly the // same. If not, the current version of ECJ has the mentioned bug. boolean hasEcjUnaryPosBug = !outer.equals(inner); // We are going to assume there is a bug in ECJ and work around it. If this fails, // we know that the bug has been fixed. assert hasEcjUnaryPosBug; } }

Target:
public void endVisit(UnaryExpression x, BlockScope b) { int operator = ((x.bits & ASTNode.OperatorMASK) >> ASTNode.OperatorSHIFT); // We don't take the constant result from ECJ if it involves a unary + and a non-literal. if (operator == OperatorIds.PLUS && !(x.expression instanceof Literal)) { hasEcjUnaryPosBug = true; // We have an (+ (expression)) Constant outer = x.constant; Constant inner = x.expression.constant; // Since the + operator is no-op, the inner and the outer constant should be exactly the // same. If not, the current version of ECJ has the mentioned bug. boolean hasEcjUnaryPosBug = !outer.equals(inner); // We are going to assume there is a bug in ECJ and work around it. If this fails, // we know that the bug has been fixed. assert hasEcjUnaryPosBug; } }
Source:
public void setUp() throws Exception { super.setUp(); fakeFtpServer = new FakeFtpServer(); fakeFtpServer.setServerControlPort(0 /* allocate port number automatically */); fakeFtpServer.addUserAccount(new UserAccount(USER, PASSWORD, USER_HOME_DIR)); fileSystem = new UnixFakeFileSystem(); fakeFtpServer.setFileSystem(fileSystem); fileSystem.add(new DirectoryEntry(USER_HOME_DIR)); fakeFtpServer.start(); fileContents = "abcdef 1234567890".getBytes(UTF_8); }

Target:
public void setUp() throws Exception { super.setUp(); fakeFtpServer = new FakeFtpServer(); fakeFtpServer.setServerControlPort(0 /* allocate port number automatically */); fakeFtpServer.addUserAccount(new UserAccount(USER, PASSWORD, USER_HOME_DIR)); fileSystem = new UnixFakeFileSystem(); fakeFtpServer.setFileSystem(fileSystem); fileSystem.add(new DirectoryEntry(USER_HOME_DIR)); fakeFtpServer.start(); }
Source:
int wifiFeatureMaskFromStaCapabilities(int capabilities) { int features = WifiManager.WIFI_FEATURE_INFRA; // Always set this if we have a STA interface for (int i = 0; i < sFeatureCapabilityTranslation.length; i++) { if ((capabilities & sFeatureCapabilityTranslation[i][1]) != 0) { features |= sFeatureCapabilityTranslation[i][0]; } } return features; }

Target:
int wifiFeatureMaskFromStaCapabilities(int capabilities) { int features = 0; for (int i = 0; i < sFeatureCapabilityTranslation.length; i++) { if ((capabilities & sFeatureCapabilityTranslation[i][1]) != 0) { features |= sFeatureCapabilityTranslation[i][0]; } } return features; }
Source:
public void test2GhzQualifiedNo5GhzAvailable() { // Do not perform selection on 2GHz if current network is good and no 5GHz available testStayOrSwitch(mThresholdQualifiedRssi2G + 1, false, mThresholdQualifiedRssi2G + 10, false, false); }

Target:
public void test2GhzQualifiedNo5GhzAvailable() { // Do not perform selection on 2GHz if current network is good and no 5GHz available testStayOrSwitch(mThresholdQualifiedRssi2G, false, mThresholdQualifiedRssi2G + 10, false, false); }
Source:
public void test2GhzNotQualifiedOther2GhzAvailable() { // Run Selection on 2Ghz networks when not qualified even if no 5GHz available testStayOrSwitch(mThresholdQualifiedRssi2G - 1, false, mThresholdQualifiedRssi2G + 1, false, true); }

Target:
public void test2GhzNotQualifiedOther2GhzAvailable() { // Run Selection on 2Ghz networks when not qualified even if no 5GHz available testStayOrSwitch(mThresholdQualifiedRssi2G - 1, false, mThresholdQualifiedRssi2G - 10, false, true); }