auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
static <C extends Condition, CPS extends AbstractConditionParserState<C>> C parseCondition( ObjectParser<CPS, QueryParseContext> condParser, XContentParser parser, QueryParseContext parseContext ) throws IOException { CPS state = condParser.parse(parser, parseContext); String error = state.checkValid(); if (error != null) { throw new ParsingException(parser.getTokenLocation(), error); } return state.condition(); }

Target:
nitpick: I'd throw IllegalArgumentException directly from there. note that IAExc will be catched by the toplevel parse function (fromXContent) and the token location will be added from there.
Source:
double getMillisAtPercentile(double percentile) { return current.getValueAtPercentile(percentile) / TimeValue.NSEC_PER_MSEC; }

Target:
`current` Histogram isn't threadsafe on its own, so synchronization is needed here.
Source:
RollingHistogram(int size) { current = new Histogram(LOWEST_DISCERNABLE_VALUE.nanos(), HIGHEST_TRACKABLE_VALUE.nanos(), SIGNIFICANT_DIGITS); list = new ArrayList<>(); recorder = new Recorder(LOWEST_DISCERNABLE_VALUE.nanos(), HIGHEST_TRACKABLE_VALUE.nanos(), SIGNIFICANT_DIGITS); this.size = size; }

Target:
maybe assert size > 0, rotate will fail if size is 0?
Source:
public WikibaseUris(String host) { root = "http://" + host; String rootHttps = "https://" + host; entityData = root + "/wiki/Special:EntityData/"; entityDataHttps = rootHttps + "/wiki/Special:EntityData/"; entity = root + "/entity/"; statement = entity + "statement/"; value = root + "/value/"; reference = root + "/reference/"; prop = root + "/prop/"; }

Target:
Not a big fan of this. If we have root as property, rootHttps should be similar. Otherwise it looks weird, even if technical use differs.
Source:
public SimSwitcherQuery(Similarity similarity, Query subQuery) { this.similarity = Objects.requireNonNull(similarity); this.subQuery = Objects.requireNonNull(subQuery); }

Target:
static import ?
Source:
public void onBackPressed() { if (getFragment().onBackPressed()) { return; } WikipediaApp.getInstance().getApplicationContext().startService(AnalyticsIntentService.getIntent(EventLoggingConfig.EXIT_PUSH)); finish(); }

Target:
A couple notes: - getApplicationContext() returns the same thing as the actual getInstance() call. - Doing this inside onBackPressed() seems counter-intuitive. It's within the realm of possibility for a user to never press the Back button to leave the app (e.g. always pressing the Home button). Why not do this in onDestroy()?
Source:
public void setUserVisibleHint(boolean visible) { super.setUserVisibleHint(visible); if (!isAdded()) { return; } if (visible) { funnel.enter(); feedAdapter.notifyDataSetChanged(); } else { funnel.exit(); } }

Target:
Since we're now using bus events, do we need this anymore? (The whole idea was to send events to individual cards, and avoid having to rebuild the whole view hierarchy of the RecyclerView.)
Source:
public static Change.Source<? extends Change.Batch> buildKafkaPoller( String kafkaServers, Collection<String> clusterNames, Uris uris, int batchSize, Date startTime) { Map<String, Class<? extends ChangeEvent>> topicsToClass = clusterNamesAwareTopics(clusterNames); ImmutableSet<String> topics = ImmutableSet.copyOf(topicsToClass.keySet()); return new KafkaPoller(buildKafkaConsumer(kafkaServers, topicsToClass, batchSize), uris, startTime, batchSize, topics); }

Target:
`buildKafkaPoller()` should return type `KafkaPoller` and not `Change.Source<? extends Change.Batch>` (minor simplification).
Source:
public PreferenceMultiLine(Context ctx, AttributeSet attrs) { this(ctx, attrs, 0); }

Target:
Ideally we should call super() in all cases, and put your setLayoutResource() call inside an init() method which is called from all constructors.
Source:
private PartitionInfo makePartitionInfo(String name, int id) { PartitionInfo pi = mock(PartitionInfo.class); when(pi.partition()).thenReturn(id); when(pi.topic()).thenReturn(name); return pi; }

Target:
Do we really need to mock `PartitionInfo`? It looks like a simple DTO...
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:
`ImmutableList.toImmutableList()` seems a bit redundant. Static import?
Source:
private int removePrefixes(char[] s, int len) { if (len > 5 && StemmerUtil.startsWith(s, len, "naj")) return StemmerUtil.deleteN(s, 0, len, 3); return len; }

Target:
might want to use "import static" for these static methods
Source:
public void onBindViewHolder(@NonNull LanguageViewHolder holder, int position) { String languageName = WikipediaApp.getInstance().getAppLanguageLocalizedName(items.get(position)); holder.languageName.setText(String.format(getContext().getString(R.string.multilingual_onboarding_laguage_string), String.valueOf(position + 1), languageName == null ? items.get(position) : languageName)); }

