auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected Collection<MessageChannel> determineTargetChannels(Message<?> message) { List<MessageChannel> channels = new ArrayList<MessageChannel>(); ConcurrentLinkedQueue<Recipient> recipientList = this.recipients; for (Recipient recipient : recipientList) { if (recipient.accept(message)) { channels.add(recipient.getChannel()); } } return channels; }

Target:
Not sure, if this scope variable is needed anymore. `Concurrent...` does the stuff on `ConcurrentModificationException`
Source:
public MessageSelector getSelector() { return selector; }

Target:
What is a `public` goal of this getter? I'd prefer do not expose them at all to avoid undesired mutation. I understand the point for `expression` comparison, but it seems for me we have to encapsulte `equals` logic to the `Recipient` class. I think it doesn't hurt to have an extra GC from the `removeRecipient(String channelName, String selector)`. Or from other side we should check the type of `MessageSelector` to get access to its `expressionString`
Source:
public void stop() { this.setActive(false); if (this.selector != null) { try { this.selector.close(); } catch (Exception e) { logger.error("Error closing selector", e); } } if (this.serverChannel == null) { return; } try { this.serverChannel.close(); } catch (IOException e) this.serverChannel = null; super.stop(); }

Target:
I see another bug - probably unlikely and maybe not even possible, but `super.stop()` is not called if `serverChannel == null`.
Source:
protected void onInit() { if (this.getSessionAcknowledgeMode()!= null) { Integer acknowledgeMode = JmsAdapterUtils.parseAcknowledgeMode(this.getSessionAcknowledgeMode()); if (acknowledgeMode != null) { if (JmsAdapterUtils.SESSION_TRANSACTED == acknowledgeMode) { jmsTemplate.setSessionTransacted(true); } else { jmsTemplate.setSessionAcknowledgeMode(acknowledgeMode); } } } }

Target:
whitespace before `!=`
Source:
public XmlValidatingMessageSelector(Resource schema, String schemaType) throws IOException { this(schema, SchemaType.valueOf(schemaType)); }

Target:
That's not true: `schemaType` can be `null` and `empty string` as well. Yes, you have `if(schemaType == null) {` in the another ctor, but here `assert` logic has to be anyway
Source:
public void stop(Runnable callback) { try { this.connectionManager.stop(callback); } finally { this.connectionLatch = new CountDownLatch(1); } }

Target:
I suggest we do this in `start()` as well (or instead). This code relies on the fact that the connection manager invokes the callback before returning. While this is true now, it might not be in future.
Source:
protected void doStop() { try { this.active = false; this.lifecycleCondition.await(Math.min(this.stopTimeout, this.receiveTimeout), TimeUnit.MICROSECONDS); this.listening = false; } catch (InterruptedException e) { logger.debug("Thread interrupted while stopping the endpoint"); Thread.currentThread().interrupt(); } }

Target:
Needs to be in finally - we might get interrupted.
Source:
public static void main(String[] args) throws Exception { AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("SyslogdTests-context.xml", SyslogdTests.class); System.out.println("Hit enter to terminate"); System.in.read(); ctx.close(); ctx.destroy(); }

Target:
One more time: why invoke `close()` directly, if `destroy()` does the same? What does 'd' letter mean in the name of this (and similar for tcp) test class? And don't you invoke `close()` in similar test for tcp? :smile:
Source:
public String toString() { StringBuilder builder = new StringBuilder(); builder.append("JpaParameter [name=").append(this.name) .append(", value=").append(this.value) .append(", expression=").append(this.expression) .append(", projectionExpression=").append(this.projectionExpression) .append("]"); return builder.toString(); }

Target:
These two need `.getExpressionString()`.
Source:
protected Properties getIntegrationProperties() { if (this.beanFactory != null) { return IntegrationContextUtils.getIntegrationProperties(this.beanFactory); } else { return null; } }

Target:
Maybe we can return an empty Properties here (perhaps a static constant empty props so we don't create a new one for each instance). It would save a null check everywhere that uses it.
Source:
public boolean isModified() { if (this.refreshDelay < 0) { return false; } long time = System.currentTimeMillis(); if (this.refreshDelay == 0 || (time - this.lastModifiedChecked.get()) > this.refreshDelay) { this.lastModifiedChecked.set(time); boolean modified = this.source.isModified(); if (modified) { this.script = null; } return modified; } return false; }

Target:
can this be just (time - this.lastModifiedChecked.get()) > this.refreshDelay) should always be > 0
Source:
public void put(String key, String value) { Assert.notNull(key, "'key' must not be null."); Assert.notNull(value, "'value' must not be null."); BoundValueOperations<String, String> ops = redisTemplate.boundValueOps(key); ops.set(value); }

Target:
`this.redisTemplate`
Source:
public String get(String key) { Assert.notNull(key, "'key' must not be null."); BoundValueOperations<String, String> ops = redisTemplate.boundValueOps(key); return ops.get(); }

Target:
`this.redisTemplate`
Source:
protected void onInit() { super.onInit(); this.jpaExecutor.setBeanFactory(this.getBeanFactory()); if(this.evaluationContext == null) { this.evaluationContext = ExpressionUtils.createStandardEvaluationContext(getBeanFactory()); } }

Target:
use instead, please, `implements IntegrationEvaluationContextAware`
Source:
private void configureMappingRouter(AbstractMappingMessageRouter router) { if (this.channelMappings != null) { router.setChannelMappings(this.channelMappings); } if (this.resolutionRequired != null) { router.setResolutionRequired(this.resolutionRequired); } else { router.setResolutionRequired(true); } if (this.channelResolver != null) { logger.warn("'channel-resolver' attribute has been deprecated in favor of using SpEL via 'expression' attribute"); router.setChannelResolver(this.channelResolver); } }

