auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public boolean replaces(@Nullable LookupExtractorFactory other) { if (this == other) { return false; } if (other == null) { return true; } if (!(other instanceof MapLookupExtractorFactory)) { return true; } final MapLookupExtractorFactory that = (MapLookupExtractorFactory) other; return isOneToOne != that.isOneToOne || !map.equals(that.map); }

Target:
thought this `return isOneToOne != that.isOneToOne || !map.equals(that.map);` is equivalent to `!this.equals(that)`
Source:
public void configure(Binder binder) { JsonConfigProvider.bind(binder, PROPERTY_BASE, LookupConfig.class); LifecycleModule.register(binder, LookupReferencesManager.class); JsonConfigProvider.bind(binder, PROPERTY_BASE, LookupListeningAnnouncerConfig.class); Jerseys.addResource(binder, LookupListeningResource.class); LifecycleModule.register(binder, LookupReferencesManager.class); LifecycleModule.register(binder, LookupResourceListenerAnnouncer.class); }

Target:
duplicated `LifecycleModule.register(binder, LookupReferencesManager.class)`
Source:
public Response shutDown() { log.info("Received shutdown request"); executorService.schedule( new Runnable() { @Override public void run() { lifecycle.stop(); System.exit(-1); } }, 1, TimeUnit.SECONDS ); executorService.shutdown(); return Response.status(Response.Status.ACCEPTED).build(); }

Target:
Are you able to get thread dumps of the not-terminating processes?
Source:
public IntegrationTestingConfig get() { loadProperties(); return new IntegrationTestingConfig() { @Override public String getCoordinatorHost() { return coordinatorHost; } @Override public String getIndexerHost() { return indexerHost; } @Override public String getRouterHost() { return routerHost; } @Override public String getBrokerHost() { return brokerHost; } @Override public String getMiddleManagerHost() { return middleManagerHost; } @Override public String getZookeeperHosts() { return zookeeperHosts; } }; }