Target:
This line does not need additional logic for the unsupporting languages. I've updated my patch to fix it. Please try to rebase your patch, thanks!
Source:
public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == SEARCH_REQUEST_ADD_A_LANGUAGE) { if (resultCode == Activity.RESULT_OK) { int position = data.getIntExtra(ACTIVITY_RESULT_LANG_POSITION_DATA, 0); setUpLanguageScroll(position); if (app.language().getAppLanguageCodes().size() == 1) { searchResultsFragment.startSearch(query, query != null && query.length() > 1); } } } }

Target:
Any reason for not using the local `startSearch()` function here?
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:
Why is this here since you do not depend on ServletContextEvent? Could it be moved to the constructor and have shutdownHooks unmodifiable?
Source:
public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) { View view = ((View) object); container.removeView(view); view.setTag(-1); }

Target:
Does the tag relate to any action?
Source:
public AutomatonHitEnum build(String source, HitWeigher queryWeigher, HitWeigher corpusWeigher) { if (reverse == null) { return new AutomatonHitEnum.Forward(forward, source, queryWeigher, corpusWeigher); } else { BitSet startPositions = reverse.runAllReverse(source); return new AutomatonHitEnum.TwoPass(forward, startPositions, source, queryWeigher, corpusWeigher); } }

Target:
I'd store this BitSet inside this factory instance and have a signature like: startPositions = reverse.runAllReverse(source, startPositions); So that this reused bitset is only stored in one place.
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:
are there guarantees that converted is not empty? if it can be empty we should probably skip it (calling while(input.incrementToken()) instead of if (input.incrementToken()).
Source:
public void makeProgress(int progress) { new Handler().postDelayed(() -> { circularProgressBar.setCurrentProgress(progress); if (progress == MAX_PROGRESS) { new Handler().postDelayed(() -> { setCircularProgressVisibility(GONE); circularProgressBar.setCurrentProgress(NO_PROGRESS); }, FINAL_LOAD_DELAY); } }, NO_DELAY); }

Target:
Is there a reason for post()ing this, instead of just executing it?
Source:
public CamusWrapper<String> decode(Message message) { long timestamp = 0; String payloadString; try { payloadString = new String(message.getPayload(), "UTF-8"); } catch (UnsupportedEncodingException e) { log.error("Unable to load UTF-8 encoding, falling back to system default", e); payloadString = new String(message.getPayload()); } return new CamusWrapper<String>(payloadString, System.currentTimeMillis()); }

Target:
I wonder if there is any reason to even decode to a string. Would making this a ByteArrayMessageDecoder be simpler? Then we could use it for anything! :)
Source:
public static void addDeclIfNew(Map<String, String> decls, String prefix, String uri) { if (!decls.containsKey(prefix)) { decls.put(prefix, uri); } else { final String currentUri = decls.get(prefix); if (!currentUri.equals(uri)) { log.warn("Prefix {}: <{}> is already declared, and will not be overwritten with <{}>", prefix, currentUri, uri); } } }

Target:
I don't think this warning should be here for system-defined prefixes, because it's essentially is informing the user about something they can't change. If somebody does override schema: (which I still think is crazy, but ok, let's leave this possibility) then there's no point warning them about us not overwriting it back. We just should ignore our setting then.
Source:
public void maybeShowIndicatorDots() { editOptionIndicatorDot.setVisibility((Prefs.showEditMenuOptionIndicator() && Prefs.getTotalUserDescriptionsEdited() >= ACTION_DESCRIPTION_EDIT_UNLOCK_THRESHOLD) ? VISIBLE : GONE); }

Target:
Again, this is too much specific logic that this component does not need to know about. It should only depend on Prefs.showEditMenuOptionIndicator().
Source:
Korean() { NormalizeCharMap.Builder builder = new NormalizeCharMap.Builder(); builder.add("\u00B7", "\u0020"); builder.add("\u318D", "\u0020"); builder.add("\u00AD", "\""); builder.add("\u200C", "\""); charMap = builder.build(); }

Target:
u00AD and u200C should map to "" (empty string) not "\"" (double quote). The original JSON has "\\u00AD=>" ... but the quotes are around the mapping \\u00AD=> (map to nothing) and not part of the mapping!
Source:
private void writeObject(ObjectOutputStream out) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); try (OutputStreamDataOutput osdo = new OutputStreamDataOutput(bos)) { automaton.save(osdo); } byte[] bytes = bos.toByteArray(); out.writeInt(bytes.length); out.write(bytes); }

Target:
why do you need to know the size in bytes in the output? It looks like it's just used for logging?
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:
static import?
Source:
public static String randomAsciiOfLength(int count) { return RandomStringUtils.randomAlphabetic(count); }

Target:
Done
Source:
private FileItem checkFileItem(FileItem item, FileItem prevValue, String fieldName) { if (prevValue == null) { if (fieldName.equals(item.getFieldName())) { return item; } return null; } else { return prevValue; } }

Target:
With a few less imbricated if's (minor enough, feel free to ignore): private FileItem checkFileItem(FileItem item, FileItem prevValue, String fieldName) { if (prevValue != null) return prevValue; if (fieldName.equals(item.getFieldName())) { return item; } return null; }
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:
Well, adding classes for better semantics, but ok let's go with inspecting the event then. some.trim().startsWith("{") should do it right?
Source:
public static Properties processProperties(final String propertyFileName) throws IOException { final File propertyFile = new File(propertyFileName); if (!propertyFile.exists()) { throw new FileNotFoundException(propertyFile.toString()); } final Properties properties = new Properties(); final InputStream is = new FileInputStream(propertyFile); try { properties.load(is); } finally { if (is != null) { is.close(); } } return properties; }