Target:
I'm curious why this call needed to be added since AbstractMappingMessageRouter has: ``` private volatile boolean resolutionRequired = true; ```
Source:
MessageHandler createMethodInvokingHandler(Object targetObject, String targetMethodName) { MessageHandler directHandler = null; directHandler = createDirectHandlerIfPossible(targetObject, targetMethodName); if (directHandler != null) { return directHandler; } else { ServiceActivatingHandler handler = (StringUtils.hasText(targetMethodName)) ? new ServiceActivatingHandler(targetObject, targetMethodName) : new ServiceActivatingHandler(targetObject); return this.configureHandler(handler); } }

Target:
I guess 'else' is not required here since the if block has a return... personally, I'd find this easier to read: ``` MessageHandler handler = createDirectHandlerIfPossible(targetObject, targetMethodName); if (handler == null) { ServiceActivatingHandler handler = (StringUtils.hasText(targetMethodName)) ? new ServiceActivatingHandler(targetObject, targetMethodName) : new ServiceActivatingHandler(targetObject); handler = this.configureHandler(handler); } return handler; ``` ...but feel free to ignore that :)
Source:
public Message<?> receive(long timeout) { try { if (this.receiveTimeout < 0) { this.latch.await(); } else { if (!this.latch.await(this.receiveTimeout, TimeUnit.MILLISECONDS)) { this.clientTimedOut = true; } } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } this.clientHasReceived = true; return this.message; }

Target:
should this only be set if the latch.await above returned true? in the current impl I don't think it would make a difference since clientTimedOut is checked prior to clientHasReceived in the if/else below, but that order could be a fragile assumption
Source:
protected boolean isPostProcessWithinAdviceIfPresent() { return this.hasAdviceChain() ? this.postProcessWithinAdvice : true; }

Target:
`return !this.hasAdviceChain() || this.postProcessWithinAdvice;`
Source:
protected Object handleRequestMessage(Message<?> requestMessage) { Object result = this.doHandleRequestMessage(requestMessage); if (this.isPostProcessWithinAdviceIfPresent()) { this.postProcess(requestMessage, result); } return result; }