Target:
why would this be required again?
Source:
public AlphaNumericTopNMetricSpec( @JsonProperty("previousStop") String previousStop ) { // Set empty string as previousStop of super class otherwise we will get NPE super((previousStop == null) ? "" : previousStop); this.previousStop = (previousStop == null) ? "" : previousStop; }

Target:
instead, can you put this.previousStop = (previousStop == null) ? "" : previousStop; in the constructor of LexicographicTopNMetricSpec and here , replace line#191 by this.previousStop = super.getPreviousStop() ?
Source:
public byte[] getCacheKey() { byte[] previousStopBytes = StringUtils.toUtf8(getPreviousStop()); return ByteBuffer.allocate(1 + previousStopBytes.length) .put(CACHE_TYPE_ID) .put(previousStopBytes) .array(); }

Target:
i believe this will throw an NPE if previousStop is null
Source:
public TopNMapFn( TopNQuery query, TopNAlgorithm topNAlgorithm ) { this.query = query; this.topNAlgorithm = topNAlgorithm; this.dimension = query.getDimensionSpec().getDimension(); this.extractionFn = TopNQueryEngine.canApplyExtractionInPost(query) ? null : query.getDimensionSpec().getExtractionFn(); }

Target:
Given that we are using a rewrite strategy, at first glance, this seems weird to me. Is it a hold over from before and just not required, or is it still necessary for some reason?
Source:
public TopNMapFn( TopNQuery query, TopNAlgorithm topNAlgorithm ) { this.query = query; this.topNAlgorithm = topNAlgorithm; this.dimension = query.getDimensionSpec().getDimension(); this.extractionFn = query.getDimensionSpec().getExtractionFn(); }

Target:
this seems like an unnecessary optimization?
Source:
public static Collection<DimensionSpec> extractionsToRewrite(GroupByQuery query) { return Collections2.filter( query.getDimensions(), new Predicate<DimensionSpec>() { @Override public boolean apply(@Nullable DimensionSpec input) { return input != null && input.getExtractionFn() != null && ExtractionFn.ExtractionType.ONE_TO_ONE.equals( input.getExtractionFn().getExtractionType() ); } } ); }

Target:
I think we removed null dimensions specs, no?
Source:
public static boolean canApplyExtractionInPost(TopNQuery query) { return query != null && query.getDimensionSpec() != null && query.getDimensionSpec().getExtractionFn() != null && ExtractionFn.ExtractionType.ONE_TO_ONE.equals(query.getDimensionSpec().getExtractionFn().getExtractionType()) && query.getTopNMetricSpec().canBeOptimizedUnordered(); }

Target:
I don't think we need to check for null here. We can just have Precondition.checkNotNull, since none of the instances where this is called would have a null query.
Source:
public long getSerializedSize() { return baseIntBuffers.getSerializedSize() + 1 + 4 + 4 + 1; }

Target:
Can we get some more information on the magic numbers here?
Source:
private DataSegment createDescriptorFile(DataSegment segment, Path outDir, final FileSystem fs) throws IOException { final Path descriptorFile = new Path(outDir, "descriptor.json"); log.info("Creating descriptor file at[%s]", descriptorFile); final ByteSource byteSource = ByteSource.wrap(jsonMapper.writeValueAsBytes(segment)); byteSource.copyTo(new HdfsOutputStreamSupplier(fs, descriptorFile)); return segment; }

Target:
This is not a requirement, but you can simply chain the methods here to make it more readable ``` java ByteSource .wrap(jsonMapper.writeValueAsBytes(segment)) .copyTo(new HdfsOutputStreamSupplier(fs, descriptorFile)); ```
Source:
public String apply(long value) { return this.apply(Long.valueOf(value)); }

Target:
I wonder if there's not a reason to just let it auto-box?
Source:
private void createAuditTable(final IDBI dbi, final String tableName) { createTable( dbi, tableName, ImmutableList.of( String.format( "CREATE TABLE %1$s (\n" + " id %2$s NOT NULL,\n" + " audit_key VARCHAR(255) NOT NULL,\n" + " type VARCHAR(255) NOT NULL,\n" + " author VARCHAR(255) NOT NULL,\n" + " email_id VARCHAR(255) NOT NULL,\n" + " comment VARCHAR(2048) NOT NULL,\n" + " created_date VARCHAR(255) NOT NULL,\n" + " payload %3$s NOT NULL,\n" + " PRIMARY KEY(id)\n" + ")", tableName, getSerialType(), getPayloadType() ), String.format("CREATE INDEX idx_%1$s_key_time ON %1$s(audit_key, created_date)", tableName), String.format("CREATE INDEX idx_%1$s_type_time ON %1$s(audit_key, created_date)", tableName), String.format("CREATE INDEX idx_%1$s_audit_time ON %1$s(created_date)", tableName) ) ); }

Target:
I think we need a blob in here about what the previous state or something was. E.g., if we modified a rule, what was the previous rule?
Source:
public OnheapIncrementalIndex(IncrementalIndexSchema incrementalIndexSchema, boolean deserializeComplexMetrics, int maxRowCount) { super(incrementalIndexSchema, deserializeComplexMetrics); this.facts = new ConcurrentSkipListMap<>(); this.maxRowCount = maxRowCount; this.aggList = new Aggregator[maxRowCount][];// To handle concurrency, we allocate up to maxRowCount for(int i = 0; i < this.aggList.length; ++i){ this.aggList[i] = null; } }

Target:
I think this is overkill with memory allocation. We can revert back to the model we had in 0.6 and used a thread safe data structure here.
Source:
public int getId(String value) { if (value == null) { return -1; } final Integer id = falseIds.get(value); return id == null ? -1 : id; }

Target:
null values should be treated like empty string.
Source:
public ValueMatcher makeMatcher(ColumnSelectorFactory factory){ if (filters.size() == 0) { return new BooleanValueMatcher(false); } final ValueMatcher[] matchers = new ValueMatcher[filters.size()]; for (int i = 0; i < filters.size(); i++) { matchers[i] = filters.get(i).makeMatcher(factory); } return makeMatcher(matchers); }

Target:
I think this changes behavior. Before an empty and filter would always return true, now it returns false.
Source:
public byte[] compress(byte[] bytes) { LZFChunk chunk = null; try (final ResourceHolder<ChunkEncoder> encoder = CompressedPools.getChunkEncoder()) { chunk = encoder.get().encodeChunk(bytes, 0, bytes.length); } catch (IOException e) { log.error(e, "IOException thrown while closing ChunkEncoder."); } // IOException should be on ResourceHolder.close(), not encodeChunk, so this *should* never be null return null == chunk ? null : chunk.getData(); }

Target:
let's move the return statement in here, so we don't need the extraneous check
Source:
protected BasicDataSource getDatasource() { MetadataStorageConnectorConfig connectorConfig = getConfig(); BasicDataSource dataSource = new BasicDataSource(); dataSource.setUsername(connectorConfig.getUser()); dataSource.setPassword(connectorConfig.getPassword()); String uri = connectorConfig.getConnectURI(); dataSource.setUrl(uri); if (connectorConfig.isUseValidationQuery()) { dataSource.setValidationQuery(connectorConfig.getValidationQuery()); dataSource.setTestOnBorrow(true); } return dataSource; }

Target:
i think we should just always use a validation query
Source:
public boolean isQueryCacheable(Query query) { return !Sets.newHashSet(unCacheable).contains(query.getType()); }

Target:
no need to create a set here..
Source:
public List<String> getNames() { return Lists.newArrayList(name); }

Target:
does this have to be a list or can it be an iterable?
Source:
public QueryRunner<Result<SelectResultValue>> preMergeQueryDecoration(QueryRunner<Result<SelectResultValue>> runner) { return new UnionQueryRunner<Result<SelectResultValue>>( new IntervalChunkingQueryRunner<Result<SelectResultValue>>( runner, config.getChunkPeriod() ) ); }

Target:
is there no common place (at the broker level) we can add the unioning query runner?
Source:
public Iterable<String> getNames() { return Lists.newArrayList(name); }

Target:
Minor nitpick, but can we do Arrays.asList(name)?
Source:
public CardinalityAggregator( String name, List<DimensionSelector> selectorList, boolean byRow ) { this.name = name; this.selectorList = Lists.newArrayList(selectorList); this.collector = HyperLogLogCollector.makeLatestCollector(); this.byRow = byRow; }

Target:
why the copy?
Source:
public HashBasedNumberedShardSpec( @JsonProperty("partitionNum") int partitionNum, @JsonProperty("partitions") int partitions ) { super(partitionNum, partitions); hashFunction = Hashing.murmur3_32(); }

Target:
can this be configurable? we make it configurable elsewhere
Source:
public Status doGet() { return new Status( getVersion("/druid-server.version"), getVersion("/druid-api.version"), getExtensionVersions(), new Memory(Runtime.getRuntime()) ); }

Target:
why do we need a file to get this?
Source:
public void run() { try { Injector injector = makeInjector(); Lifecycle lifecycle = initLifecycle(injector); try { injector.getInstance(ExecutorLifecycle.class).join(); lifecycle.stop(); } catch (Throwable t) { log.error(t, "Error when starting up. Failing."); System.exit(1); } } catch (Exception e) { throw Throwables.propagate(e); } }

Target:
We are moving the exception catching out of the try{} down there and into this area. Is that intentional?
Source:
public void emitStats( String tier, MasterStats stats, List<ServerHolder> serverHolderList ) { return; }

Target:
this isn't needed
Source:
public ConjurerFirehoseFactory( @JsonProperty("startTime") Long startTime, @JsonProperty("stopTime") Long stopTime, @JsonProperty("linesPerSec") Integer linesPerSec, @JsonProperty("maxLines") Long maxLines, @JsonProperty("filePath") String filePath ) { this(Conjurer.getBuilder().withStartTime(startTime).withStopTime(stopTime).withMaxLines(maxLines).withFilePath(filePath).withLinesPerSec(linesPerSec).withCustomSchema(true)); }

Target:
formatting
Source:
public boolean hasNext() { boolean hasNext = delegate.hasNext() || !cursor.isDone(); if(!hasNext) for(BufferAggregator agg : aggregators) agg.close(); return hasNext; }

Target:
squigglies ftw
Source:
public boolean hasNext() { boolean hasNext = delegate.hasNext() || !cursor.isDone(); if(!hasNext) { // cleanup for(BufferAggregator agg : aggregators) { agg.close(); } } return hasNext; }

Target:
It is not safe to clean things up here. If an exception is thrown while iterating, it will not complete the iteration and resources will never get cleaned up. The Sequence interface provides ways of ensuring that things get closed, look at GroupByQueryEngine.process(), there's a cleanup method that you can use there which will be guaranteed to be called.
Source:
public Optional<Task> getTask(String taskid) { Preconditions.checkNotNull(taskid, "taskid"); if(tasks.containsKey(taskid)) { return Optional.of(tasks.get(taskid).task); } else { return Optional.absent(); } }

Target:
Accessing fields is generally frowned upon in idiomatic Java. I know it's an annoying extra couple of keystrokes, but it appears like the Task object is not actually encapsulating any state.
Source:
public static void injectSystemProperties(Job job) { for (String propName : System.getProperties().stringPropertyNames()) { Configuration conf = job.getConfiguration(); if (propName.startsWith("hadoop.")) { conf.set(propName.substring("hadoop.".length()), System.getProperty(propName)); } } }

Target:
It's kinda weird to pull the configuration out for each and every property... Looks like that's how the code was, which was needless. Let's fix that up now and just get the configuration once.
Source:
public Object compute(Map<String, Object> combinedAggregators) { Object retVal = combinedAggregators.get(fieldName); if (retVal == null) { throw new ISE("Mismatch! Agg[%s] was not specified!", fieldName); } return retVal; }

Target:
I'd rather figure this out earlier. Can we add a verifyFields(Set<String>) method to the postAggs which will verify that the fields it wants are there and recursively do the same for any other PostAggs they have?
Source:
public void stop() { try { for (WorkerWrapper workerWrapper : zkWorkers.values()) { workerWrapper.getWatcher().close(); } } catch (Exception e) { throw Throwables.propagate(e); } finally { started = false; } }

Target:
I wonder if the Wrapper shouldn't have a close() method if its own instead of making the people who use them know about all the things stored inside and what should and should not be closed.
Source:
protected byte[] json2fleece(String json) throws LiteCoreException { boolean commit = false; db.beginTransaction(); FLSliceResult body = null; try { body = db.encodeJSON(json5(json).getBytes()); byte[] bytes = body.getBuf(); commit = true; return bytes; } finally { if (body != null) body.free();; db.endTransaction(commit); } }

Target:
multiple semi colons;;
Source:
private static String emptyDirectory(String path){ File f = new File(path); if(f.exists()) { for (File log : f.listFiles()) { log.delete(); } f.delete(); } return path; }

Target:
It was on purpose (the directory is about to be used so there is no need to delete it), but I guess either way is fine
Source:
ConsoleLogger() { _domains.addAll(EnumSet.allOf(LogDomain.class)); }

Target:
As we have ALL, I think you can just add only ALL here.
Source:
Document(Database database, String id, FLDict body) { this(database, id, (C4Document) null); this._database = database; this._id = id; this._data = body; updateDictionary(); }

Target:
I think we don't need to set _database and _id here as `this(database, id, (C4Document) null);` should already do that.
Source:
public void testGetExistingDocWithIDInBatch() throws CouchbaseLiteException { final int NUM_DOCS = 10; Database.getLog().getConsole().setLevel(LogLevel.VERBOSE); // Save 10 docs: createDocs(NUM_DOCS); db.inBatch(new Runnable() { @Override public void run() { validateDocs(NUM_DOCS); } }); }

Target:
Is this for testing if the console log works? Can we delete it if we don't need it?
Source:
public String toString() { return "DocumentReplication {" + "replicator=" + replicator + ", is pushing =" + pushing + ", document id =" + docId + ", revision id =" + revId + ", error code =" + error.getCode()+ ", error domain=" + error.getDomain() + ", is transient=" + trans + ", flags =" + flags + ", doc is deleted =" + isDeleted + '}'; }

Target:
Please remove info that is not in public API.
Source:
public List<Result> allResults() { randomAccess = true; return new ResultSetList(); }

Target:
randomAccess is not thread safe.
Source:
public Result next() { if (query == null) throw new IllegalStateException("_query variable is null"); if (randomAccess) return null; synchronized (getDatabase().getLock()) { try { if (c4enum.next()) { return currentObject(); } else return null; } catch (LiteCoreException e) { Log.w(TAG, "Query enumeration error: %s", e); return null; } } }

Target:
randomAccess is not thread safe.
Source:
private DocumentChangeListenerToken addDocumentChangeListener(Executor executor, DocumentChangeListener listener, String docID) { // NOTE: caller method is synchronized. if (!docListenerTokens.containsKey(docID)) { Set<DocumentChangeListenerToken> listeners = Collections.synchronizedSet(new HashSet<DocumentChangeListenerToken>()); docListenerTokens.put(docID, listeners); registerC4DocObserver(docID); } DocumentChangeListenerToken token = new DocumentChangeListenerToken(executor, listener, docID); docListenerTokens.get(docID).add(token); return token; }

Target:
Does it need to be a synchronized set?
Source:
private void postDocumentChanged(final String documentID) { synchronized (lock) { if (!c4DocObservers.containsKey(documentID) || c4db == null) return; // NOTE: docListenerTokens and its Set value are synchronized collections. // And DocumentChange is immutable Set<DocumentChangeListenerToken> tokens = docListenerTokens.get(documentID); if (tokens != null) { synchronized (tokens) { DocumentChange change = new DocumentChange(documentID); for (DocumentChangeListenerToken token : tokens) token.notify(change); } } } }

Target:
As this is under the synchronized (lock), is this synchronized required?
Source:
public Document getDocument() { return rs.getQuery().getDatabase().getDocument(documentID); }

Target:
Not in spec.
Source:
public ArrayInterface setArray(int index, Array value) { return setObject(index, value); }

Target:
I think it should return Array here.
Source:
void mustBeOpen() { if (c4db == null) throw new CouchbaseLiteRuntimeException("Database is not open."); }

Target:
I think we should throw IllegalStateException instead of CouchbaseLiteRuntimeException as it's self described that this is in an inconsistent or illegal state that users shouldn't do. CouchbaseLiteRuntimeException should be something that LC might thrown but not expected?
Source:
boolean selectConflictingRevision() throws CouchbaseLiteException { try { if (!c4doc.getRawDoc().selectNextLeaf(false, true)) return false; setC4Doc(c4doc); // self.c4Doc = _c4Doc; // This will update to the selected revision } catch (LiteCoreException e) { Log.e(TAG, "Failed to selectNextLeaf: doc -> " + c4doc, e); return false; } return true; }

Target:
Is CouchbaseLiteException thrown from anything in this method? Or it should return void but throw CouchbaseLiteException instead?
Source:
public static Node getNodeBySystemSession(Node node) throws RepositoryException { node.getSession().save(); SessionProvider systemSessionProvider = getSystemSessionProvider(); return (Node) systemSessionProvider.getSession(node.getSession().getWorkspace().getName(), getRepository()) .getItem(node.getPath()); }

Target:
Why do you need to save the node before get it by system provider?
Source:
private static String getUnsupportedType(String component, String[] supportedTypes, Map<String, String> typeMapping) { String componentType = typeMapping.get(component); if (component == null || componentType == null) { return null; } for (String okayType: supportedTypes) { if (okayType.equalsIgnoreCase(componentType)) { return null; } } return componentType; }

Target:
If component is null, this will have NPE'd by this point if typeMapping does not happen to be a type that allows null keys (most don't)
Source:
public AuthnRequest build(final SAML2MessageContext context) { final SingleSignOnService ssoService = context.getIDPSingleSignOnService(this.bindingType); final String idx = this.assertionConsumerServiceIndex > 0 ? String.valueOf(assertionConsumerServiceIndex) : null; final AssertionConsumerService assertionConsumerService = context.getSPAssertionConsumerService(idx); assertionConsumerService.setLocation(this.urlResolver.compute(assertionConsumerService.getLocation(), context.getWebContext())); return buildAuthnRequest(context, assertionConsumerService, ssoService); }

Target:
Let's do that on this PR. You still have the issue of one metadata for N ACS URLs...
Source:
protected boolean isTokenRequest(final WebContext context) { return ContextHelper.isGet(context) && CommonHelper.isNotBlank(context.getRequestParameter(CasConfiguration.TICKET_PARAMETER).orElse(null)); }

Target:
isNotBlank should accept an optional and return false if it's not present
Source:
protected String getTokenFromSession(final WebContext context) { return ((Optional<String>) context.getSessionStore().get(context, Pac4jConstants.CSRF_TOKEN)).orElse(null); }

Target:
this cast seems dangerous: why is an optional stored in there?
Source:
public final Optional<RedirectAction> getLogoutAction(final WebContext context, final U currentProfile, final String targetUrl) { init(); return Optional.of(logoutActionBuilder.getLogoutAction(context, currentProfile, targetUrl)); }

Target:
ofNullable?
Source:
public SessionStore<J2EContext> buildFromTrackableSession(final J2EContext context, final Object trackableSession) { if (trackableSession != null) { return new J2EProvidedSessionStore((HttpSession) trackableSession); } else { return (SessionStore<J2EContext>) SessionStore.EMPTY; } }

Target:
I have no opinion on this, but is it really what we would want? to throw exception while before we would be returning `null`? (I haven't finished reading, so maybe I will get an answer in the rest of the diff : )
Source:
protected HttpAction redirectToIdentityProvider(final C context, final List<Client> currentClients) { final IndirectClient currentClient = (IndirectClient) currentClients.get(0); return (HttpAction) currentClient.redirect(context).get(); }

Target:
I don't think it makes sense to have an optional `HttpAction` here. The signature of the `redirect` method should not have an `Optional`. As we are working on the API, I'm wondering if this `redirect` should belong to the `IndirectClient` class instead of the `Client` interface.
Source:
public FromAttributesAuthorizationGenerator() { this.roleAttributes = Arrays.asList(new String[] {}); this.permissionAttributes = Arrays.asList(new String[] {}); }

Target:
Can you use `new ArrayList<String>();`?
Source:
protected void internalInit(WebContext context) { CommonHelper.assertNotNull("ticketValidator", this.ticketValidator); if (this.ticketValidator instanceof InitializableObject) { ((InitializableObject) this.ticketValidator).init(); } }

Target:
This is the way I used to initialize objects, but I tend to do things differently right now: initialization must be handled by the component which is initializable, not by another one using it; otherwise, initialization may be forgotten.
Source:
public void setLinkedId(final String linkedId) { if (this.linkedId != null) { // Don't allow unsetting of already set linked id CommonHelper.assertNotNull("linkedId", linkedId); } this.linkedId = linkedId; }

Target:
If we want to remove a link to an account, we should allow to set `null`. We should just remove the `CommonHelper.assertNotNull` test.
Source:
public Object getCustomParam(String name) { return (customParams!=null)?customParams.get(name):null; }

Target:
Don't check the `customParams` if it has already been checked in the `setCustomParams` method.
Source:
public String getCustomParam(String name) { if (customParams != null) { return customParams.get(name); } else { return null; } }

Target:
This check is useless as the `customParams` can never be `null`.
Source:
public boolean isProfileAuthorized(final WebContext context, final U profile) throws RequiresHttpAction { if (profile != null && !(profile instanceof AnonymousProfile)) { return true; } else { if (this.redirectionUrl != null) { throw RequiresHttpAction.redirect("user should be authenticated", context, this.redirectionUrl); } else { return false; } } }

Target:
Looks like the above block is repeated. Could we extract this bit out?
Source:
public static boolean isNotEmpty(final Collection coll) { return coll != null && !coll.isEmpty(); }

Target:
You could simply turn this into !isEmpty()
Source:
public Client findClient(final WebContext context) { final String name = context.getRequestParameter(this.clientNameParameter); if (name == null && defaultClient != null) { return defaultClient; } CommonHelper.assertNotBlank("name", name); return findClient(name); }

Target:
What is this `defaultClient` for? It doesn't seem related to the resource changes...
Source:
protected MetadataResolver initServiceProviderMetadataResolver(final WebContext context) { String finalCallbackUrl = computeFinalCallbackUrl(context); this.spMetadataResolver = new SAML2ServiceProviderMetadataResolver(this.configuration.getServiceProviderMetadataPath(), this.configuration.getServiceProviderMetadataResource(), finalCallbackUrl, (this.configuration.getServiceProviderEntityId().equals("CALLBACK_URL") ? finalCallbackUrl : this.configuration.getServiceProviderEntityId()), this.configuration.isForceServiceProviderMetadataGeneration(), this.credentialProvider); return this.spMetadataResolver.resolve(); }

Target:
I get the idea, but can you remove this for now? Let's try to keep one change at a time, there are already many things to account for.
Source:
protected MetadataResolver initServiceProviderMetadataResolver(final WebContext context) { this.spMetadataResolver = new SAML2ServiceProviderMetadataResolver(this.configuration.getServiceProviderMetadataPath(), computeFinalCallbackUrl(context), this.configuration.getServiceProviderEntityId(), this.configuration.isForceServiceProviderMetadataGeneration(), this.credentialProvider); return this.spMetadataResolver.resolve(); }

Target:
I think that passing the `configuration` could be sufficient, couldn't it? To mirror what's done for the identity provider...
Source:
protected void initializeClientConfiguration() { if (this.casPrefixUrl != null && !this.casPrefixUrl.endsWith("/")) { this.casPrefixUrl += "/"; } if (CommonHelper.isBlank(this.casPrefixUrl)) { this.casPrefixUrl = this.casLoginUrl.replaceFirst("/login$", "/$"); } else if (CommonHelper.isBlank(this.casLoginUrl)) { this.casLoginUrl = this.casPrefixUrl + "login"; } }

Target:
The `$` is not a required convention, it's part of the regexp which is the first parameter of the `replaceFirst` method. ``` String url1 = "http://localhost:8080/cas/login"; System.out.println(url1.replaceFirst("/login$", "/end")); ``` Will output: `http://localhost:8080/cas/end`. And it works for: `String url1 = "http://loginserver/cas/login";` which is the needed fix. Though, the proposed fix: `this.casPrefixUrl = this.casLoginUrl.replaceFirst("/login$", "/$");` doesn't work and generates: `Illegal group reference: group index is missing`.
Source:
public List<Client> getClients() { init(); if (this.clients == null) { return Collections.emptyList(); } else { return this.clients; } }

Target:
While `getClients` should have no initialization.
Source:
public Google2AttributesDefinition() { addAttribute(GENDER, Converters.genderConverter); addAttribute(GENDER, Converters.stringConverter); addAttribute(DISPLAY_NAME, Converters.stringConverter); addAttribute(GIVEN_NAME, Converters.stringConverter); addAttribute(FAMILY_NAME, Converters.stringConverter); addAttribute(URL, Converters.stringConverter); addAttribute(PICTURE, Converters.stringConverter); addAttribute(LANGUAGE, Converters.localeConverter); addAttribute(BIRTHDAY, Google2Converters.dateConverter); addAttribute(EMAILS, Google2Converters.listEmailConverter); }

Target:
`GENDER` again?
Source:
public String getEmail() { final List<Google2Email> list = getEmails(); if (list != null && list.size() > 0) return list.get(0).getEmail(); else return null; }

Target:
You get it right. Per code conventions, I like to see brackets around `if` and `else` clauses.
Source:
protected abstract C retrieveCredentials(final WebContext context) throws RequiresHttpAction; public final U getUserProfile(final C credentials, final WebContext context) { init(); logger.debug("credentials : {}", credentials); if (credentials == null) { return null; } final U profile = retrieveUserProfile(credentials, context); for (AuthorizationGenerator<U> authorizationGenerator : this.authorizationGenerators) { authorizationGenerator.generate(profile); } return profile; }

Target:
I would keep the condition on `!= null` as the list can be set to `null`...
Source:
public MemcachedClient create() { if (useSharedClient && clients.size() == 1) { logger.info("Using a shared client"); return clients.get(0); } logger.info("Creating a new client"); MemcachedClient client = null; try { client = new MemcachedClient(this.addresses); } catch (IOException ex) { throw new IllegalStateException("Error starting Memcached client.", ex); } clients.add(client); return client; }

Target:
this can lead to more than 1 client being created because create is probably called concurrently. Keep things simple and just make the method synchronized
Source:
public void setup() { this.map = targetInstance.getMap(name); generatedIds = generateStrings(keyCount, idLength); }

Target:
This could lead to a huge amount of data being kept in memory; even though it is just readonly.
Source:
public static File getConfigurationFile(String filename) { File file = new File(filename).getAbsoluteFile(); if (file.exists()) { return file.getAbsoluteFile(); } else { return newFile(getSimulatorHome(), "conf", filename).getAbsoluteFile(); } }

Target:
Duplicate `getAbsoluteFile()`
Source:
public MetronomeBuilder withRatePerSecond(double ratePerSecond) { if (ratePerSecond <= 0) { throw new IllegalArgumentException("ratePerSecond can't smaller than 0"); } long intervalMicros = round(SECONDS.toMicros(1) / ratePerSecond); return withIntervalMicros(intervalMicros); }

Target:
`smaller than 1`
Source:
private static boolean setValue(Object object, String value, Field field) throws IllegalAccessException { if (setIntegralValue(object, value, field)) { return true; } if (setFloatingPointValue(object, value, field)) { return true; } if (setNonNumericValue(object, value, field)) { return true; } return isProbeField(field); }

Target:
overall the commit is very good, but this method might be misleading - it doesn't set anything if the field belongs to a probe.
Source:
public long getOperationCount() { try { Long count = invokeMethod((operationCountWorkerInstance != null) ? operationCountWorkerInstance : testClassInstance, operationCountMethod); return (count == null ? -1 : count); } catch (Exception e) { LOGGER.warn("Exception while retrieving operation count from " + testCase.getId() + ": " + e.getMessage()); return -1; } }

Target:
won't this produce awful lot of warnings when the method is not available? I thought you would log it to `finest` - disabled by default, but with an option to enable it if needed.
Source:
public void terminate() throws IllegalStateException{ terminate(Integer.MAX_VALUE); }

Target:
no need to declare unchecked exception.
Source:
public void run() { long iteration = 0; while (!testContext.isStopped()) { for (int i = 0; i < keyCount; i++) { String key = keys[random.nextInt(keys.length)]; map.put(key, createValue(key,random)); iteration++; if (iteration % logFrequency == 0) { LOGGER.info(Thread.currentThread().getName() + " At iteration: " + iteration); } } } }

Target:
Do we need this inner for loop?
Source:
public T select() { int chance = random.nextInt(100); for (Map.Entry<T, Integer> entry : operations.entrySet()) { Integer probability = entry.getValue(); if ((chance -= probability) < 0) { return entry.getKey(); } } return defaultOperation; }

Target:
So for discussion sake, lets assume we have 10 instead of 100 chances, and you will have 80% read and 20% put, then the array would look like: ``` [put, put, read, read, read, read, read, read, read, read] ``` To find your operration, you can do a: ``` int index = random.nextInt(array.length); return array[index] ```
Source:
OperationSelector(Object[] operations) { this.random = new Random(); this.operations = operations; }

Target:
Personal flavour; do whatever you like. If an object can be initialized in the class constructor, I do that. It keeps the normal constructor cleaner and shorter. Especially when you have some initialization logic in the normal constructor, this can be a good way to get rid of things that don't to be there.
Source:
public void onResponse(Object response) { operations.addAndGet(performanceUpdateFrequency); }

Target:
aren't you introducing the calculation bug again?
Source:
List<MetricFamilySamples> fromCounter(String dropwizardName, Counter counter) { String name = sanitizeMetricName(dropwizardName); MetricFamilySamples.Sample sample = sampleBuilder.createSample(dropwizardName, "", new ArrayList<String>(), new ArrayList<String>(), new Long(counter.getCount()).doubleValue()); return Arrays.asList(new MetricFamilySamples(name, Type.GAUGE, getHelpMessage(dropwizardName, counter), Arrays.asList(sample))); }

Target:
Is the metric name going to match the timeseries name?
Source:
protected Child getNoLabelsChild() throws IllegalArgumentException { if (noLabelsChild == null) { throw new IllegalArgumentException("For a labelled metric you must specify the labels"); } return noLabelsChild; }

Target:
IllegalArgumentException is a runtime exception, no need to declare it.
Source:
List<MetricFamilySamples> familySamplesList(Collector.Type type, List<MetricFamilySamples.Sample> samples) { MetricFamilySamples mfs = new MetricFamilySamples(fullname, type, help, samples); List<MetricFamilySamples> mfsList = new ArrayList<MetricFamilySamples>(1); mfsList.add(mfs); return mfsList; }

Target:
This should be protected
Source:
private double nullSafeArrayLength(long[] array) { return null == array ? 0 : array.length; }

Target:
This should be static technically.
Source:
public static void main(String[] args) throws Exception { PushGateway pg = new PushGateway(args[0], args[1]); g.set(42); pg.push(pushRegistry, "job"); }

Target:
This will throw an exception if there's only one arg.
Source:
public void pushAdd(CollectorRegistry registry, String job, Map<String, String> groupingKey) throws IOException { HttpPost request = new HttpPost(); request.setEntity(createOutputEntity(registry)); doRequest(registry, job, groupingKey, request); }

Target:
I think this code and function would be better inlined in doRequest
Source:
StandardExports(StatusReader statusReader, OperatingSystemMXBean osBean, RuntimeMXBean runtimeBean) { this.statusReader = statusReader; this.osBean = osBean; this.runtimeBean = runtimeBean; this.unix = osBean instanceof UnixOperatingSystemMXBean; this.linux = osBean.getName().indexOf("Linux") == 0; }

Target:
this is getting a little towards the magic side, I'd put the RHS in parens
Source:
public void start() { this.counter = Counter.build().name(COUNTER_NAME) .help("Log4j log statements at various log levels") .labelNames("level") .register(registry); trace = counter.labels("trace"); debug = counter.labels("debug"); info = counter.labels("info"); warn = counter.labels("warn"); error = counter.labels("error"); super.start(); }

Target:
> in this case that should thrown an exception as we would double count otherwise seeing as we only ever have a single registry. No exception would be thrown currently, prometheus scrapes of the target will fail though due to duplicate metrics. I think double counting is preferable to failing scrapes for the entire target.
Source:
public void onLogin(User user) { mIconsHidden = false; supportInvalidateOptionsMenu(); Log.e("LOGGED IN", "EFCEF"); ((LoginListener)mMediaView).onLogin(user); if (((MainApplication)getApplication()).isFirstTimeGalleryUser()) { MediaFragment.createHelpDialog(this).show(); ((MainApplication)getApplication()).setFirstTimeGalleryUser(false); } }

Target:
This log can't go live.
Source:
public VCardBuilder addAdr(final Map parameters, final List values) { properties.add(new VCardProperty("adr", parameters, "text", (List) getAdrTextOrDefault(values))); return this; }

Target:
(List) cast is redundant?
Source:
private RpslObject convertToRpslObject(final WhoisResources whoisResources, final ObjectType objectType) { for (WhoisObject whoisObject : whoisResources.getWhoisObjects()) { if (objectType == ObjectType.getByName(whoisObject.getType())) { return whoisObjectMapper.map(whoisObject, FormattedServerAttributeMapper.class); } } setErrorMessage(whoisResources, "Unable to find " + objectType + " in WhoisResources"); throw new ReferenceUpdateFailedException(Response.Status.BAD_REQUEST, whoisResources); }

Target:
final?
Source:
public static boolean isIanaResource(final RpslObject resource) { final RpslAttribute netname = resource.findAttribute(AttributeType.NETNAME); final boolean status = (netname != null && IANA_NETNAME.equals(netname.getValue().trim())); LOGGER.debug("Is inetnum with netname iana? {}", resource.getKey(), netname != null ? netname.getValue() : null, status); return status; }

Target:
this appears to be a useless check - null is still used
Source:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; State state = (State) o; if (id != state.id) return false; if (count != state.count) return false; return source != null ? source.equals(state.source) : state.source == null; }

Target:
these three statements can be folded into one: return (id == state.id) && (count == state.count) && ...
Source:
public synchronized void init() { // there should be only one LoggingDriver initialized per JVM (or we won't know which applicationContext's loggerContext to log to) try { Driver driver = DriverManager.getDriver(URL_PREFIX); LOGGER.error("LoggingDriver already installed; removing"); try { DriverManager.deregisterDriver(driver); } catch (SQLException e) { throw new IllegalStateException("Unable to de-register logging JDBC driver", e); } } catch (SQLException expected) { LOGGER.error("SQLException ", expected); } try { DriverManager.registerDriver(this); } catch (SQLException e) { throw new IllegalStateException("Unable to register logging JDBC driver", e); } }

Target:
log @ debug for expected exception, or ignore
Source:
private void loadRemoteEntries() { if (swipeRefresh != null && !swipeRefresh.isRefreshing()) { swipeRefresh.setRefreshing(true); } state.setLoadRemoteEntries(new LoadRemoteEntries(this)); Utils.execute(state.loadRemoteEntries); }

Target:
Use tabs
Source:
public List<Pipeline> getPipelines() { if (pagingEnabled) { if (!isFullScreenView()) { int startIndex = ((this.getCurrentPage() - 1) * noOfPipelines); int retrieveSize = Math.min(pipelines.size() - ((this.getCurrentPage() - 1) * noOfPipelines), noOfPipelines); return pipelines.subList(startIndex, startIndex + retrieveSize); } } return pipelines; }

Target:
Just collapse these two if statements if (pagingEnabled && !isFullScreenView()) { ...
Source:
public void calculatePipelineRoutes(Task task, final Route route, List<Route> allRoutes) { if (task.getDownstreamTasks() != null && task.getDownstreamTasks().size() > 0) { for (String downstreamTaskName: task.getDownstreamTasks()) { // assume each task only appears once in the pipeline Route currentRoute = createRouteAndCopyTasks(route, task); calculatePipelineRoutes(getTaskFromName(downstreamTaskName), currentRoute, allRoutes); } } else { Route currentRoute = createRouteAndCopyTasks(route, task); allRoutes.add(currentRoute); } }

Target:
Should this method really be public?
Source:
public int getGenre() { if (id3v2Tag != null && id3v2Tag.getGenre() != -1) { return id3v2Tag.getGenre(); } else if (id3v1Tag != null) { return id3v1Tag.getGenre(); } else { return -1; } }

Target:
This changes the default behaviour and would lead to different results when a consumer updates mp3agic. We could do that in the future but should keep the decision to prefer id3v2 over id3v1 consistent in the whole library. This should go to another pull request and signed off by @mpatric before.
Source:
public static AddonArchive getDeployment() { AddonArchive archive = ShrinkWrap .create(AddonArchive.class) .addBeansXML() .addAsAddonDependencies( AddonDependencyEntry.create("org.jboss.forge.addon:ui"), AddonDependencyEntry.create("org.jboss.forge.addon:shell-test-harness"), AddonDependencyEntry.create("org.jboss.forge.addon:resources"), AddonDependencyEntry.create("org.jboss.forge.furnace.container:cdi") ); return archive; }

Target:
Remove all @AddonDeployment annotations and leave only @AddonDeployments. Also, remove the addAsAddonDependencies below.
Source:
public File move(File source, File target) throws IOException { if (target.isDirectory()) { Path path = Files.move(source.toPath(), Paths.get(target.getAbsolutePath(), source.getName()), ATOMIC_MOVE); return path.toFile(); } this.renameFile(source, target); return target; }

Target:
Can't we use this method regardless of the target type?
Source:
public void move(FileResource<?> target) { try { getFileOperations().move(file, target.getUnderlyingResourceObject()); this.file = target.getUnderlyingResourceObject(); } catch (IOException e) { throw new ResourceException("Error while moving Resource " + this, e); } }

Target:
This won't work if the target is a DirectoryResource. Return the File object from getFileOperation().move() (Change the signature)
Source:
public Metadata getMetadata(UIContext context) { return Metadata.from(super.getMetadata(context), getClass()) .name("Constraint: New Annotation") .description("Create a Bean Validation constraint annotation") .category(super.getMetadata(context).getCategory()); }

Target:
You can remove this line. Metadata.from already reuses the category from super.getMetadata
Source:
public void testFileSize() throws Exception { File file = File.createTempFile("forge", "testFileSize"); file.deleteOnExit(); try (FileWriter write = new FileWriter(file)) { write.append("Test"); FileResource<?> fileResource = factory.create(file).reify(FileResource.class); Assert.assertEquals(file.length(), fileResource.getSize()); file.delete(); } }

Target:
file.delete() should be called outside the try block, otherwise the FileWriter associated with it won´t release the lock
Source:
public boolean isCorrectMutator(MethodSource<JavaClassSource> method, PropertySource<JavaClassSource> property) { String returnType = method.getReturnType().getName(); String className = property.getOrigin().getName(); return returnType.equals(className); }

Target:
Can returnType be null? Perhaps it's better to invert this (className.equals(returnType))
Source:
public Resource<T> getChild(final String name) { throw new RuntimeException("not implemented"); }

Target:
Not backwards compatible.
Source:
public static WebArchive createWebApplication() { return ShrinkWrap.create(WebArchive.class, "spring-test.war") .addClasses(Employee.class, EmployeeService.class, DefaultEmployeeService.class, EmployeeRepository.class, DefaultEmployeeRepository.class, NullEmployeeRepository.class, EmployeeController.class, ClassPathResourceLocationsProcessor.class) .addAsLibraries(springDependencies()) .addAsLibraries(mockitoDependencies()); }

Target:
The extension internal class quite likely should not be here. Good you have added it into the archive appender, but it should be removed from here.
Source:
public void addCatalogVersion(final String catalogResource) throws Exception { final StandaloneCatalog inputCatalogVersion = XMLLoader.getObjectFromString(Resources.getResource(catalogResource).toExternalForm(), StandaloneCatalog.class); final StandaloneCatalogWithPriceOverride inputCatalogVersionWithOverride = new StandaloneCatalogWithPriceOverride(inputCatalogVersion, priceOverride, internalTenantContext.getTenantRecordId(), internalCallContextFactory); if (versionedCatalog == null) { versionedCatalog = new DefaultVersionedCatalog(new ArrayList<>()); } versionedCatalog.add(inputCatalogVersionWithOverride); }

Target:
You could use the no-arg constructor instead.
Source:
public boolean addTrackingIds(final Collection<String> trackingIds) { this.trackingIds.addAll(trackingIds); return true; }

Target:
You could have returned the result of `addAll` to make the returned value a bit more meaningful. This (historic) boolean API is a bit weird though.
Source:
public String toString() { return "DefaultSubscriptionBillingEvent{" + "type=" + type + ", plan='" + plan + '\'' + ", planPhase='" + planPhase + '\'' + ", effectiveDate=" + effectiveDate + ", totalOrdering=" + totalOrdering + ", bcdLocal=" + bcdLocal + '}'; }

Target:
Unclear if there are circular dependencies with the objects' `toString` methods (we had the problem in the past). Might be safer to just print the names.
Source:
public T call() throws Exception { try { Request.setPerThreadRequestData(requestData); UUIDs.setRandom(random); ThreadContext.bind(securityManager); ThreadContext.bind(subject); MDC.setContextMap(mdcContextMap); return delegate.call(); } finally { Request.resetPerThreadRequestData(); UUIDs.setRandom(null); ThreadContext.unbindSecurityManager(); ThreadContext.unbindSubject(); // Reset the MDC as before the call, in case the plugin fiddle'd with it MDC.setContextMap(mdcContextMap); } }

Target:
Unrelated to your change but this whole `finally` block is a crazy amount of thread reset state!
Source:
public List<AuditLogWithHistory> getEmailAuditLogsWithHistoryForId(final UUID accountEmailId, final AuditLevel auditLevel, final InternalTenantContext context) throws AccountApiException { return transactionalSqlDao.execute(true, AccountApiException.class, new EntitySqlDaoTransactionWrapper<List<AuditLogWithHistory>>() { @Override public List<AuditLogWithHistory> inTransaction(final EntitySqlDaoWrapperFactory entitySqlDaoWrapperFactory) { final AccountEmailSqlDao transactional = entitySqlDaoWrapperFactory.become(AccountEmailSqlDao.class); return auditDao.getAuditLogsWithHistoryForId(transactional, TableName.ACCOUNT_EMAIL, accountEmailId, auditLevel, context); } }); }

Target:
Can you use the other signature (without the exception)? It doesn't look like `AccountApiException` is thrown here (same remark below).
Source:
public List<AuditLog> getAuditLogs() { return ImmutableList.<AuditLog>copyOf(accountAuditLogs); }

Target:
It seems like we could change for free the definition of `accountAuditLogs` to be `private final List<AuditLog> accountAuditLogs;` and avoid that copy.
Source:
private static BigDecimal computeAmount(final BigDecimal targetTierPrice, final Integer targetQuantity) { return targetTierPrice.multiply(new BigDecimal(targetQuantity)); }

Target:
Nit: `BigDecimal.valueOf()`
Source:
public UsageDetailMode getItemResultBehaviorMode() { final UsageDetailMode mode = staticConfig.getItemResultBehaviorMode(); if (mode.compareTo(UsageDetailMode.AGGREGATE) != 0 || mode.compareTo(UsageDetailMode.DETAIL) != 0) { return UsageDetailMode.AGGREGATE; } return mode; }

Target:
You could simplify it (use `==`).
Source:
private boolean isUsageOverrideListHasOnlyNull(List<UsagePriceOverride> usagePriceOverrides) { for (UsagePriceOverride override : usagePriceOverrides) if (override != null) return false; return true; }

Target:
Nit: Add brackets: ``` if (override != null) { return false; } ```
Source:
public PaymentPluginApi getPaymentPluginApi() throws PaymentApiException { final String pluginName = getPaymentProviderPluginName(true); return getPaymentPluginApi(pluginName); }

Target:
I would have expected the opposite: Since this is called when [running payment operations](https://github.com/killbill/killbill/blob/work-for-release-0.17.x/payment/src/main/java/org/killbill/billing/payment/core/sm/payments/PaymentOperation.java#L74), and that we _only_ want to fetch deleted payment method for `GET` operations, then shouldn't this be `false`?
Source:
public Pagination<Payment> getPayments(final Long offset, final Long limit, final boolean withPluginInfo, final boolean withAttempts, final Iterable<PluginProperty> properties, final TenantContext context) { return paymentProcessor.getPayments(offset, limit, withPluginInfo, properties, context, internalCallContextFactory.createInternalTenantContext(context)); }

Target:
Same here: The new flag `withAttempts` is not passed (used) the `paymentProcessor#getAccountPayments`