Target:
Wouldn't FileInputStream do it by itself if file does not exists?
Source:
public BufferedEventSender(int maxCap) { this.queue = new ArrayBlockingQueue<>(maxCap, true); }

Target:
Do we really need the queue to be fair? My understanding is that there is a kafka queue in the transport, and that queue probably isn't maintaining full order anyway (if we have multiple partitions).
Source:
MergingUpdater(AbstractTripleStore database) { this.database = database; String property = System.getProperty("outputDumps"); outputDumps = Boolean.TRUE.toString().equals(property); id = UUID.randomUUID().toString().replaceAll("-", ""); }

Target:
configuration should be injected, not read from system properties in the constructor.
Source:
private int codepointAt(final int idx) { if (idx < 0 || idx >= text.length) { return 0; } return text[idx]; }

Target:
could this hide bugs? Would it make sense to throw an exception or simply remove the check? Also because 0x0 is a valid code point this makes this return value a bit ambiguous. I'd be in favor of just accessing the array and let the JVM throw an error if this is possible.
Source:
void replaceScriptOne(StringBuilder scriptOne) { translate(scriptOne, scriptOneToScriptTwo); }

Target:
nit: Should be public
Source:
public void unregSwitch(boolean synch) { super.unregisterDP(synch); }

Target:
What's this method for? Why is it public?
Source:
public synchronized boolean removeSwitch(final long ovxDpid) { this.dpidCounter.releaseIndex((int) (0x000000 << 32 | ovxDpid)); OVXSwitch sw = this.getSwitch(ovxDpid); boolean down = sw.tearDown(); if (down) { sw.unregister(); } return down; }

Target:
If the validation step in the api throws an exception then this is not necessary.
Source:
public double getLatitude() { return mLatitude; }

Target:
Please make getters final
Source:
public int getUserId(String userName) { resultSet = executor.executeQuery("SELECT User_ID FROM Users WHERE Name LIKE '" + userName + "';"); if(resultSet == null) return -1; else { try { while(resultSet.next()) { return resultSet.getInt("User_ID"); } } catch (SQLException e) { new IllegalStateException("SQL Error: " + e); } } return -1; }

Target:
throw that please
Source:
public List<Thread> getThreads() { try { getResult(); } catch (SQLException e) { new IllegalStateException("SQL Error: " + e); } return threads; }

Target:
should be thrown, the others as well
Source:
public void setLatitude(double latitude) { this.mLatitude = latitude; }

Target:
avoid using this.
Source:
public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mContext = getActivity().getApplicationContext(); mDataBaseAdapter = new DataBaseAdapter(getActivity()); mDataBaseAdapter.createDatabase(); mDataBaseAdapter.open(); mItemAdapter = new ATMItemListAdapter(mContext, ((MainActivity) getActivity()).getLocationTracker()); setListAdapter(mItemAdapter); getLoaderManager().initLoader(0, null, this); getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); }

Target:
already set in xml
Source:
public Cursor getAddress(String rowId, String[] columns) { String selection = "rowId = ?"; String[] selectionArgs = new String[]{rowId}; return query(selection, selectionArgs, columns); }

Target:
Make final
Source:
public Cursor getWordMatches(String query, String[] columns) { String selection = KEY_ADDRESS + " LIKE ?"; String[] selectionArgs = new String[] {"%" + query + "%"}; return query(selection, selectionArgs, columns); }

Target:
Make final
Source:
public void onListItemClick(ListView listView, View view, int position, long id) { Log.i("list", "onListItemClick"); super.onListItemClick(listView, view, position, id); ATMItem item = (ATMItem) getListAdapter().getItem(position); mDataManager.setCurrentItem(item); mModeChangeRequester.onModeChange(ModesManager.ModeIndex.DETAIL); }

Target:
use const LOG
Source:
protected boolean isDuplicateEntry(String token, Usage usageRecord) { try { ClientResponse response = client.getEntry(token, usageRecord.getUuid()); if (response.getStatus() == 200) { return true; } } catch (Exception e) { LOG.warn(String.format("Could not verify duplicate entry for UUID: %s, attempt to re-push the record...", usageRecord.getUuid())); return false; } return false; }

Target:
NIT: this really isn't needed since this method returns false by default.
Source:
public boolean onCreate() { mDatabaseAdapter = new DataBaseAdapter(getContext(), SharedData.getInstance()); return true; }

Target:
Use SharedData inside DataBaseAdapter.
Source:
public void serialize(ByteBuffer bb) { bb.put(data, 0, getLength()); }

Target:
should return an int
Source:
private void registerCallbacks() { view.addCloseOnClickListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int index = MainView.getInstance().indexOfComponent(view); MainView.getInstance().remove(index); view.revalidate(); view.repaint(); MainView.getInstance().setSelectedIndex(0); } }); }