Target:
Should be **final** as and `doInvokeAdvisedRequestHandler` too. In general postProcess implementation now looks not so clear and and very stiffly: `doInvokeAdvisedRequestHandler`, in the end, delegates to this `handleRequestMessage`. So check `isPostProcessWithinAdviceIfPresent()` twice looks like redundant. Unfortunately, I don't see more flexible solution yet :-(. Maybe through a `ThreadLocal` flag?
Source:
public HDPath extend(List<ChildNumber> path2) { List<ChildNumber> mutable = new ArrayList<>(this.unmodifiableList); // Mutable copy mutable.addAll(path2); return new HDPath(mutable); }

Target:
question: the `hasPrivateKey` field ends up being false in HDPaths produced by `extend()` operations, should it be preserved or should there be a way to introduce true values?
Source:
public synchronized Sha256Hash hashForSignatureWitness( int inputIndex, Script scriptCode, Coin prevValue, SigHash type, boolean anyoneCanPay) { byte[] connectedScript = scriptCode.getProgram(); return hashForSignatureWitness(inputIndex, connectedScript, prevValue, type, anyoneCanPay); }

Target:
This parameter seems to be ignored, because it is overridden in line 1284. Is this perhaps a bug? Or am I wrong?
Source:
public int hashCode() { int hashCode = (int)version ^ "getblocks".hashCode() ^ stopHash.hashCode(); return locator.hashCode(hashCode); }

Target:
...so don't pass the "intial hashcode" into location.hashCode(...) but instead mix the various hash codes yourself here. Guava Objects.hashCode() can help.
Source:
public byte[] getProgram() { try { // Don't round-trip as Bitcoin Core doesn't and it would introduce a mismatch. if (program != null) return Arrays.copyOf(program, program.length); ByteArrayOutputStream bos = new ByteArrayOutputStream(); for (ScriptChunk chunk : chunks) { bos.write(chunk.toByteArray()); } program = bos.toByteArray(); return program; } catch (IOException e) { throw new RuntimeException(e); // Cannot happen. } }

Target:
Here we will be making many allocations.
Source:
public ECKey getKey() { final ECKey key = ECKey.fromPrivate(Arrays.copyOf(bytes, 32)); return isCompressed() ? key : key.decompress(); }

Target:
Rather than creating a compressed key and then decompressing it, shall we use the `ECKey.fromPrivate(bytes, compressed)` constructor in the first place?
Source:
public void writeWallet(Wallet wallet, OutputStream output) throws IOException { Protos.Wallet walletProto = walletToProto(wallet); int serializedSize = walletProto.getSerializedSize(); int bufferSize = serializedSize > this.walletWriteBufferSize ? this.walletWriteBufferSize : serializedSize; final CodedOutputStream codedOutput = CodedOutputStream.newInstance(output, bufferSize); walletProto.writeTo(codedOutput); codedOutput.flush(); }

Target:
Wouldn't this forced call slow down saving considerably? Do we need the minimum calculation? It doesn't hurt to pick a larger buffer, no?
Source:
public static byte[] createHeightScriptData(final int height, final int numberOfBytes) { final int maxNumberOfBytes = 4; checkArgument(numberOfBytes <= maxNumberOfBytes); final byte[] int32Buffer = ByteBuffer.allocate(maxNumberOfBytes).order(ByteOrder.LITTLE_ENDIAN).putInt(height).array(); if (numberOfBytes != maxNumberOfBytes) { return Arrays.copyOf(int32Buffer, numberOfBytes); } else { return int32Buffer; } }

Target:
I'd write '<' here, rather than '!='. It's a bit clearer imho.
Source:
public final MessageSerializer getDefaultSerializer() { // Construct a default serializer if we don't have one if (null == this.defaultSerializer) { this.defaultSerializer = getSerializer(false, false); } return defaultSerializer; }

Target:
Shouldn't this be synchronized?
Source:
TransactionInput(NetworkParameters params, Transaction parentTransaction, TransactionOutput output) { super(params); long outputIndex = output.getIndex(); try { outpoint = new TransactionOutPoint(params, outputIndex, output.getParentTransaction()); } catch (NullPointerException e) { outpoint = new TransactionOutPoint(params, output); } scriptBytes = EMPTY_ARRAY; sequence = NO_SEQUENCE; setParent(parentTransaction); this.value = output.getValue(); length = 41; }

Target:
It's usually a bad idea to catch NPE's or any other exception that can be generated by a common class of bugs. You're doing this because output.getParentTransaction() might return null? In that case use an if statement!
Source:
public void deserializeAndAddExtension(WalletExtension extension, byte[] data) throws Exception { String id = checkNotNull(extension).getWalletExtensionID(); lock.lock(); try { if (extensions.containsKey(id)) return; else { extension.deserializeWalletExtension(this, data); addExtension(extension); } } finally { lock.unlock(); } }

Target:
Missing { }
Source:
public boolean removeWatchedAddress(final Address address) { return removeWatchedAddresses(Lists.newArrayList(address)); }

Target:
FYI ImmutableList.of(address) is more efficient, but it's no big deal, that's just a note for future reference.
Source:
public void notifyBuildEnded(GerritTriggeredEvent event) { if (event instanceof ChangeBasedEvent) { IGerritHudsonTriggerConfig serverConfig = getServerConfig(event); if ((serverConfig != null && serverConfig.isGerritBuildCurrentPatchesOnly()) || this.getBuildCancellationPolicy().isEnabled()) { getRunningJobs().remove((ChangeBasedEvent)event); } } }

Target:
You check for `null` in `EventListener` so I guess you need to check for it here as well.
Source:
public void run() { GerritTrigger trigger = getGerritTrigger(); if (trigger == null) { return; } if (StringUtils.isEmpty(trigger.getTriggerConfigURL())) { return; } if (!trigger.getJob().isBuildable()) { return; } trigger.updateTriggerConfigURL(); }

Target:
To be safe, should check `gerritTrigger.getJob() != null` first.
Source:
public long calculateAverageDynamicConfigRefreshInterval() { long total = 0; for (GerritServer server : PluginImpl.getServers_()) { total += server.getConfig().getDynamicConfigRefreshInterval(); } long average = total / Math.max(1, PluginImpl.getServers_().size()); //Avoid division by 0 return Math.max(GerritDefaultValues.MINIMUM_DYNAMIC_CONFIG_REFRESH_INTERVAL, average); }

Target:
`@Restricted(NoExternalUse.class)`
Source:
public void setTriggerConfigURL(String triggerConfigURL) { // If the trigger URL has changed from the previous value, then we can't use // the project list that we might already have loaded from the last time this trigger // was started. Just make a note of that here; we'll deal with it in "start()". if (triggerConfigURL == null) { if (this.triggerConfigURL != null) { // We need to start fresh when the URL has changed. this.dynamicConfigurationChangedFromLastStart = true; } } else { if (!triggerConfigURL.equals(this.triggerConfigURL)) { // We need to start fresh when the URL has changed. this.dynamicConfigurationChangedFromLastStart = true; } else { // We had this same configuration before. this.dynamicConfigurationChangedFromLastStart = false; } } this.triggerConfigURL = triggerConfigURL; }

Target:
Have you tested that this actually works? IIRC when configuring the trigger a new instance is created, both via the UI and via pipeline script, so it's not the same instance that gets the `stop` and `start` calls.
Source:
public void run() { GerritTrigger trigger = getGerritTrigger(); if (trigger == null) { return; } if (trigger.getTriggerConfigURL() == null || trigger.getTriggerConfigURL().isEmpty()) { return; } trigger.updateTriggerConfigURL(); }

Target:
use `StringUtils.isEmpty()`
Source:
/*package*/ RunningJobs getRunningJobs() { if (runningJobs == null) { runningJobs = new RunningJobs(); } return runningJobs; }

Target:
Removing the synchronized here means there is risk of dirty write.
Source:
private List<Run> fromMemoryImprintToBuilds(MemoryImprint memoryImprint) { final List<Run> runs = new ArrayList<Run>(memoryImprint.getEntries().length); for (Entry entry : memoryImprint.getEntries()) { if (entry == null) { continue; } runs.add(entry.getBuild()); } return runs; }

Target:
`getBuild()` can also be `null` if jobs have been triggered but not yet started. Even though you take care of potential `null` entries below it is safest if we can omit them all together in the source in case some other caller isn't that foreseeing.
Source:
public void setEntryCustomUrl(GerritTriggeredEvent event, Run r, String customUrl) { MemoryImprint pb = getMemoryImprint(event); if (pb != null) { Entry entry = pb.getEntry(r.getParent()); if (entry != null) { logger.info("Recording custom URL for {}: {}", event, customUrl); entry.setCustomUrl(customUrl); } } }

Target:
lower this to `debug` or `trace` and you can fix around line 422 while you're at it ;)
Source:
public static DependencyQueueTaskDispatcher getInstance() { ExtensionList<DependencyQueueTaskDispatcher> dispatchers = Jenkins.getInstance().getExtensionList(DependencyQueueTaskDispatcher.class); if (dispatchers == null) { return null; } return dispatchers.get(0); }

Target:
I guess the list could be empty as well causing an indexoutofbounds on line 110. so adding " || dispatchers.isEmpty()" would make it safer.
Source:
public boolean initialize() { if (events == null) { try { events = CacheBuilder.newBuilder() .expireAfterWrite(unit.toMillis(expiration), TimeUnit.MILLISECONDS) .build(); logger.info("initialized replication cache with expiration in {}: {}", unit, expiration); } catch (Exception ex) { logger.warn("initialize failure in {}: {}", unit, expiration); return false; } } return true; }

Target:
Why not use the unit as the second parameter?
Source:
public List<PreparedRemark> prepareRemarkList(List<Remark> list) { if (list.isEmpty()) { return ImmutableList.of(); } List<PreparedRemark> remarksPrepared = new ArrayList<PreparedRemark>(list.size()); for (Remark remark : list) { try{ User refUser = userDao.getUserCached(remark.getRefUserId()); remarksPrepared.add(new PreparedRemark(remark,refUser)); }catch(UserNotFoundException e){ } } return remarksPrepared; }

Target:
лучше этот Exception выбрасывать на верхний уровень или обернуть в RuntimeException если не хочется его везде прописывать. Т.к. его возникновение это признак нарушения целостности БД или программной ошибки.
Source:
public void deleteTagFromTopic(int msgId, int tagId) { jdbcTemplate.update( "DELETE FROM tags WHERE msgid=? and tagid=?", new Object[]{new Integer(msgId), new Integer(tagId)} ); }

Target:
Такая конструкция избыточна, там помоему можно просто писать ", msgid, tagid" - работает varargs + auto boxing
Source:
public String getOriginalFileName() { String idArray[] = this.id.split("/"); int idLen = idArray.length; String originalFileName = ""; if(idArray != null && idArray.length>0) { originalFileName = idArray[idLen-1]; } return originalFileName; }

Target:
If you're pulling out `idLen` variable then you should use it consistently throughout the code. There's also no need for the `null` check here as the code would have already thrown a NPE on line 4483 if idArray was `null`.
Source:
public Set<String> availableRoleIds() { String[] configStrings = ServerConfigurationService.getStrings("access.enabledRoles"); LinkedHashSet<String> availableIds = new LinkedHashSet<String>(); availableIds.addAll(Arrays.asList(configStrings)); if(!this.isPubviewPossible) { availableIds.remove(PUBVIEW_ROLE); } return availableIds; }

Target:
If this isn't defined then it will return a `null` and when doing the `Arrays.asList(null)` and NPE will get thrown.
Source:
private int getKeySize() { return _keySize; }

Target:
If the `_keySize` is an `Integer` then return that here so it doesn't get unboxed and reboxed. Use `int` everywhere or `Integer` everywhere.
Source:
public void notifyBegin(List<Response.ResponseListener> listeners, Response response) { for (int i = 0; i < listeners.size(); i++) { Response.ResponseListener listener = listeners.get(i); if (listener instanceof Response.BeginListener) notifyBegin((Response.BeginListener)listener, response); } }

Target:
I don't think we need to do this - the List iterator is supposed to be simple and in this case the JIT should eliminate its allocation.
Source:
public HttpFields.Mutable getTrailers() { return trailers; }

Target:
Should not this be just `HttpFields` as return type?
Source:
public void test303(Scenario scenario) throws Exception { start(scenario, new RedirectHandler()); Response response = client.newRequest("localhost", connector.getLocalPort()) .scheme(scenario.getScheme()) .path("/303/localhost/done") .timeout(5, TimeUnit.SECONDS) .send(); assertNotNull(response); assertEquals(200, response.getStatus()); assertFalse(response.getHeaders().contains(HttpHeader.LOCATION.asString())); }

Target:
Since you have replaced `containsKey()` with `contains()`, can you also remove all the `.asString()` in this class, now that `contains()` takes a `HttpHeader`?
Source:
public String getQueryEncoding() { return _queryEncoding == null ? null : _queryEncoding.toString(); }

Target:
Should be `_queryEncoding.name()`, not `toString()`.
Source:
public void setMaxInactiveInterval(int seconds) { _dftMaxIdleSecs = seconds; System.err.println("SETMAXINACTIVE = " + seconds); if (LOG.isDebugEnabled()) { if (_dftMaxIdleSecs <= 0) LOG.debug("Sessions created by this manager are immortal (default maxInactiveInterval={})", _dftMaxIdleSecs); else LOG.debug("SessionManager default maxInactiveInterval={}", _dftMaxIdleSecs); } }

Target:
println left in
Source:
public int getSessionTimeout() { System.err.println("CALLING GETSESSIONTIMEOUT"); if (!isStarting()) throw new IllegalStateException(); if (!_enabled) throw new UnsupportedOperationException(); int timeout = -1; if (_sessionHandler != null) { timeout = _sessionHandler.getMaxInactiveInterval(); System.err.println("GETSESSIONTIMEOUT FROM SESSIONHANDLER = " + timeout); } return (int)TimeUnit.SECONDS.toMinutes(timeout); }

Target:
ditto... and more below
Source:
protected void onError(HttpField field, Throwable t) { LOG.warn("Exception while processing {}", field, t); throw new BadMessageException("Bad header value for " + field.getName()); }

Target:
add the Throwable t as the cause of this exception
Source:
public AmplitudeClient(String instance) { this.instanceName = Utils.normalizeInstanceName(instance); this.url = Constants.EVENT_LOG_URL; logThread.start(); httpThread.start(); }

Target:
I kinda like leaving this set when the variable is declared, but either way is fine.
Source:
protected void updateServer() { updateServer(false); if (logDiagnosticEvents) { Diagnostics.getLogger().flushEvents(); } }

Target:
is this boolean necessary here? can we just delegate the check if diagnostics are enabled to the diagnostics logger?
Source:
protected JSONObject getApiPropertiesTrackingOptions() { JSONObject apiPropertiesTrackingOptions = new JSONObject(); if (disabledFields.size() == 0) { return apiPropertiesTrackingOptions; } for (String key : SERVER_SIDE_PROPERTIES) { if (disabledFields.contains(key)) { try { apiPropertiesTrackingOptions.put(key, false); } catch (JSONException e) { AmplitudeLog.getLogger().e(TAG, e.toString()); } } } return apiPropertiesTrackingOptions; }

Target:
Prefer `isEmpty()`.
Source:
private String getCountryFromNetwork() { TelephonyManager manager = (TelephonyManager) context .getSystemService(Context.TELEPHONY_SERVICE); try { if (manager.getPhoneType() != TelephonyManager.PHONE_TYPE_CDMA) { String country = manager.getNetworkCountryIso(); if (country != null) { return country.toUpperCase(Locale.US); } } } catch (NullPointerException e) { // Failed to get phone type } catch (Resources.NotFoundException e) { // Failed to get phone type } return null; }

Target:
I hesitate to say this, but I think catching all Exceptions would make sense here, as it's a system call and not much we can do about it. It should probably also include the getSystemService call on line 149.
Source:
public Iterable<DynamicTest> verifySquares() { return Arrays.asList( testSquareAt(0, 0), testSquareAt(1, 2), testSquareAt(0, 1) ); }

Target:
This could use the new parameterized support in m4
Source:
public void setText(final String text) { if (this.text != null) { this.text.setText(text); return; } this.text = new Text(text); add(this.text, (Element) getElement()); }

Target:
Would it be better/easier to just have the `Text` be created/added in the constructor then just set/get from there? Could you try that?
Source:
public Column(final ColumnSize firstSize, final ColumnSize... otherSizes) { setSize(firstSize, otherSizes); setStyleName(firstSize.getCssName()); }

Target:
Why is this required? Shouldn't it be handled by `setSize()`?
Source:
public Point indexCenterPoint(int index){ if(index < 0 || index > Constants.INVENTORY_SIZE){ throw new IndexOutOfBoundsException(); } final Point base = component().screenPoint(); final int x = base.x - 3 + (index % 4) * WIDTH; final int y = base.y - 2 + (index / 4) * HEIGHT; return new Point(x + WIDTH / 2, y + HEIGHT / 2); }

Target:
Should be `index > Constants.INVENTORY_SIZE - 1` since you're dealing with an index.
Source:
public boolean isFull() { return ctx.inventory.select().size() > Constants.INVENTORY_SIZE-1; }

Target:
I would suggest you to improve readability by changing it to `ctx.inventory.select().size() >= Constants.INVENTORY_SIZE`
Source:
public void poll() { if (getLogCount() > 0 && !inBank()) { burn(); } else if (!inBank()){ walkToBank(); } else if (inBank() && getLogCount() > 0) { leaveBank(); } else { bank(); } }

Target:
Having an else statement in your poll() method means that your script will always be doing something, even when you don't want it to. What happens if the script gets stuck or none of your methods return the proper values?
Source:
public boolean inBank() { Area bankArea = new Area(new Tile(3179, 3447), new Tile(3191,3433)); return bankArea.contains(ctx.players.local()); }

Target:
Make your bankArea a class-wide variable and have it populated once your script starts. Currently, your poll() method has the possibility of creating the same bankArea three times, which is a waste of resources and could potentially slow down the script.
Source:
public void start() { // Checks if logged in if (!ctx.game.loggedIn()){ ctx.controller.stop(); return; } System.out.println("Script Started!"); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new Gui(); } }); }

Target:
You don't need to worry about whether or not the player is logged in; the script's start() method will not be invoked until the player is in game.
Source:
public Book book() { for(Book b : Book.values()) { if((ctx.varpbits.varpbit(Constants.SPELLBOOK_VARPBIT) & 0x3) == b.varp) return b; } return Book.NIL; }

Target:
Introduce a local variable for varp value so you don't have to grab it each iteration.
Source:
public boolean clickContinue(final boolean key) { final Component c = getContinue(); if (c != null) { if (key) { ctx.input.send(" "); return true; } else { return c.click(); } } return false; }

Target:
This can be simplified a ton. `return c != null && ((key && ctx.input.send("{VK_SPACE}")) || c.click())` The line note didn't turn out the way it should have; I meant the `clickContinue(boolean key)` method.
Source:
public Doc() { meta = new Meta(); file = new File(); path = new Path(); external = new HashMap<>(); }

Target:
I wonder if this should be `null` by default so it won't generate an empty property `external` when not needed?
Source:
public static String getFileExtension(File file) { String extension; try { extension = FilenameUtils.getExtension(file.getAbsolutePath()); } catch (Exception e) { extension = null; } return extension.toLowerCase(); }

Target:
Might be better to throw the Exception instead of swallowing it. I'd write something like: ```java public static String getFileExtension(File file) throws Exception { return FilenameUtils.getExtension(file.getAbsolutePath()).toLowerCase(); } ``` This new method might deserve also some unit test in `FsCrawlerUtilTest`.
Source:
private SearchResponse runSearch(String filename, String content) throws IOException { logger.info(" -> Testing if file has been indexed correctly{}.", filename, content == null ? "" : " and contains [" + content + "]"); String fullQuery = "+file.filename:\"" + filename + "\""; if (content != null) { fullQuery += " +content:" + content; } SearchResponse response = elasticsearchClient.search("fscrawler_test_all_documents", null, fullQuery, 10, "*"); assertThat(response.getHits().getTotal(), is(1L)); return response; }

Target:
Use here `ElasticsearchClient.defaultSearchSize` instead?
Source:
private void recycle() { if(!options.isKeepAliveTTLEnabled()) expirationTimestamp = keepAliveTimeout == 0 ? 0L : System.currentTimeMillis() + keepAliveTimeout * 1000; else { long now = System.currentTimeMillis(); long keepAliveTTL = options.getKeepAliveTTL() * 1000 - (now - initialTimestamp); expirationTimestamp = keepAliveTimeout == 0 || (keepAliveTTL <= 0) ? 0L : Math.min(now + keepAliveTimeout * 1000, now + keepAliveTTL); } listener.onRecycle(); }

Target:
this should actually be moved to `isValid` and when initialTimestamp > keepAliveTTL then return false
Source:
public boolean isValid() { long now = System.currentTimeMillis(); return expirationTimestamp == 0 || now <= expirationTimestamp && (!options.isKeepAliveTTLEnabled() || options.getKeepAliveTTL() * 1000 > now - initialTimestamp); }

Target:
can you surround with parenthesis the two expressions right and left of `&&` to make it more clear ?
Source:
public void testListenInvalidPort() { final int port = 9090; final HttpServer httpServer = vertx.createHttpServer() .requestHandler(ignore -> {}) .listen(port, onSuccess(s -> vertx.createNetServer() .connectHandler(ignore -> {}) .listen(port, onFailure(error -> { assertNotNull(error); testComplete(); })))); await(); httpServer.close(); }

Target:
we need this close to be in a finally block
Source:
void register() { register(repliedAddress, true, Promise.promise()); }

Target:
we should pass `null` and allow the downstream `EventBusImpl#addRegistration` to be passed `null`, to avoid creating a `Promise` when it is not needed.
Source:
public <T> T convert(Class<T> type) { try { if (type == JsonObject.class || type == JsonArray.class) { return (T) Json.decodeValue(buffer.toString()); } else { return Json.decodeValue(buffer.toString(), type); } } catch (Exception e) { e.printStackTrace(); throw new DecodeException(e.getMessage()); } }

Target:
no print stacktrace
Source:
public void example1Pointers() { // Build a pointer from a string JsonPointer pointer1 = JsonPointer.from("/hello/world"); // Build a pointer from an URI JsonPointer pointer2 = JsonPointer.fromURI(URI.create("#/hello/world")); // Build a pointer manually JsonPointer pointer3 = JsonPointer.create() .append("hello") .append("world"); }

Target:
don't use URI here as it will not be translated to other languages.
Source:
void timeout() { if (status.compareAndSet(Status.WAITING, Status.TIMED_OUT)) { handler.handle(Future.failedFuture(new VertxException("Timed out waiting to get lock"))); } }

Target:
use instead the string version in order to avoid creating a costly stack trace creation with the exception.
Source:
void handleClosed() { Handler<Void> endHandler = this.endHandler; synchronized (conn) { cleanupHandlers(); Handler<Void> closeHandler = this.closeHandler; if (closeHandler != null) { conn.getContext().runOnContext(closeHandler); } } if (endHandler != null) { endHandler.handle(null); } }

Target:
endHandler must be read in the synchronized block
Source:
public void setUp() throws Exception { super.setUp(); if (USE_DOMAIN_SOCKETS) { assertTrue("Native transport not enabled", USE_NATIVE_TRANSPORT); tmp = TestUtils.tmpFile("vertx", ".sock"); testAddress = SocketAddress.domainSocketAddress(tmp.getAbsolutePath()); } else { testAddress = SocketAddress.inetSocketAddress(1234, "localhost"); } testDir = testFolder.newFolder(); }

Target:
actually we don't need this because it cannot work since we only have HTTP server with domain sockets and not HTTP client, that's why only a simple test is necessary
Source:
protected <T> HandlerHolder<T> addRegistration(String address, HandlerRegistration<T> registration, boolean replyHandler, boolean localOnly) { Objects.requireNonNull(registration.getHandler(), "handler"); LocalRegistrationResult result = addLocalRegistration(address, registration, replyHandler, localOnly); addRegistration(result.newAddress, address, replyHandler, localOnly, registration::setResult); return result.holder; }

Target:
Perhaps we should seize the opportunity to rename this method. It is confusing as it is the same name as the current method but its purpose is really to provide a hook for clustered event bus to propagate the registration.
Source:
public synchronized void close() { synchronized (this) { if (timerID >= 0) { client.getVertx().cancelTimer(timerID); timerID = -1; } } endpointMap.clear(); for (HttpClientConnection conn : connectionMap.values()) { conn.close(); } }

Target:
Why `synchronize(this)` here since the method is `synchronized`?
Source:
private synchronized void checkExpired() { if (timerID >= 0) { long timestamp = System.currentTimeMillis(); endpointMap.values().forEach(e -> e.pool.closeIdle(timestamp)); timerID = client.getVertx().setTimer(1, id -> checkExpired()); } }

Target:
Why do we need this check?
Source:
static void checkType(Object obj) { if (obj instanceof String || obj instanceof Integer || obj instanceof Long || obj instanceof Boolean || obj instanceof Double || obj instanceof Float || obj instanceof Short || obj instanceof Byte || obj instanceof Character || obj instanceof byte[] || obj instanceof JsonObject || obj instanceof JsonArray || obj instanceof Shareable) { } else { throw new IllegalArgumentException("Invalid type for shareddata data structure: " + obj.getClass().getName()); } }

Target:
I think that if JsonObject and JsonArray implement it, we need to remove them from this list as well
Source:
void handleData(Buffer data) { synchronized (conn) { bytesRead += data.getByteBuf().readableBytes(); if (decoder != null) { try { decoder.offer(new DefaultHttpContent(data.getByteBuf())); } catch (HttpPostRequestDecoder.ErrorDataDecoderException e) { handleException(e); } } if (dataHandler != null) { dataHandler.handle(data); } } }

Target:
rather use `data.length()`
Source:
void add(Closeable hook) { if (closeHooks == null) { // Has to be concurrent as can be removed from non context thread closeHooks = new ConcurrentHashSet<>(); } closeHooks.add(hook); }

Target:
synchronization issue here. You may instantiate the set several times.
Source:
boolean isLocal() { return isFromWire(); }

Target:
Shouldn't it be `return !isFromWire();`
Source:
private List<String> getArguments() { List<String> args = executionContext.commandLine().allArguments(); // Add system properties passed as parameter if (systemProperties != null) { args.addAll( systemProperties.stream().map( entry -> "-D" + entry) .collect(Collectors.toList())); } // Add id - it's important as it's the application mark. args.add("-Dvertx.id=" + getId()); return args; }

Target:
seems simpler to do `systemProperties.stream().map(entry -> "-D" + entry).forEach(args::add)`
Source:
public List<String> processArgs() { // As we are maintaining the launcher and starter class, choose the right one. final List<String> processArgument = VertxCommandLauncher.getProcessArguments(); return processArgument != null ? processArgument : Starter.PROCESS_ARGS; }

Target:
why final ?
Source:
public void testVersion() throws Exception { String[] args = new String[]{"-version"}; MyStarter starter = new MyStarter(); starter.run(args); // TODO some way of getting this from the version in pom.xml assertEquals(System.getProperty("vertxVersion"), starter.getVersion()); }

Target:
no need for new String[], same for others below
Source:
protected String rtrim(String s) { if (s == null || s.length() == 0) { return s; } int pos = s.length(); while (pos > 0 && Character.isWhitespace(s.charAt(pos - 1))) { --pos; } return s.substring(0, pos); }

Target:
could be made static
Source:
public void requestBegin(HttpClientRequest request) { if (!isEnabled()) return; timings.put(request, time(null, null)); }

Target:
Always called with (null, null) - so method and URI is never taken into account?
Source:
public Boolean hasModifierProperty(@NotNull PsiModifierList modifierList, @NotNull String name) { final PsiElement parent = modifierList.getParent(); //Only apply final modifier to val local variables if (parent instanceof PsiLocalVariable && isVal((PsiLocalVariable) parent)) { return PsiModifier.FINAL.equals(name) ? Boolean.TRUE : null; } return null; }

Target:
It could be better to check for PsiModifier.FINAL.equals(name) first, before checking for instanceof and isVal
Source:
public ServletOutputStream getOutputStream() throws IOException { final ServletOutputStream originalStream = this.getResponse().getOutputStream(); return this.out; }

Target:
looks the variable originalStream is not used.
Source:
private void deleteContent( final ArtifactStore store ) throws IndyWorkflowException { List<Transfer> contents = downloadManager.listRecursively( store.getKey(), DownloadManager.ROOT_PATH ); Set<String> pending = contents.stream().map( Transfer::getPath ).collect( Collectors.toSet() ); for ( String path : pending ) { contentManager.delete( store, path, new EventMetadata().set( IGNORE_READONLY, Boolean.TRUE ) ); } }

Target:
You should be able to use `contentManager.delete(store, DownloadManager.ROOT_PATH, ...)` I believe.
Source:
public String generateStorePath( String physicalPath ) { if ( StringUtils.isBlank( baseDir ) || !physicalPath.contains( baseDir ) ) { return physicalPath; } final int storePathStart = physicalPath.indexOf( baseDir ) + baseDir.length(); final String storePath = physicalPath.substring( storePathStart ); return storePath.startsWith( "/" ) ? storePath : "/" + storePath; }

Target:
I would suggest removing the /. In physical store we use "new File( baseDir, fileInfo.getFileStorage())" so the storage path is always relative to baseDir. Although both works, they mean a bit different, e.g, "9s/3b/jasldjgenha" vs. "/9s/3b/jasldjgenha". In the this case, the leading / might confuse with the root of the whole disk.
Source:
public String toString() { return "ConnectionPoolInfo{" + "name='" + name + '\'' + ", url='" + url + '\'' + ", user='" + user + '\'' + ", password='" + password + '\'' + ", dataSourceClassname='" + dataSourceClassname + '\'' + ", driverClassname='" + driverClassname + '\'' + ", useMetrics=" + useMetrics + ", useHealthChecks=" + useHealthChecks + ", properties=" + properties + '}'; }

Target:
Just some concern for security: should we output user/pass here?
Source:
private void startRemoteManager() { if ( !remoteConfiguration.isEnabled() ) { logger.info( "Infinispan remote configuration not enabled. Skip." ); return; } ConfigurationBuilder builder = new ConfigurationBuilder(); builder.addServer().host( remoteConfiguration.getRemoteServer() ).port( remoteConfiguration.getHotrodPort() ); remoteCacheManager = new RemoteCacheManager( builder.build() ); logger.info( "Infinispan remote cache manager started." ); }

Target:
Will this need to be a list of remote servers in order to handle clustering? What if the one we have configured goes down but the cluster is still up?
Source:
public void monthNameFormat(String pattern) { monthNameFormat = new SimpleDateFormat(pattern, locale); monthNameFormat.setTimeZone(timeZone); for (MonthDescriptor month : months) { month.setLabel(monthNameFormat.format(month.getDate())); } validateAndUpdate(); }

Target:
this looks like it's copied from `init`...can you extract a private method instead?
Source:
public View getView(int position, View convertView, ViewGroup parent) { MonthView monthView = (MonthView) convertView; if (monthView == null) { monthView = MonthView.create(parent, inflater, weekdayNameFormat, listener, today); } monthView.setEvents(this.events); monthView.init(months.get(position), cells.get(position)); return monthView; }

Target:
why not pass this in `#init`?
Source:
public FluentInitializer withHighlightedDates(Collection<Date> dates) { if (dates != null) { highlightDates(dates); } return this; }

Target:
is the `!= null` check necessary here?
Source:
public int compareTo(FitnessAndQuality o) { if (fitness == o.fitness) { if (quality == o.quality) { return 0; } return quality < o.quality ? -1 : 1; } return fitness < o.fitness ? -1 : 1; }

Target:
Shouldn't this line be moved one line higher, before the close brace?
Source:
public boolean accepts(Class<?> aClass) { return aClass.isPrimitive() || aClass.isEnum() || Number.class.isAssignableFrom(aClass) || String.class.equals(aClass) || Character.class.equals(aClass) || Boolean.class.equals(aClass) || java.util.Date.class.isAssignableFrom(aClass) || java.util.Calendar.class.isAssignableFrom(aClass); }

Target:
Can you add _aClass.isEnum()_ at the end so the diff, is just 1 line, instead of 7
Source:
private boolean hasDateFormat() { return Optional .ofNullable(dateFormatContainer) .map(DateFormatContainer::getDateFormat) .isPresent(); }

Target:
although its nice to use java8 optionals. sometimes its easier to read old fashioned if null checks.
Source:
public DozerBeanMapperFactoryBean dozerMapper() throws IOException { DozerBeanMapperFactoryBean factoryBean = new DozerBeanMapperFactoryBean(); factoryBean.setMappingFiles(configurationProperties.getMappingFiles()); factoryBean.setApplicationContext(applicationContext); return factoryBean; }

Target:
Just wondering if the Mapper instance should be returned, instead of the spring factory. Or does spring wire together the Mapper by its "magic" :)
Source:
public int getMetaFromState(IBlockState state) { int i = 0; if (state.getValue(POWERED)) { i = 1; } return i; }

Target:
```java return state.getValue(POWERED) ? 1 : 0; ```
Source:
public void onEntityCollidedWithBlock(IAlchemyArray array, World world, BlockPos pos, IBlockState state, Entity entity) { double motionY = 1; double motionYGlowstoneMod = 0.1; double motionYFeatherMod = 0.05; entity.fallDistance = 0; TileAlchemyArray tileArray = (TileAlchemyArray) array; entity.motionY = motionY + motionYGlowstoneMod * (tileArray.getStackInSlot(0).getCount() - 1) + motionYFeatherMod * (tileArray.getStackInSlot(1).getCount() - 1); }

Target:
This line is a bit long, do the math on another line like in the movement array.
Source:
public String getUsage(ICommandSender sender) { return new TextComponentTranslation("commands.bloodmagic.network." + getName() + ".usage").getFormattedText() + "\n" + help; }

Target:
You are returning a localized value. It expects a ***key***.
Source:
public String getHelp() { return new TextComponentTranslation("commands.bloodmagic.bind.help").getFormattedText(); }

Target:
Pretty sure this is also supposed to just be the localization key.
Source:
public String getUsage(ICommandSender commandSender) { return new TextComponentTranslation("commands.bloodmagic.orb.usage").getFormattedText(); }

Target:
This is still an issue.
Source:
public String getHelp() { return new TextComponentTranslation("commands.bloodmagic.orb." + getName() + ".help", getInfo()).getFormattedText(); }

Target:
This expects a localization key
Source:
public static void onRitualDeath(LivingDropsEvent event){ if(!ConfigHandler.values.wellOfSufferingDrops){ if(event.getSource().equals(WayofTime.bloodmagic.ritual.RitualManager.RITUAL_DAMAGE)) { event.getDrops().clear(); } } }

Target:
Why fully qualified class name?
Source:
public static ItemStack compressInventory(ItemStack[] inv, World world) { for (CompressionHandler handler : compressionRegistry) { ItemStack stack = handler.compressInventory(inv, world); if (stack != null && stack != ItemStack.EMPTY) { return stack; } } return null; }

Target:
`stack.isEmpty()`
Source:
public boolean equals(Object o) { if (o instanceof SoulTicket) return ((SoulTicket) o).getDescription().equals(description); return false; }

Target:
If you override `equals`, you have to override `hashCode` as well.
Source:
public ItemBlockBloodTank(Block block) { super(block); setHasSubtypes(true); setMaxDamage(0); }

Target:
Unecessary.
Source:
public ItemStackWrapper(Item item, int stackSize) { this(item, stackSize, 0, null); }

Target:
Remove @ReqiredArgsConstructor and make your own ``` public ItemStackWrapper(Item item, int stackSize, int meta) { // Blah } ``` so that NBT isn't set by constructor. Use a Setter. Edit: Or make it not final. Which is perfectly fine here.
Source:
private boolean canDeclare(AbstractProject owner) { // In Hudson 1.341+ builds will be triggered via DependencyGraph // Inner class added in Hudson 1.341 String ownerClassName = owner.getClass().getName(); return DependencyGraph.class.getClasses().length > 0 // See HUDSON-5679 -- dependency graph is also not used when triggered from a promotion && !ownerClassName.equals("hudson.plugins.promoted_builds.PromotionProcess"); }

Target:
The plugin now requires newer Jenkins core version than in 2016, maybe this check is not required anymore
Source:
public void buildDependencyGraph(AbstractProject owner, DependencyGraph graph) { // Can only add dependencies in Hudson 1.341 or higher if (!canDeclare(owner)) return; for (BuildTriggerConfig config : configs) { List<AbstractProject> projectList = config.getProjectList(owner.getParent(), null); for (AbstractProject project : projectList) ParameterizedDependency.add(owner, project, config, graph); } }

Target:
please use brackets even for single-line cycles
Source:
public static void smite(final Player player) { Command_smite.smite(player, reason); }

Target:
please just leave this as `smite(player, reason`
Source:
public static void smite(final Player player) { smite(player, reason); }

Target:
Does not compile.
Source:
public boolean run(CommandSender sender, Player sender_p, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { if (args.length != 2) { return false; } final Player player = getPlayer(args[0]); if (player == null) { playerMsg(TFM_Command.PLAYER_NOT_FOUND); return true; } smite(player); return true; }

Target:
Reason should be optional.
Source:
private String shortenPackage(final String pkg) { final int sep = pkg.indexOf('/'); return sep == -1 ? "" : pkg.substring(sep + 1); }

Target:
```suggestion private static String shortenPackage(final String pkg) { ```
Source:
private String checkRatioLimit(final String minmax, final BigDecimal v) { if (v != null && (v.compareTo(BigDecimal.ZERO) == -1 || v.compareTo(BigDecimal.ONE) == 1)) { return String.format( "given %s ratio is %s, but must be between 0.0 and 1.0", minmax, v); } return null; }

Target:
While [`BigDecimal.compareTo`](https://docs.oracle.com/javase/8/docs/api/java/math/BigDecimal.html#compareTo-java.math.BigDecimal-) clearly specifies return values as `-1, 0, or 1`, `< 0` (less than zero) and `> 0` (greater than zero) look clearer to my taste, also [`Comparable.compareTo`](https://docs.oracle.com/javase/8/docs/api/java/lang/Comparable.html#compareTo-T-) specifies return values as `a negative integer, zero, or a positive`.
Source:
public void whenSealed() { assertLine("whenSealed.when", ICounter.FULLY_COVERED, 0, 0); assertLine("whenSealed.case1", ICounter.FULLY_COVERED, 0, 2); // without filter next line covered partly and has one uncovered branch: assertLine("whenSealed.case2", ICounter.FULLY_COVERED, 0, 0); assertLine("whenSealed.return", ICounter.FULLY_COVERED, 0, 0); }

Target:
Probably in conflict with #722.
Source:
public void visit(final int version, final int access, final String name, final String signature, final String superName, final String[] interfaces) { classAnnotations.clear(); coverage.setSignature(stringPool.get(signature)); coverage.setSuperName(stringPool.get(superName)); coverage.setInterfaces(stringPool.get(interfaces)); }

Target:
AFAIR instances of `ClassAnalyzer` are not reused, so this `clear()` seems useless.
Source:
public void analyzeClass(final byte[] buffer, final String location) throws IOException { try { analyzeClass(new ClassReader(buffer)); } catch (final Exception cause) { throw analyzerError(location, cause); } }

Target:
Wondering why? how this is related to ASM 6? I'm asking because we had some improvements and quite some nasty regressions/missed cases of exception handling exactly here.