Target:
Something seems wrong with tabbing in this function
Source:
public void bridgeDeleteVxLanPort(UUID bridgeId, IPv4Addr mgmtIp) throws SerializationException, StateAccessException { Bridge b = bridgesGet(bridgeId); if (b == null || b.getVxLanPortIds() == null) { return; } for (UUID portId : b.getVxLanPortIds()) { VxLanPort p = (VxLanPort)portsGet(portId); if (p.getMgmtIpAddr().equals(mgmtIp)) { bridgeDeleteVxLanPort(p); return; } } }

Target:
Check p is null?
Source:
public JumpRule( Condition condition, UUID jumpToChainID, String jumpToChainName) { super(condition, Action.JUMP); this.jumpToChainID = jumpToChainID; this.jumpToChainName = jumpToChainName; }

Target:
I guess this won't affect compatibility with previous deployments (when reading/writing to ZK), but it would be nice if somebody can confirm.
Source:
public void afterFromProto(MessageOrBuilder proto) { condition = ZoomConvert.fromProto(proto, Condition.class); Topology.Rule rule = (Topology.Rule) proto; if (rule.getType() == Topology.Rule.Type.NAT_RULE && rule.getMatchForwardFlow()) { ForwardNatRule natRule = (ForwardNatRule) this; natRule.buildFields(); } validateProto(rule); }

Target:
Wouldn't have been possible to override the afterFromProto in the ForwardNatRule class, adding there any initialization code as needed?
Source:
public void beforeToProto() { throw new ZoomConvert.ConvertException("Conversion of an object of " + "class: " + this.getClass() + " to a protocol buffer is not " + "supported"); }

Target:
Nit: not needed
Source:
public void testConversionForByteFields() { TestableZoomObject2 pojo = new TestableZoomObject2(); TestMessage proto = pojo.toProto(TestMessage.class); assertTrue(pojo.compare(proto)); TestableZoomObject2 convertedPojo = ZoomConvert.fromProto(proto, TestableZoomObject2.class); assertTrue(pojo.equals(convertedPojo)); }

Target:
i.e. assertEquals?
Source:
public OverpassDataFetcher() { url = "http://www.overpass-api.de/api/interpreter?data="; }

Target:
zamiast tego czysciej bedzie jak zrobisz 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:
czy tworzenie nowej instancji zoomstyleparser'a za kazdym razem ma sens? Moze lepiej przechowywac go jako pole?
Source:
public void setPosition(float x, float y) { if (mapSize.x < x && mapSize.y < y) { offset.x = x; offset.y = y; } }

Target:
Nie pomyli?e? tu przypadkiem kierunków znaków?! Teraz jest chyba, ?e je?li wykracza poza mapSize. :D
Source:
public MarketHistory(Market market) { super(); this.market = market; history = new HashMap<String, List<Double>>(); }

Target:
I think we do not need super() in this file.
Source:
public static Order findAndExtractOrder(ArrayList<Order> position, String symbol) { for (Order stock : position) { if (stock.getStockSymbol().equals(symbol)) { position.remove(stock); return stock; } } return null; }

Target:
Before go through the loop make sure that position and symbol parameters are not null.
Source:
public static int ownedQuantity(ArrayList<Order> position, String symbol) { int ownedQuantity = 0; for (Order stock : position) { if (stock.getStockSymbol().equals(symbol)) { ownedQuantity += stock.getSize(); } } return ownedQuantity; }

Target:
unsafe addition, can cause integer overflow. use long instead of integer
Source:
public Market(String name) { this.marketName = name; stockList = new HashMap<String, Stock>(); marketHistory = new MarketHistory(this); orderBook = new OrderBook(this); }

Target:
Redundant variable name - just use "name"
Source:
public Trader(String name, double cashInHand) { super(); this.name = name; this.cashInHand = cashInHand; this.stocksOwned = new ArrayList<Order>(); this.ordersPlaced = new ArrayList<Order>(); }

Target:
We don't need super here
Source:
public MarketHistory(Market m) { super(); this.market = m; history = new HashMap<String, List<Double>>(); }

Target:
We don't need super here
Source:
public Trader(String traderName, double cashInHand) { super(); this.name = name; this.cashInHand = cashInHand; this.position = new ArrayList<Order>(); this.ordersPlaced = new ArrayList<Order>(); }

Target:
Unnecessary call to super()
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:
a lot of conditionals makes this less readable.
Source:
public Trader(String name, double cashInHand) { super(); this.name = name; this.cashInHand = cashInHand; this.position = new ArrayList<Holding>(); this.ordersPlaced = new ArrayList<Order>(); }

Target:
Unnecessary call to super
Source:
public BuyOrder(String inputStock, int sizeIn, double priceIn, Trader traderIn) { stockSymbol = inputStock; size = sizeIn; price = priceIn; trader = traderIn; }

Target:
you aren't calling super class. add super(params)
Source:
public void setBuyOrders(HashMap<String, ArrayList<Order>> buyOrders) { this.buyOrders = buyOrders; }

Target:
this method should be changed to private
Source:
public MarketHistory(Market m) { super(); this.m = market; history = new HashMap<String, List<Double>>(); }

Target:
This should have been changed to: this.market = m;
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:
NPE risk?
Source:
public void onClick(View v){ if(butPlus == v){ }else if(butMinus == v){ }else if(butUp == v){ }else if(butDown == v){ } }

Target:
Zawsze robi?em/widzia?em tak to zrobione: int id = v.getId(); if(id == R.id.butPlus)
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:
optional: add uri as a parameter and turn this into return RouterDataConverter.fromData(routerData, getBaseUri()) here and in other usages below
Source:
public void setUserPages(UserPages userPages) { this.userPages = userPages; userPagesNull = false; }

Target:
Good call. Whoops. Although, might want to check if the new userPages object is null, and possibly set it to true, in case someone is TRYING to null it out. :)
Source:
public static WebAppDescriptor.Builder getBuilder() { if (!isCompatApiEnabled()) { return getBuilderForVladimir(); } else { return getBuilderForLegacyApi(); } }

Target:
revert, although this will be useful to see the tests running on v2 on the gate :D
Source:
public NatRule(Condition condition, Action action, boolean dnat) { super(condition, action); this.dnat = dnat; if (!action.equals(Action.ACCEPT) && !action.equals(Action.CONTINUE) && !action.equals(Action.RETURN)) { throw new IllegalArgumentException("A nat rule's action " + "must be one of: ACCEPT, CONTINUE, or RETURN."); } }

Target:
again, scala type in java code.
Source:
public LiteralRule(Condition condition, Action action, UUID chainId) { super(condition, action, chainId); if (action != Action.ACCEPT && action != Action.DROP && action != Action.REJECT && action != Action.RETURN) throw new IllegalArgumentException("A literal rule's action " + "must be one of: ACCEPT, DROP, REJECT or RETURN."); }

Target:
The trailing curly brace is missing here. && action != Action.REJECT && action != Action.RETURN) {
Source:
public static boolean isCompatApiEnabled() { return Boolean.parseBoolean(System.getenv("midonet.newStack")); }

Target:
return System.getProperty("midonet.newStack") != null;
Source:
public void setUp() throws Exception { super.setUp(); loadBalancer = createStockLoadBalancer(); PoolResName = FuncTest.isCompatApiEnabled() ? "Pool" : "pool"; HmResName = FuncTest.isCompatApiEnabled() ? "HealthMonitor" : "health monitor"; }

Target:
we're not running v1 tests anymore, so you can use the v2 option
Source:
public void afterFromProto(Message proto) { super.afterFromProto(proto); switch (action) { case ACCEPT: flowAction = Rule.Accept; break; case DROP: flowAction = Rule.Drop; break; case REDIRECT: flowAction = Rule.Redirect; break; default: throw new IllegalArgumentException("Invalid action"); } }

Target:
Only accept and redirect are used now. I don't think Drop is needed. Accept is only needed for the case where you want to pop/push a vlan without redirecting.
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:
infinite loop! also, the buf.limit is not needed
Source:
public URI getServiceContainerGroup() { if (serviceGroupId == null) { return null; } return absoluteUri(SERVICE_CONTAINER_GROUPS, serviceGroupId); }

Target:
Nit: I think this is not really needed, since absoluteUri does this check.
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:
This shouldn't get thrown.
Source:
public String toString(){ StringBuilder sb = new StringBuilder(); sb.append("{ regEx=\"").append(regExString). append("\", className=\"").append(someClass.getCanonicalName()). append("}"); return sb.toString(); }

Target:
This could maybe be done more cleanly with a stringformatter, but this is probably fine too.
Source:
public void showProgressDialog(Context context) { if (!mShowDialog) { return; } if (mProgressDialog == null) { if (TextUtils.isEmpty(mDialogMsg)) { mDialogMsg = "Loading. Please wait..."; } mProgressDialog = ProgressDialog.show(context, "", mDialogMsg, true); return; } if (mProgressDialog.isShowing()) { return; } mProgressDialog.show(); }

Target:
Problem je context koji se menja, zato treba izbeci ovaj if. public void showProgressDialog(Context context) { if (!mShowDialog) { return; } if (TextUtils.isEmpty(mDialogMsg)) { mDialogMsg = "Loading. Please wait..."; } if (mProgressDialog != null && mProgressDialog.isShowing()) { return; } mProgressDialog = ProgressDialog.show(context, "", mDialogMsg, true); }
Source:
public byte[] getBody() throws AuthFailureError { VolleyLog.e(mBodyContent); if (mBodyContent == null) { return super.getBody(); } return mBodyContent.getBytes(); }

Target:
if (mBodyContent.equals("null"))
Source:
void resetButtons() { for (int i = 0; i < fieldSize; i++) for (int j = 0; j < fieldSize; j++) arrayOfButtons[i][j].setGraphic(new ImageView(imageEmpty)); field.resetLogic(); }

Target:
braces
Source:
public boolean moveCellsUp() { boolean dirty = false; if (moveCellsUpLoop()) dirty = true; for (int i = 0; i < GRID_WIDTH; i++) { for (int j = 0; j < (GRID_WIDTH - 1); j++) { int nextJ = j + 1; dirty = combineCells(i, nextJ, i, j, dirty); } } if (moveCellsUpLoop()) dirty = true; return dirty; }

Target:
braces
Source:
public boolean moveCellsDown() { boolean dirty = false; if (moveCellsDownLoop()) dirty = true; for (int i = 0; i < GRID_WIDTH; i++) { for (int j = GRID_WIDTH - 1; j > 0; j--) { int previousJ = j - 1; dirty = combineCells(i, previousJ, i, j, dirty); } } if (moveCellsDownLoop()) dirty = true; return dirty; }

Target:
braces
Source:
public void randomField() { for (int i = 0; i < width; i++) for (int j = 0; j < height; j++) { currentGeneration[i][j] = (int) (Math.random() * 2) == 0 ? (byte) 1 : (byte) 0; } }

Target:
braces
Source:
private short X(short x) { if (x == -1) return (short) (width - 1); if (x == width) return (short) 0; return x; }

Target:
bad name of method https://google.github.io/styleguide/javaguide.html#s4-formatting
Source:
private byte newCellState(byte cellSelf, byte neighbourCount) { if (cellSelf == 0) { if (neighbourCount == 3) return (byte) 1; else return (byte) 0; } else { if (neighbourCount == 2 || neighbourCount == 3) return (byte) 1; else return (byte) 0; } }

Target:
braces
Source:
public void setDelay(int delay) { if ((this.delay > 999 && this.delay < delay) || (this.delay < 6 && this.delay > delay)) return; else this.delay = delay; }

Target:
braces
Source:
public void dispose() { this.h.removeMessages(EVENT_DTMF_DONE); this.h.removeMessages(EVENT_PAUSE_DONE); this.h.removeMessages(EVENT_NEXT_POST_DIAL); this.parent.dispose(); this.h = null; this.owner = null; this.parent = null; }

Target:
> Use this.h.removeCallbacksAndMessages(null) instead. Done in Patch Set 2
Source:
public void dispose() { //Remove all messages from the queue this.removeCallbacksAndMessages(null); this.phone = null; }

Target:
> Use this.removeCallbacksAndMessages(null) instead. Done in Patch set 2
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:
> Use this.removeCallbacksAndMessages(null) instead. Done in Patch set 2
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:
> Use this.removeCallbacksAndMessages(null) instead. Done in Patch set 2
Source:
public void dispose() { //Remove all messages from the queue mHandler.removeCallbacksAndMessages(null); mHandler = null; super.dispose(); }

Target:
Consider promoting, this code is the same in here and RuimPhoneBookInterfaceManager.
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:
file.exists() can throw SecurityException, too. Why the check in the first place? Won't file.delete() fail gracefully anyway?
Source:
public void executeInBackground(final Runnable task) { executor.execute(new Runnable() { public void run() { System.out.println("STARTING TASK"); task.run(); System.out.println("ENDING TASK"); } }); }

Target:
remove debug printf when submitting patches.
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:
if address == null return. is better.
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:
Not a big deal, but the style in the other tests so far has been e.g. 'new T_iget_13().run();' It might be a good idea to keep all these as similar as possible. But of course that's minor.
Source:
public synchronized int delete(Uri uri, String selection, String[] selectionArgs) { SqlArguments args = new SqlArguments(uri, selection, selectionArgs); synchronized (mLock) { SQLiteDatabase db = mOpenHelper.getWritableDatabase(); int count = db.delete(args.table, args.where, args.args); if (count > 0) sendNotify(uri); return count; } }

Target:
Why are you synchronizing on "this" here if you are synchronizing on the lock below?
Source:
public synchronized int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { SqlArguments args = new SqlArguments(uri, selection, selectionArgs); synchronized (mLock) { SQLiteDatabase db = mOpenHelper.getWritableDatabase(); int count = db.update(args.table, values, args.where, args.args); if (count > 0) sendNotify(uri); return count; } }

Target:
Why are you synchronizing on "this" here if you are synchronizing on the lock below?
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:
message.isStatusReportMessage -> message.isStatusReportMessage(). Right?
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:
or just return Boolean.valueOf(prop)
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:
Lets not create a the local variable and just: sendScreenState(pm.isScreenOn());
Source:
public static void execShell(String command) { String[] args = { "/system/bin/sh", "-c", command }; try { Libcore.os.execv("/system/bin/sh", args); } catch (ErrnoException e) { throw new RuntimeException(e); } }

Target:
(args[0], args)?
Source:
public boolean onEvaluateInputViewShown() { Configuration config = getResources().getConfiguration(); return isInputViewShown() || config.keyboard == Configuration.KEYBOARD_NOKEYS || config.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_YES; }

Target:
This seems to be risky. The availability of the hard keyboard may be changed when the display rotates (e.g. Droid), and in that case, the software keyboard should be hidden. The fix should be implemented just in InputMethodManagerSerivce.java.
Source:
private static void invokeForEachKeyFactory(KeyFactoryRunnable runnable) throws Exception { for (Provider provider : getKeyFactoryProviders()) { try { runnable.run(getKeyFactory(provider)); } catch (Exception e) { throw new Exception("provider: " + provider.getName(), e); } } }

Target:
Throwable
Source:
private static void invokeForEachKeyFactoryPair(KeyFactoryPairRunnable runnable) throws Exception { for (Provider provider1 : getKeyFactoryProviders()) { for (Provider provider2 : getKeyFactoryProviders()) { try { runnable.run(getKeyFactory(provider1), getKeyFactory(provider2)); } catch (Exception e) { throw new Exception("provider1: " + provider1.getName() + ", provider2: " + provider2.getName(), e); } } } }

Target:
the others don't catch Throwable either if we want to fix one, we should probably fix them all
Source:
public GridDialog(Shell parentShell, int numColumns, boolean makeColumnsEqualWidth) { super(parentShell); mNumColumns = numColumns; mMakeColumnsEqualWidth = makeColumnsEqualWidth; setShellStyle(getShellStyle() | SWT.RESIZE); }

Target:
Don't you want to do that in AvdCreationDialog instead? I don't think the base class should arbitrarily decide how all derived dialog will behave. Also this hides the root of the problem, which is that the error message should be in a SWT.WRAP Label, which it is not and that making it wrap properly needs a hack like the one from http://stackoverflow.com/questions/3499349/layout-issue-autogrow-label-swt
Source:
private String surfaceRotationToString(int surfaceRotation) { switch (surfaceRotation) { case Surface.ROTATION_0: return "0"; case Surface.ROTATION_90: return "90"; case Surface.ROTATION_180: return "180"; case Surface.ROTATION_270: return "270"; } throw new IllegalArgumentException("Unsupported surface rotation value" + surfaceRotation); }

Target:
This method should be static and static methods typically go at the bottom of the class.
Source:
private int stringToSurfaceRotation(String s) { if (s.equals("0")) { return Surface.ROTATION_0; } if (s.equals("90")) { return Surface.ROTATION_90; } if (s.equals("180")) { return Surface.ROTATION_180; } if (s.equals("270")) { return Surface.ROTATION_270; } throw new IllegalArgumentException("Unsupported surface rotation string '" + s + "'"); }

Target:
This method should be static as well. Also, comparisons of the form "0".equals(s) are preferred over s.equals("0") since if s is null the former won't throw a NPE while the latter will. I'm aware that the rest of this file doesn't follow this convention, but there's no reason not to fix it for new patches... :)
Source:
public void testHostWithNul() throws Exception { URL url = new URL("http://host\u0000/"); try { url.openStream(); fail(); } catch (Exception expected) }

Target:
can we be more specific about the expected exception?
Source:
protected void hyperlinkActivated(@NotNull Notification notification, @NotNull HyperlinkEvent e) { if (myHyperlinks.length == 1) { myHyperlinks[0].executeIfClicked(myProject, e); return; } for (NotificationHyperlink hyperlink : myHyperlinks) { if (hyperlink.executeIfClicked(myProject, e)) { return; } } }

Target:
I don't think you should do loop unrolling here
Source:
public String getText() { return StringUtil.escapeXml(myText); }

Target:
I think it's better to do the escaping at the point where the message is going to be converted to HTML. If not maybe rename this message to getTextAsHtml.
Source:
List<E> getValues(@NotNull GrStatementOwner closure) { List<E> result = Lists.newArrayList(); for (PsiElement element : closure.getChildren()) { List<E> values = getValues(element); if (values != null && !values.isEmpty()) { result.addAll(values); } } return result; }

Target:
Maybe add protected as modified on this and the other two package protected methods to match what is done for setValue?
Source:
public static void runFinalization() { boolean shouldRunGC; synchronized(lock) { shouldRunGC = runGC; runGC = false; } if (shouldRunGC) { Runtime.getRuntime().gc(); } Runtime.getRuntime().runFinalization(); justRanFinalization = true; }

Target:
Should this assignment guarded by the lock as well?
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:
Please define resultcode before using it. int resultCode = intent != null ? intent.getIntExtra("result", 0) : 0;
Source:
public void setUp() { mHandlerThread.start(); mMessenger = new Messenger(new Handler(mHandlerThread.getLooper()) { @Override public void handleMessage(Message msg) { switch (msg.what) { case MSG_TEST_STARTED: onTestStarted(); break; case MSG_TEST_ENDED_CLEAN: onTestEnded(false); break; default: super.handleMessage(msg); } } }); }

Target:
setUp() should call super.setUp();
Source:
public void tearDown() { mHandlerThread.quitSafely(); }

Target:
tearDown() should call super.tearDown(); try { mHandlerThread.quitSafely(); } finally { super.tearDown(); }
Source:
public boolean equals(Object o) { if (this == o) return true; if (o == null || !getClass().isAssignableFrom(o.getClass())) return false; NamedObject that = (NamedObject)o; if (!myName.equals(that.myName)) return false; if (!myValues.equals(that.myValues)) return false; return true; }

Target:
Doesn't this make equals assymetrical, if this is a subclass of o then this.equals(o) may be true while o.equals(this) would be false.
Source:
public boolean filter(String filter, boolean fullTrace, Locale locale) { return allocatedClassMatches(filter, locale) || getMatchingStackFrames(filter, fullTrace, locale).size() > 0; }

Target:
!isEmpty
Source:
private static File[] splitDexPath(String path) { List<File> result = splitPaths(path, null, false); return result.toArray(new File[result.size()]); }

Target:
what is the rationale for changing this return type to File[] ? I think it's probably easier to make this.dexFiles a List<File> and have getDexFiles() return a List<File> too
Source:
protected IdeFrameFixture openProject(@NotNull String projectDirName) throws IOException { final File projectPath = setUpProject(projectDirName); WelcomeFrameFixture welcomeFrame = findWelcomeFrame(); welcomeFrame.openProjectButton().click(); FileChooserDialogFixture openProjectDialog = FileChooserDialogFixture.findOpenProjectDialog(myRobot); return openProjectAndWaitUntilOpened(projectPath, openProjectDialog); }

Target:
Just checking: this doesn't actually create .idea files for a Gradle-only project that's missing .idea files right? If not, we should probably keep at least one IntelliJ project in the VCS such that we can make sure our project open action also works.
Source:
public List<VirtualFile> getBestFileMatches() { if (myResources != null && myFile != null) { FolderConfiguration config = myConfiguration.getFullConfig(); VersionQualifier versionQualifier = config.getVersionQualifier(); config.setVersionQualifier(null); List<VirtualFile> matchingFiles = myResources.getMatchingFiles(myFile, getResourceType(), config); config.setVersionQualifier(versionQualifier); return matchingFiles; } return Collections.emptyList(); }

Target:
do try { } finally { } around this and maybe rename versionQualifier here to prevQualifier to make it clear that we are restoring it to its previous value after temporarily clearing it
Source:
Location getLocation() { return new TypeInInputLibraryLocation(inputJackLibrary.getLocation(), Jack.getUserFriendlyFormatter().getName(enclosingPackage, simpleName)); }

Target:
Cache in field?
Source:
public boolean equals(Object obj) { return obj instanceof TypeInInputLibraryLocation && ((TypeInInputLibraryLocation) obj).inputLibLoc.equals(inputLibLoc) && ((TypeInInputLibraryLocation) obj).typeName.equals(typeName); }

Target:
final
Source:
public ClassDefItem call() { long now = System.nanoTime(); ClassDefItem clazz = translateClass(name, bytes, classFile); translateTime += System.nanoTime() - now; methodDefs += classFile.getMethods().size(); fieldDefs += classFile.getFields().size(); return clazz; }

Target:
Trivial nit: Should be 1 space after equals.
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:
nit: tabs?
Source:
public boolean hasValidJdkLocation() { File javaDir = getJavaDir(); return javaDir != null && JdkLocationStep.validateJdkLocation(javaDir.getAbsolutePath()) == null; }

Target:
...and another one :-)
Source:
private String getListingOfDex(@Nonnull File dex) throws IOException { assert dex.isFile(); StringBuilder sb = new StringBuilder(); for (ClassDef def : new DexBuffer(dex).classDefs()) { String typeName = def.getTypeName(); sb.append(typeName); sb.append(":"); sb.append(TextUtils.LINE_SEPARATOR); } return sb.toString(); }

Target:
nit: useful LV?
Source:
public void setSelectedTestArtifactName(@NotNull String selectedTestArtifactName) { ImmutableSet<String> knownArtifacts = ImmutableSet.of(AndroidProject.ARTIFACT_ANDROID_TEST, AndroidProject.ARTIFACT_UNIT_TEST); checkArgument(knownArtifacts.contains(selectedTestArtifactName), "Unknown test artifact %s.", selectedTestArtifactName); mySelectedTestArtifactName = selectedTestArtifactName; }

Target:
A set with 2 elements is an overkill. Just check if the artifact name is either of those 2 constants.
Source:
private StringBuffer getPathFromDirInternal(@Nonnull CachedParentVDir baseDir, @Nonnull CachedParentVDir currentDir) { if (baseDir == currentDir) { return new StringBuffer(); } CachedParentVDir currentParent = currentDir.getParent(); assert currentParent != null; return getPathFromDirInternal(baseDir, currentParent).append(currentDir.getName()).append('/'); }

Target:
Seems similar to DirectFS, no way to share code ?
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:
This is the case at startup, right? Maybe just == -1L instead?
Source:
private void compareWithAns(String doc, String ansPath) throws FileNotFoundException { Scanner in = new Scanner(new File(ansPath)); String ansDoc = ""; while (in.hasNext()) { ansDoc += in.nextLine() + "\n"; } doc = StringUtil.replace(doc, "\n", ""); ansDoc = StringUtil.replace(ansDoc, "\n", ""); assertEquals(doc, ansDoc); }

Target:
Are you removing the \n after you added them above? Can not you just not add it?
Source:
public void setVariants( Set<BaseVariantData> variants) { mVariants = variants; }

Target:
fits on a single line
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:
this is incorrect (and should fail with my new test. This would mean that if disabled the output is null, which is not what is expected (we expect the list to contain a null value). Though I realize that this is not consistent with the Abi/Language version...