auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private ChannelPipelineFactory initChannelPipelineFactory() { ChannelPipelineFactory pipelineFactory; boolean enableCompression = compressionType.equalsIgnoreCase("deflate"); if (enableCompression || enableSsl || enableIpFilter) { pipelineFactory = new AdvancedChannelPipelineFactory( enableCompression, enableSsl, keystore, keystorePassword, keystoreType, enableIpFilter, patternRuleConfigDefinition); } else { pipelineFactory = () -> Channels.pipeline(); } return pipelineFactory; }

Target:
This can be replaced by method reference, i.e. `pipelineFactory = Channels::pipeline`
Source:
public String getOpenPinName() { waitForElementByElement(pinTitle); String pinName = pinTitle.getText(); return pinName; }

Target:
return the String in one line
Source:
public IBuildServer getServer() { if (parent != null) { return parent.getServer(); } if (server != null && ((EObject) server).eIsProxy()) { InternalEObject oldServer = (InternalEObject) server; server = (IBuildServer) eResolveProxy(oldServer); if (server != oldServer) { if (eNotificationRequired()) { eNotify(new ENotificationImpl(this, Notification.RESOLVE, BuildPackage.BUILD_PLAN__SERVER, oldServer, server)); } } } return server; }

Target:
we shouldn't modify the @generated methods. I think you won't need this anyway based on what you are doing in merge()
Source:
public <T extends Object> boolean contains(AttributeDefinition<T> def) { return contains(def.name()); }

Target:
I don't think `<T extends Object>` is needed, `<T>` is enough.
Source:
public boolean equals(Object o) { if(!(o instanceof MethodKey)) return false; MethodKey m = (MethodKey) o; if(m.k != k) return false; if(m.nArgs != nArgs) return false; if(!m.method.equals(method)) return false; return true; }

Target:
`return m.method.equals(method);`, instead of this line and next?
Source:
private static int countExternalReferences(PDOMBinding binding) throws Exception { IPDOMIterator<PDOMName> extRefs = binding.getExternalReferences(); assertNotNull(extRefs); int count = 0; for( ; extRefs.hasNext(); ++count) extRefs.next(); return count; }

Target:
Since incrementing count is the main purpose of this loop, it's better to rewrite the loop as: for (; extRefs.hasNext(); extRefs.next()) { ++count; }
Source:
public void addCookie(Cookie cookie) { this.cookies.add(new ZestCookie(cookie.getDomain(), cookie.getName(), cookie.getValue(), cookie.getPath(), cookie.getExpiryDate(), cookie.getSecure())); }

Target:
Could call the method `addCookie(String domain,....)` instead.
Source:
public void testJsonEmptyDiskDescription() throws IOException { String jsonDescription = null; jsonDescription = ImagesHandler.getJsonDiskDescription("DiskAlias", ""); assertTrue("Should be map of disk alias and disk description", jsonDescription.equals("{\"DiskDescription\":\"\",\"DiskAlias\":\"DiskAlias\"}")); }

Target:
please just define on the next row.
Source:
public void MobileLogin_003_failedLoginWrongLogin() { MobileBasePageObject mobile = new MobileBasePageObject(driver); mobile.openHome(wikiURL); mobile.openRandomPage(); System.out.println(credentials.userName12); MobileSpecialUserLogin login = mobile.loginFailedDropDown(mobile.getTimeStamp(), mobile.getTimeStamp()); login.verifyWrongLoginErrorMessage(); }

Target:
remove this line
Source:
private void validateStateOfWrittenEntry(long address, @Nonnull ILogData ld) { ILogData logData; try { logData = read(address, defaultReadOptions); } catch (TrimmedException te) { // We cannot know if the write went through or not throw new UnrecoverableCorfuError("We cannot determine state of an update because of a trim."); } if (!logData.equals(ld)){ throw new OverwriteException(OverwriteCause.DIFF_DATA); } }

Target:
You can just use `read(long address)` here which also uses defaultReadOptions.
Source:
public void testReparentingToGrandparent() { RulesetModel child = rm.addRuleset("child", rootId, id1); RulesetModel grandchild = rm.addRuleset("grandchild", id1, id2); assertEquals(id1, grandchild.getParentRulesetId()); rm.removeRuleset(id1); assertEquals(rootId, grandchild.getParentRulesetId()); }

Target:
```suggestion rm.addRuleset("child", rootId, id1); ``` `child` is unused
Source:
public void unsetMavenWorkspaceRepository(MavenWorkspaceRepository mavenWorkspaceRepository) { this.mavenWorkspaceRepository = null; }

Target:
Isn't the correct thing: ```java if (this.mavenWorkspaceRepository == mavenWorkspaceRepository) { this.mavenWorkspaceRepository = null; } ``` to properly handle replacement?
Source:
public void assertAuthentication(MockWebServer server) { assertEquals(server.getRequestCount(), 2); try { assertEquals(server.takeRequest().getRequestLine(), "POST /tokens HTTP/1.1"); } catch (InterruptedException e) { Throwables.propagate(e); } }

Target:
You can't assert that the request count will be 2 in a base class like this. There are many mock tests that have more requests than that.
Source:
void whenCreateLedger_thenSuccess() throws Exception { LedgerHandle lh = bk.createLedger(BookKeeper.DigestType.MAC, ledgerPassword); assertNotNull(lh); assertNotNull(lh.getId()); log.info("[I33] Ledge created: id=" + lh.getId()); }

Target:
Again let's remove this blank lines.
Source:
public String toString() { Map<String, Object> display = new ConcurrentHashMap<String, Object>(this.values); display.remove(VALUES_KEY); return display.toString(); }

Target:
HashMap is enough, here.
Source:
public void setup() { openTSDBMessageFormatter = Mockito.mock(OpenTSDBMessageFormatter.class); writer = new TCollectorUDPWriter2(openTSDBMessageFormatter); outputWriter = Mockito.mock(Writer.class); result = Mockito.mock(Result.class); server = ServerFixtures.dummyServer(); }

Target:
This instance variable can be inlined.
Source:
void addRevisionType(Element anyMapping, Element anyMappingEnd, boolean isKey) { final Element revTypeProperty = MetadataTools.addProperty( anyMapping, verEntCfg.getRevisionTypePropName(), verEntCfg.getRevisionTypePropType(), true, isKey ); revTypeProperty.addAttribute( "type", "org.hibernate.envers.internal.entities.RevisionTypeType" ); // Add further columns to the aud table addAdditionalColumns( anyMappingEnd ); }

Target:
The arguments being passed should also be proceeded and followed by a space. See line 173 as an example.
Source:
public void walk(Consumer<Node> consumer) { treeIterable(TreeTraversal.PREORDER).forEach(consumer); }

Target:
Quite classy code!
Source:
public void onStateReceived(int segmentId, boolean isLastChunk) { if (!isCancelled && isLastChunk) { boolean isCompleted = false; synchronized (segments) { if (segments.contains((Object) segmentId)) { finishedSegments.add((Integer) segmentId); if (finishedSegments.size() == segments.size()) { log.debugf("Finished receiving state for segments %s", segments); isCompleted = true; } } } if (isCompleted) { notifyCompletion(true); } } }

Target:
why not implement in ```IntSet``` methods to avoid this casts and (un)boxing?
Source:
public Matrix removeColumn(int j) { return removeColumn(j, this.factory); }

Target:
Unnecessary `this`.
Source:
void readLogFile() { getDisplay().asyncExec(() -> setContentDescription(Messages.LogView_readLog_loading)); fetchLogEntries().thenAccept(this::updateLogViewer); }

Target:
This does not need to be async, or IF it should be async, it should have the same guard. But here we really don'T do anything bad, we can and should do this without asyncExec.
Source:
public void triggerPoolMonitoringJob() { try { poolMonitoringJob.cancel(true); } catch (Throwable t) { log.debug("Exception cancelling existing job: {}", ExceptionUtils.getRootCauseMessage(t)); } poolMonitoringJob = schedulerService.scheduleWithFixedDelay( this::managePrestartedVmsInAllVmPools, 0, vmPoolMonitorIntervalInMinutes, TimeUnit.MINUTES); }

Target:
(1) it seems like the code here won't function well when being executed by several threads simultaneously; and (2) are we sure the commands (run stateless vm in this case) behaves properly when their thread is interrupted? I think that maybe we should not cancel running tasks and trigger a new task only if we are sure that the previous one is canceled
Source:
public ITmfTrace getTrace() throws RuntimeException { for (ITmfTrace trace : TmfTraceManager.getInstance().getOpenedTraces()) { if (trace.getResource().equals(getResource())) { return trace; } } return null; }

Target:
Shouldn't receive a RuntimeException anymore?
Source:
private void assertAsSetContainsAll(MetricTarget... targets) { assertContainsAll(asSet(targets), asList(targets)); }

Target:
Minor: I wouldn't static import these for clarity.
Source:
public void appendColumn( final BaseColumn column ) throws MoveColumnVetoException { final MetaData metaData = new BaseColumnSynchronizer.ColumnMetaDataImpl( column ); for ( int i = 0; i < synchronizers.size(); i++ ) { final Synchronizer synchronizer = synchronizers.get( i ); if ( synchronizer.handlesAppend( metaData ) ) { synchronizer.append( metaData ); break; } } eventBus.fireEvent( new AfterColumnInserted() ); }

Target:
@manstis Any obscure reason to make this change? Seems like a slower iterator on a List.
Source:
private ConceptReferenceTerm getConceptReferenceTermByConceptSource(Concept concept, ConceptSource conceptSource) { Collection<ConceptMap> conceptMappings = concept.getConceptMappings(); if(conceptMappings != null && conceptSource != null) { for (ConceptMap cm : conceptMappings) { ConceptReferenceTerm term = cm.getConceptReferenceTerm(); if (term.getConceptSource() != null && term.getConceptSource().equals(conceptSource)) { return term; } } } return null; }

Target:
You won't need to test for the nullity of `term.getConceptSource()` if you do this: ```java if (conceptSource.equals(term.getConceptSource())) { ... ``` Because at this point you already know that `conceptSource` is not null.
Source:
public void testMapSubscript() { assertQuery("SELECT map(array[1], array['aa'])[1]", "SELECT 'aa'"); assertQuery("SELECT map(array['a'], array['aa'])['a']", "SELECT 'aa'"); assertQuery("SELECT map(array[array[1,1]], array['a'])[array[1,1]]", "SELECT 'a'"); assertQuery("SELECT map(array[(1,2)], array['a'])[(1,2)]", "SELECT 'a'"); // Force the last value in the key BlockBuilder to the end of the internal Slice, so that searching for longer key values can be tested. // 'idv_fail' and 'request_fail' has the same hash value. assertQuery("SELECT map(array['0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456', 'idv_fail'], array['aa', 'bb'])['request_fail']", "SELECT NULL"); assertQuery("SELECT map(array['0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456', 'idv_fail'], array['aa', 'bb'])['idv_fail']", "SELECT 'bb'"); }

Target:
@yingsu00 I don't think I understand how this works. Would you clarify? Perhaps, a unit tests would be easier to understand. What is the very long string here for?
Source:
public ImageData getImageDataFor(ImageDescriptor descriptor) { if (descriptorToImageData.containsKey(descriptor)) { return descriptorToImageData.get(descriptor); } return null; }

Target:
return descriptorToImageData.get(descriptor);
Source:
protected boolean checkCanDisableVirtIoScsi() { VmValidator vmValidator = createVmValidator(vmFromConfiguration); if (Boolean.FALSE.equals(getParameters().isVirtioScsiEnabled()) && !validate(vmValidator.canDisableVirtioScsi(getAdjustedDiskImagesFromConfiguration()))) { return false; } else return true; }

Target:
please use project formatter, this should be inside
Source:
private void doUnmarshal() { try { if(this.response != null && this.response.trim().startsWith("{")){ unmarshal(); } } catch (Exception e) { e.printStackTrace(); if(this.exception == null){ this.exception = e; } } }

Target:
if this.exception != null || this. response == null || !this.response.trim().startsWith("{"){ return; } try ... catch ...
Source:
private boolean validateHostsConnectionResults(List<Pair<Guid, Boolean>> hostsConnectionResults) { for (Pair<Guid, Boolean> hostsConnectionResult : hostsConnectionResults) { if (hostsConnectionResult.getSecond() == true) { return true; } } return false; }

Target:
don't need the "== true", it's a boolean :-)
Source:
public String getModifiedIndex() { Objects.requireNonNull(eventIndexName, "null value"); if(!eventIndexName.equals("netflow")) { return String.format("%s-%s", eventIndexName, TYPE); } return TYPE; }

Target:
Here we can check if the String is empty once we change the default value using: `if(!eventIndexName.isEmpty())`
Source:
public void applyTitle(final String title, final MutationContext mutationContext) { if (title != null && title.trim().length() > 0 && getShapeView() instanceof HasTitle) { final HasTitle hasTitle = (HasTitle) getShapeView(); hasTitle.setTitle(title); hasTitle.refreshTitle(); } }

Target:
mutationContext parameter is never used in this Class (but used in 8 method declaration). I suppose add this parameter in the future will be easier than clean up it.
Source:
public void processAdminDistribution(EDXLDistribution body, AssertionType assertion) { GenericDBUtils.logInfoServiceProcess(this.getClass()); sendToAdapter(body, assertion, adminUtils, adapterFactory); }

Target:
What is the point of all these logs here? "Flag service processing debug: PassthroughInboundAdminDistribution" would be outputted.
Source:
public void testReceivedJobMessageWithWrongJobID() { exception.expect(IllegalStateException.class); JobMessage message = mock(JobMessage.class); when(message.getJobID()).thenReturn(JOB_ID); try { jobHandler.onJobMessage(message); } finally { verify(jobSpy, atLeast(0)).getState(); verify(jobSpy, atLeast(0)).getJobID(); verifyNoMoreInteractions(jobSpy); } }

Target:
if this is supposed to throw an exception (which i guess from the looks of this), then add a fail statement below stating with what exception this should have thrown.
Source:
public UserProfile() { this.userPortalVmLoginAutomatically = true; this.sshPublicKey = ""; }

Target:
no need for explicitly using 'this'
Source:
public static void subqueryRestriction(RelNode relNode) { if(relNode instanceof HiveAggregate) { HiveAggregate aggregate = (HiveAggregate)relNode; if(!aggregate.getAggCallList().isEmpty() && aggregate.getGroupSet().isEmpty()) { throw new CalciteSubqueryRuntimeException("Subquery rewrite: Aggregate without group by is not allowed"); } } else if(relNode instanceof HiveProject || relNode instanceof HiveFilter) { subqueryRestriction(relNode.getInput(0)); } else { return; } }

Target:
This is not needed?
Source:
protected Map<String, Pair<String, String>> getExclusiveLocks() { if (isImageLockNeeded()) { return Collections.singletonMap(getDisk().getId().toString(), LockMessagesMatchUtil.DISK); } return Collections.EMPTY_MAP; }

Target:
This method is called before canDoAction(), so if getDisk() is indeed null - which you check in CDA, this will result in a NullPointerException. Instead, just get the ID from the parameters
Source:
public void run() { Socket socket; OutputStream outputStream = null; try { socket = serverSocket.accept(); String response = getResponse(socket); outputStream = socket.getOutputStream(); writeResponseHeader(outputStream); write(response.getBytes(), outputStream); outputStream.flush(); } catch (IOException e) { // e.printStackTrace(); } finally { // we should not close the connection, let the client close the // connection StreamUtils.quietlyClose(outputStream); } }

Target:
again: removing the explicit initialization: worse, not better
Source:
public final boolean mightBeRacilyClean(final int smudge_s, final int smudge_ns) { // If the index has a modification time then it came from disk // and was not generated from scratch in memory. In such cases // the entry is 'racily clean' if the entry's cached modification // time is equal to or later than the index modification time. In // such cases the work file is too close to the index to tell if // it is clean or not based on the modification time alone. // final int base = infoOffset + P_MTIME; final int mtime = NB.decodeInt32(info, base); if (smudge_s < mtime) return true; if (smudge_s == mtime) return smudge_ns <= NB.decodeInt32(info, base + 4); return false; }

Target:
Should we also delete this rule? IIRC the only reason we had it was to ensure already smudged entries stayed smudged. If we change our smudge logic to be length based this no longer makes any sense, and is actually a source of bugs by always selecting modified files as potentially racily clean.
Source:
private void init() { if (mMediaPlayerList != null) { Log.wtfStack(TAG, "init: The service has already been initialized"); return; } mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); sDeviceMaxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC); mMediaPlayerList = new MediaPlayerList(Looper.myLooper(), this); mNativeInterface = AvrcpNativeInterface.getInterface(); mNativeInterface.init(AvrcpTargetService.this); }

Target:
Since init() is only called once, could we move it to start() so that start() and stop() become symmetrical?
Source:
public void testByteBuf2BytesEmptyByteBuf() { ByteBuf buf = Unpooled.buffer(); ArrayAsserts.assertArrayEquals(new byte[]{}, ByteBufUtils.byteBuf2Bytes(buf)); buf.release(); }

Target:
nit: could you please perform the release calls in a finally block so the ByteBufs get released even if the assert fails?
Source:
public String getPagingData() { if(getPagination() == null) return ""; return getPagination().getTag(); }

Target:
Please add braces around the if expression and reformat
Source:
private static boolean isBalloonEnabled(VmManagementParametersBase params) { Boolean balloonEnabled = params.isBalloonEnabled(); return balloonEnabled != null ? balloonEnabled : VmDeviceUtils.isBalloonEnabled(params.getVmStaticData().getId()); }

Target:
As you are calling a method in the same class you may want to drop the "VmDeviceUtils." prefix.
Source:
private int distanceUntilTurn() { final GeoPoint whereIam = whereIAm(); final int fromEnd; if (whereIam == null) { fromEnd = Integer.MAX_VALUE;} else { // Get distance to end of active segment final Segment activeSeg = Route.journey().activeSegment(); fromEnd = activeSeg.distanceFromEnd(whereIam); } return fromEnd; }

Target:
Three things here: 1. Why are you using `Integer.MAX_VALUE` as a magic number, instead of the (arguably more logical) `null` value to indicate a lack of location fix? (You would obviously need to change the return type to be an `Integer` object rather than an `int` primitive.) 2. Formatting. Yuck! 3. Why not just return from the if branch; do away with the else branch, and return inline instead of having a `fromEnd` variable?
Source:
public void transformSlope(){ final ITmfTimestampTransform slope = TimestampTransformFactory.create(10, 0); assertEquals(t1e3, slope.transform(t1e2)); assertEquals(tn100, slope.transform(new TmfNanoTimestamp(10))); assertEquals(tn100, slope.transform(slope.transform(tn1))); assertEquals(tn100, slope.transform(slope.transform(tn1))); assertEquals(tn100, slope.composeWith(slope).transform(tn1)); }

Target:
yes, we already knew that
Source:
boolean isBitrateImproving(int newBitrateBps) { synchronized (critSect) { boolean initialProbe = !remoteRate.isValidEstimate() && newBitrateBps > 0; boolean bitrateAboveEstimate = remoteRate.isValidEstimate() && newBitrateBps > (int) (remoteRate .getLatestEstimate()); return initialProbe || bitrateAboveEstimate; } }

Target:
Looks like the worst that could happen is that the values in the log message are not precise
Source:
public COL get() { // load upon the first use if (parsed==null) { synchronized (this) { if (parsed==null) { try { load(); } catch (IOException e) { throw new RuntimeException(e); } } } } return parsed; }

Target:
It would be rather preferable to create a new method with error propagation
Source:
protected List<MPartStack> findDirectStacks(MPartSashContainer root) { List<MPartStack> result = new ArrayList<>(); for (MPartSashContainerElement e : root.getChildren()) { if (e instanceof MPartStack) { result.add((MPartStack) e); } else if (e instanceof MPartSashContainer) { result.addAll(findDirectStacks((MPartSashContainer) e)); } } return result; }

Target:
why not private? it is only used by the private method synchCTFState. I would place the new method below synchCTFState. I don't get really why the findElements() method does not what you need here. Both do a recursive search for MPartStack in areaModel. Maybe EModelServiceFindTest could be extended to check your use case?
Source:
public boolean isAutomaticProvisioningEnabled () { return AutomaticProvisioningStatus.ENABLED.equals(getAutomaticProvisioning()) ? true : false; }

Target:
Can be simplified to `AutomaticProvisioningStatus.ENABLED.equals(getAutomaticProvisioning());`
Source:
public Object poll() { Object value = queue.poll(); if (capacity != null) { capacity.incrementAndGet(); } return value; }

Target:
Sorry that I missed a case. If we poll `null`, we should not increment `capacity`.
Source:
public String query() { if (query == null) { synchronized (conn) { if (query == null) { query = path() == uri || queryStart == -1 ? null : queryStart > 0 && uri.length() > queryStart ? uri.substring(queryStart + 1) : HttpUtils.parseQuery(uri); } } } return query; }

Target:
This becomes unreadable with so many chain of logic operations and ternary blocks. I believe proper if statements would be preferred and more readable
Source:
public PropertyValue getValue(ClassPropertyReference propertyReference, Object rawValue) throws XWikiRestException { String reference = ""; if (rawValue != null) { reference = rawValue.toString(); } if (StringUtils.isEmpty(reference)) { return null; } DocumentReference documentReference = documentReferenceResolver.resolve(reference, EntityType.DOCUMENT); PropertyValue propertyValue = this.getValueFromQueryResult(documentReference, getPropertyDefinition(propertyReference)); if (propertyValue != null) { propertyValue.setValue(reference); } return propertyValue; }

Target:
You could also do: PropertyValue propertyValue = super.getValue(propertyReference, documentReference); just to be sure we don't miss something from the base class. It also makes it more clear that the reason we overwrite the implementation from the base class is because we want to change the input raw value and we want to add more information to the returned property value.
Source:
public boolean performPaste(Object target, ISelection selection) { if (target instanceof IBreakpointContainer && selection instanceof IStructuredSelection) { IBreakpointContainer container = (IBreakpointContainer) target; for (Object object : ((IStructuredSelection)selection)) { IBreakpoint breakpoint = (IBreakpoint)DebugPlugin.getAdapter(object, IBreakpoint.class); if (breakpoint != null) { container.getOrganizer().addBreakpoint(breakpoint, container.getCategory()); } } return true; } return false; }

Target:
double parantheses should be obsolete here
Source:
public static Node createInvalidType(Node node, NodeType type) { StringBuilder message = new StringBuilder("Invalid type " + node.getType() + ", expected " + type); if (node.getParent() != null && node.getParent() instanceof KeyValueNode) { message.append(" (key: \"" + ((KeyValueNode) node.getParent()).getKey() + "\")"); } return new ErrorNode(message.toString()); }

Target:
Why are we only adding this to this error message only?
Source:
public static File getHadoopTokens(HadoopSecurityManager hadoopSecurityManager, Props props, Logger log) throws HadoopSecurityManagerException { File tokenFile = null; try { tokenFile = File.createTempFile("mr-azkaban", ".token"); } catch (Exception e) { e.printStackTrace(); throw new HadoopSecurityManagerException("Failed to create the token file.", e); } hadoopSecurityManager.prefetchToken(tokenFile, props, log); return tokenFile; }

Target:
printing out stack trace is not needed
Source:
public void tearDown() throws Exception { super.tearDown(); lfuJedis.disconnect(); }

Target:
Reverse order.
Source:
protected AbstractProcessor(final String[] sourceExtensions, final String[] headerExtensions) { this.sourceExtensions = sourceExtensions.clone(); if(headerExtensions != null) { this.headerExtensions = (String[]) headerExtensions.clone(); } else { this.headerExtensions = null; } }

Target:
Rather than changing the contract that all other compilers match, perhaps follow existing pattern and pass `new String[] {}`
Source:
public void init(EmptyAssetsScreen presenter) { this.presenter = presenter; if (!this.presenter.canUpdateProject()) { this.addAsset.disabled = true; } }

Target:
IMO this should move to the presenter in the first place.. i.e. where you call ```view.init( this )``` add the next line that calls ```if(this.canUpdateProject()) { view.enableAddAssetButton( false ); }```
Source:
public static void configureSentry(ApplicationContext context) { FileSettings settings = context.getBean(FileSettings.class); String sentryDsn = ofNullable(settings.getString("sentry.dsn")).orElse("none"); if (!sentryDsn.equals("none")) { Sentry.init(sentryDsn); } }

Target:
можно просто не указывать настройку sentry.dsn либо явно указать протокол noop:// (https://github.com/getsentry/sentry-java/blob/master/sentry/src/main/java/io/sentry/dsn/Dsn.java#L21) — он используется по умолчанию думаю, не стоит поверх этого наворачивать ещё какую-то нашу собственную логику даже без явного вызова Sentry.init сентри все равно будет автоматически инициализировать клиент (и искать dsn в параметрах jvm или энв-переменных), поэтому доп. логика с none может привести к странному поведению
Source:
public RequestMatcher value(String parameter, String... expectedValues) { List<Matcher<? super String>> matcherList = Arrays.stream(expectedValues) .map(Matchers::equalTo) .collect(Collectors.toList()); return this.value(parameter, matcherList); }

Target:
We don't use `this" for methods.
Source:
private ObjCClass(long handle, Class<? extends ObjCObject> type, String name, boolean custom) { super(handle, false); this.type = type; this.name = name; this.custom = custom; if (custom) { ObjCObject.ObjectOwnershipHelper.registerClass(this); } }

Target:
I think it would be better to have this call at the end of the `ObjCClass.register()` method. Just after the `ObjCClass` instance is created.
Source:
private static boolean inSameSubtree(long bitsA, long bitsB, int level) { return (bitsA >>> level) == (bitsB >>> level) || level == MAX_BITS; }

Target:
why flip the `||`?
Source:
private ReplicationFactor(int allReplicas, int transientReplicas) { this.allReplicas = allReplicas; this.fullReplicas = allReplicas - transientReplicas; }

Target:
nit: `allReplicas` and `totalReplicas` names are used for the same thing, maybe we should normalize it?
Source:
protected static void assertAttAuthzStatements(final Assertion assertion) throws WSSecurityException { if (CollectionUtils.isEmpty(assertion.getAttributeStatements()) && (assertion.getAuthnStatements() == null || assertion.getAuthnStatements().isEmpty())) { assertAuthzDecisionStatements(assertion); } }

Target:
consider to use CollectionUtils
Source:
private void newTestSubject(int cachedEvents, long fetchDelay, long cleanupDelay) { Optional.ofNullable(testSubject).ifPresent(EmbeddedEventStore::shutDown); testSubject = new EmbeddedEventStore(storageEngine, NoOpMessageMonitor.INSTANCE, cachedEvents, fetchDelay, cleanupDelay, MILLISECONDS, SnapshotResolver.lastSnapshotResolver()); }

Target:
This stuff would benefit..from a Builder maybe, with defaults in it. What do you think? ;p
Source:
private MavenProject getSiblingModule(Artifact artifact) { @SuppressWarnings("unchecked") List<MavenProject> modules = (List<MavenProject>)project.getParent().getModules(); for (MavenProject module : modules) { if (module.getId().equals(artifact.getId())) { return module; } } return null; }

Target:
can project.getParent() be null?
Source:
private ASTArgumentList getArgumentList(ASTArguments args) { if (args != null) { super.visit(args, null); return args.getFirstChildOfType(ASTArgumentList.class); } return null; }

Target:
it doesn't seem right to do this here.... why a getter triggers node visitation? Aren't we visiting twice these nodes by doing this?
Source:
public Object getNextValue() { double value = (double) getValue(); double stepSize = MAX_VALUE; while (stepSize >= MIN_VALUE) { if (value >= stepSize) { break; } else { stepSize = stepSize / 10; } } if( value >= MAX_VALUE) { return 0; } return value + stepSize; }

Target:
This should probably be `return MAX_VALUE`, to prevent cycling the step size back to zero. And below should be `return MIN_VALUE`
Source:
protected Object computeParameterValue(JpaParameter parameter, Object value, Object[] values) { return value; }

Target:
I don't think we need that if we drop the support for expression parameters as repository method parameters, right?
Source:
public AbstractRepositoryRestController(PagedResourcesAssembler<Object> assembler, PersistentEntityResourceAssembler<Object> entityResourceAssembler) { System.out.println("Registering " + this.getClass() + " controller..."); this.assembler = assembler; this.perAssembler = entityResourceAssembler; }

Target:
Remove that on before merging.
Source:
private Optional<Map<String, VariableDefinition>> getVariableDefinitionMap(String processDefinitionId) { ProcessExtensionModel processExtensionModel = processDefinitionId != null ? processExtensionService.getExtensionsForId(processDefinitionId) : null; return Optional.ofNullable(processExtensionModel) .map(p -> p.getExtensionsByProcessDefinitionId(processDefinitionId)) .map(Extension::getProperties); }

Target:
I thought we did not have the processDefinitionId in the extensions json I thought we had only the process definition key in the extensions json And that's why yesterday in this class we tried to look up by key(and not by id like in the past) What am i missing?
Source:
protected void checkStarted() throws StoreException { if (!started) { throw new StoreException("Store not started", StoreErrorCodes.Store_Not_Started); } }

Target:
is this necessary?
Source:
public void close() throws SQLException { if (hpccConnection != null) { hpccConnection.close(); hpccConnection = null; } if (result != null) { result.close(); result = null; } sqlQuery = ""; dbMetadata = null; closed = true; parameters = null; parser = null; eclQuery = null; }

Target:
Should you be closing the connection as well? What happens if the caller attempts to execute query after closing the prepstmt
Source:
public String getExpression() { // The escaped CSS content has to be escaped to be a valid Java literal return "\"" + Generator.escape(toCss()) + "\""; }

Target:
toCss() already escape the String, no need to escape it again.
Source:
public List<? extends Module> getJacksonModules() { return Arrays.<Module>asList( new SimpleModule("FirehoseModule") .registerSubtypes( new NamedType(ClippedFirehoseFactory.class, "clipped"), new NamedType(TimedShutoffFirehoseFactory.class, "timed"), new NamedType(IrcFirehoseFactory.class, "irc"), new NamedType(LocalFirehoseFactory.class, "local"), new NamedType(ProtoBufInputRowParser.class, "protobuf"), new NamedType(EventReceiverFirehoseFactory.class, "receiver") ) ); }

Target:
there is another class named IndexingServiceFirehoseModule, wondering if we can just delete that class and use FireshoseModule in indexing service also.
Source:
protected void handleDemandLoadException(Resource resource, IOException exception) { try { super.handleDemandLoadException(resource, exception); // CHECKSTYLE:OFF } catch (Exception e) { // CHECKSTYLE:ON // do nothing. The errors are added to the Resource#getErrors() in super(). } }

Target:
Same question here
Source:
public final Type getType() { if (beginA == endA && beginB < endB) return Type.INSERT; if (beginA < endA && beginB == endB) return Type.DELETE; if (isEmpty()) return Type.EMPTY; return Type.REPLACE; }

Target:
Surprising to me you suggest this. I guess you spent this method call because you know for sure the call comes for free because of inlining. Right?
Source:
private String getHumanReadableSize(long bytes) { int unit = 1000; if (bytes < unit) return bytes + " B"; int exp = (int) (Math.log(bytes) / Math.log(unit)); String pre = "" + "KMGTPE".charAt(exp - 1); return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre); }

Target:
Cosmetic: Please, always use braces around conditions and loops. Thanks! :)
Source:
private KieBuilderImpl kieBuilderClone( final KieFileSystem kieFileSystemClone ) { KieBuilderImpl kieBuilder = null; if ( this.kieBuilder != null ) { kieBuilder = (KieBuilderImpl) createKieBuilder( kieFileSystemClone ); kieBuilder.setkModule( ( (KieBuilderImpl) this.kieBuilder ).getkModule() ); kieBuilder.setTrgMfs( ( (KieFileSystemImpl) kieFileSystemClone ).getMfs() ); } return kieBuilder; }

Target:
It is OK to make the `createKieBuilder` return KieBuilderImpl. Less likely to break in the future in case we support more implementations.
Source:
public void setUp() throws MalformedURLException { base = new URL("http://localhost:" + port); }

Target:
Generally, it's a good idea to have `throws Exception` rather than a more specific one in the signature of test methods.
Source:
public ProcessInstance getProcessInstance(String instanceId) throws WorkflowException { ProcessInstanceImpl instance = repository.getById(instanceId); return instance; }

Target:
![MINOR](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/severity-minor.png 'Severity: MINOR') Immediately return this expression instead of assigning it to the temporary variable "instance". [![rule](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/rule.png)](http://integration.silverpeas.org/sonar/coding_rules#rule_key=squid%3AS1488)
Source:
protected int[] makeDimValSelector(PooledTopNParams params, int numProcessed, int numToProcess) { final TopNMetricSpecBuilder<int[]> arrayProvider = params.getArrayProvider(); if (query.getDimensionSpec().preservesOrdering()) { return arrayProvider.build(); } arrayProvider.ignoreFirstN(numProcessed); arrayProvider.keepOnlyN(numToProcess); return query.getTopNMetricSpec().configureOptimizer(arrayProvider).build(); }

Target:
same, needs to be negated
Source:
protected void bindWidgetToSetting(UIWidget widget) { UISlider slider = widget.find("slider", UISlider.class); assert slider != null; updateSliderIfInteger(slider); setSliderRange(slider); slider.bindValue(new Binding<Float>() { @Override public Float get() { return getSetting().getValue().floatValue(); } @Override public void set(Float value) { setSettingValue(value); } }); }

Target:
Don't need to have this in a separate function if it's just a oneliner, IMO.
Source:
public static void sendResponse(ChannelHandlerContext channel, HttpRequest request, String messageBody, HttpResponseStatus status) { sendResponse(channel, request, messageBody, null); }

Target:
NIT: spacing (need new line). But wait and see if there's other changes you'll need to make from the other reviewers.
Source:
public void clearSwapDir() throws IOException { if (! m_blockPathMap.isEmpty()) { throw new IllegalStateException("Attempt to clear swap directory when " + "there are still managed blocks; use releaseAllBlocks() instead"); } try (DirectoryStream<Path> dirStream = Files.newDirectoryStream(m_largeQuerySwapPath)) { Iterator<Path> it = dirStream.iterator(); while (it.hasNext()) { Path path = it.next(); VoltFile.recursivelyDelete(path.toFile()); } } }

Target:
If its needed to be cleared in init --force please do cleanup there too.
Source:
public void authenticateWithWrongAuthentication() throws SecurityException, SecurityProviderNotFoundException { when(provider.authenticate(authentication)).thenThrow(UnauthorisedException.class); manager.addProvider(provider); expected.expect(UnauthorisedException.class); manager.authenticate(authentication); verify(provider).authenticate(authentication); }

Target:
wrap this in a `try`...
Source:
public ArrayList<CapraOfficeObject> getSelection() { return this.selection; }

Target:
Should return the interface (List), not the class.
Source:
private static ArrayList<Artifact> asArtifacts(Collection<Change> changes) { ArrayList<Artifact> arts = new ArrayList<>(); for (Change artifactChange : changes) { Artifact changeArtifact = artifactChange.getChangeArtifact(); if (changeArtifact.isValid()) { arts.add(artifactChange.getChangeArtifact()); } } return arts; }

Target:
use local variable "changeArtifact" here
Source:
private LanguageMapping computeInheritedMapping(IProject project, IFile file, ICConfigurationDescription configuration) throws CoreException { LanguageMapping mappings[] = LanguageMappingResolver.computeLanguage(project, file.getProjectRelativePath().toPortableString(), configuration, fContentType.getId(), true); LanguageMapping inheritedMapping = mappings[0]; // Skip over the file mapping because we want to know what mapping the file // mapping overrides. int index = 1; while (inheritedMapping.inheritedFrom == LanguageMappingResolver.FILE_MAPPING) { inheritedMapping = mappings[index++]; } return inheritedMapping; }

Target:
Where is the index guard? Would be much cleaner if you do standard for loop for (int i=0; i<mappinsg.length;i++) { if (mappings[i].inheritedFrom!=LanguageMappingResolver.FILE_MAPPING) return mappinsg[i]; } // not sure what we do here
Source:
public static DBI create(ConnectionFactory connectionFactory) { DBI dbi = new DBI(connectionFactory); dbi.installPlugins(); return dbi; }

Target:
This is the only thing I object to. I'm not a fan of Spring-style magic--by which I mean stuff just happens because a JAR is on the classpath (or sometime next year, in the Java 9 module graph). JDBI has thus far done a great job of keeping the magic "visible." I would rather force users to make a single call to `DBI.installPlugins()` so that the ServiceLoader stuff is truly opt-in.
Source:
public TransactionTemplate retries( int retries ) { if ( retries < 1 ) { throw new IllegalArgumentException( "Number of retries must be greater than or equal to 1" ); } return new TransactionTemplate( gds, monitor, retries, backoff, retryPredicate ); }

Target:
Oh, so the number of retries actually includes the first try as well.
Source:
public String toString() { return "InternalSinkRecord{" + "consumerRecord=" + originalRecord.toString() + "} " + super.toString(); }

Target:
Hmm, let's just have this delegate to the super method. It's internal, so we need not include the original record details. ```suggestion return super.toString(); ```
Source:
public ZKConfig(File configFile) throws ConfigException { init(); addConfiguration(configFile); }

Target:
Instead of calling `init` explicitly here, you could just call `this()` to call the default constructor `ZKConfig`.
Source:
public String getServerVersion() throws SecurityException, TransactionException, TException { return Version.getVersion(ConcourseServer.class).toString(); }

Target:
why does this need to declare that it throws these exceptions, now?
Source:
public void registerCache(String name) { CacheDescriptor defaultDescriptor = getCacheDescriptor(DEFAULT_CACHE_ID); if (defaultDescriptor == null) { defaultDescriptor = new CacheDescriptor(); defaultDescriptor.options.put(CacheDescriptor.OPTION_MAX_SIZE, String.valueOf(CacheDescriptor.DEFAULT_MAX_SIZE)); register(XP_CACHES, defaultDescriptor); } CacheDescriptor newDescriptor = (CacheDescriptor) new CacheDescriptor().merge(defaultDescriptor); newDescriptor.name = name; // add to registry (merging if needed) register(XP_CACHES, newDescriptor); // start if needed maybeStart(name); }

Target:
Don't forget to re-add default TTL here probably.
Source:
private Consumer<Future<String>> assertAllLocksAcquiredCorrectly() { return result -> { try { String assertionError = result.get( SECONDS_TO_RUN * 100, TimeUnit.SECONDS ); if ( assertionError != null ) { fail( assertionError ); } } catch ( InterruptedException | ExecutionException | TimeoutException e ) { throw Exceptions.launderedException( e ); } }; }

Target:
`Exceptions.launderedException` is being removed, so avoid calling it here. Just wrap and throw `RuntimeException`.
Source:
private void storeCredentials(AddRemotePage remotePage) { if (remotePage.getStoreInSecureStore()) { URIish uri = remotePage.getSelection().getURI(); if (uri != null) SecureStoreUtils.storeCredentials(remotePage.getCredentials(), uri); } }

Target:
style nit: missing braces
Source:
public Indexer(Config config, Deduper deduper) { this.config = config; this.deduper = deduper; this.localDatabase = new SqlDatabase(config); try { localDatabase.getConnection().setReadOnly(true); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } this.eventBus = LocalEventBus.getInstance(); }

Target:
try/catch block in a constructor with `e.printStackTrace()`? Shouldn't this be something like `SqlDatabase.createReadOnly(config);` or something?
Source:
void setLocalPartitionCount(int partitionCount) { // this method should be invoked before participation, so the initial value is expected to be 0. if (!offlineCount.compareAndSet(0, partitionCount)) { logger.warn("Number of OFFLINE partitions has changed before initializing participant metrics"); } }

Target:
Should this throw IllegalStateException? Seems like bug case.
Source:
private void log(ITestNGMethod method, String prefix) { if (method.getInstance() != null) { messages.add(prefix + method.getInstance().getClass().getName() + "." + method.getMethodName()); } else { messages.add(prefix + method.getMethodName()); } }

Target:
could be static
Source:
public Void visitAggregation(AggregationNode node, ImmutableList.Builder<Expression> context) { node.getAggregations().values() .forEach(aggregation -> context.add(aggregation.getCall())); node.getGroupingSets().forEach(groupingSet -> groupingSet .forEach(symbol -> context.add(symbol.toSymbolReference()))); return super.visitAggregation(node, context); }

Target:
It is wrong. Symbols are not expressions.
Source:
public SslConnection accept(StreamConnection tcpConnection, SSLEngine engine) { SslConnection connection = new JsseSslStreamConnection(tcpConnection, engine, socketBufferPool, applicationBufferPool, startTls); if(sslEngineCallback != null) { sslEngineCallback.acceptCallback(connection, engine); } return connection; }

Target:
What is the purpose of this mechanism?
Source:
private static String remoteUrl(final Context context) { String customURL = context.get(Download.INSTANCE); if(customURL != null && !customURL.isEmpty()) { return context.get(Download.INSTANCE); } else { return DEFAULT_REMOTE_URL; } }

Target:
Let's try sticking to the current style add final and use it as return value
Source:
private void mapLinesToOffsets() throws IOException { try (Scanner scanner = new Scanner(Paths.get(filePath))) { int currentGlobalOffset = 0; while (scanner.hasNextLine()) { lineToOffset.add(currentGlobalOffset); currentGlobalOffset += getLineLengthWithLineSeparator(scanner); } } }

Target:
why not have `filePath` be a `Path` directly?
Source:
public boolean handlesEvent(CellPreviewEvent<EntityModel> event) { NativeEvent nativeEvent = event.getNativeEvent(); if (!BrowserEvents.CLICK.equals(nativeEvent.getType())) { return false; } return true; }

Target:
this can be simply "return BrowserEvents.CLICK.equals( event.getNativeEvent().getType())"
Source:
public Optional<Iterable<String>> getFlags(String field) { Optional<String> value = delegate.getValue(SECTION_NAME, field); return value.map(input -> Splitter.on(" ").split(input.trim())); }

Target:
We should mark this as `private`.
Source:
private void storeNetwork() throws UnsupportedEncodingException { if (sourceProtocol.equals(NetConfigSourceProtocol.OPENSTACK_METADATA)) { networkData = new VmInitToOpenStackMetadata(vmInit).asMap(); } else { storeNetworkAsEni(); } }

Target:
we typically compare enum values using '==' instead of 'equals'
Source:
public Object execute(ExecutionEvent aEvent) throws ExecutionException { GerritTableView reviewTableView = GerritTableView.getActiveView(); // see http://gerrit-documentation.googlecode.com/svn/Documentation/2.5.2/user-search.html //for All > AbandonedOpen--> status:abandoned GerritUi.Ftracer.traceInfo(NLS.bind(Messages.AllReviewsHandler_executeCommand, GerritQuery.QUERY_ALL_ABANDONED_CHANGES)); reviewTableView.processCommands(GerritQuery.QUERY_ALL_ABANDONED_CHANGES); return null; }

Target:
Strings that aren't being displayed to users should not be internationalized.
Source:
protected boolean canDoAction() { setGlusterVolumeId(getParameters().getVolumeId() == null ? getGeoRepSession().getMasterVolumeId() : getParameters().getVolumeId()); if (!super.canDoAction()) { return false; } if (getGeoRepSession().getStatus().equals(GeoRepSessionStatus.ACTIVE)) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_GEOREP_SESSION_ALREADY_STARTED); } return true; }

Target:
I think this change does not belong in this patch
Source:
public boolean isValid(Object[] array, ConstraintValidatorContext constraintValidatorContext) { if ( array == null ) { return false; } return Array.getLength( array ) > 0; }

Target:
Interesting, what's the rationale for not using array.length?
Source:
public String getDescription() { return null; }

Target:
This needs to be implemented?
Source:
private static HttpScheme connectionScheme(ChannelHandlerContext ctx) { final HttpScheme scheme = connectionSchemeAttribute(ctx).get(); return (scheme == null) ? HttpScheme.HTTP : scheme; }

Target:
nit: you can remove the `()`
Source:
public String getDescription() { if (description == null || description.isEmpty()) { } return description; }

Target:
set your feature as transient
Source:
public String getTitle() { return this.id; }

Target:
`this.id` -> `id`
Source:
private void buildIndex() { int i = 0; index.clear(); Entry q = head; while (q != null) { if (++i % 100 == 0) { index.add(q); } q = q.next; } }

Target:
style nit: we don't use braces around single line blocks
Source:
private URL deploymentOne() throws Throwable { System.out.println("deployment"); return new URL("http://blah.com"); }

Target:
Remove this
Source:
public static void initialize(Props props) { if (props == null) { throw new NullPointerException("props argument can't be null"); } instance = new JobCallbackRequestMaker(props); isInitialized = true; logger.info("Initialization for " + JobCallbackRequestMaker.class.getName() + " is completed"); }

Target:
return right away if initialized already?
Source:
void cancel() { if (callback != null) { callback = null; } ImageView target = this.target.get(); if (target == null) { return; } ViewTreeObserver vto = target.getViewTreeObserver(); if (!vto.isAlive()) { return; } vto.removeOnPreDrawListener(this); }

Target:
This check can be dropped.
Source:
protected Map<K, V> copy(Map<K, V> source, Map dest) { for (Entry<K, V> entry : source.entrySet()) { K key = entry.getKey(); K altKey; if (key instanceof String) { altKey = (K) new CaseInsensitiveString((String) key); } else { altKey = key; } dest.put(altKey, entry.getValue()); } return dest; }

Target:
I think we could get rid of the `altKey` variable and the corresponding else block as well.
Source:
protected void limitTotalNumberOfCnxns() throws IOException { if (maxCnxns <= 0) { // maxCnxns limit is disabled return; } int cnxns = getNumAliveConnections(); if (cnxns >= maxCnxns) { throw new IOException("Too many connections " + cnxns + " - max is " + maxCnxns); } }

Target:
A graceful shutdown would be nice. See the use of `ServerMetrics.getMetrics().CONNECTION_REJECTED` in the code base. Alternately, could reuse the `ClientCnxnLimitException` exception.
Source:
public static TLSClientParametersFactory getInstance() { if (tlsCPFactory == null) { tlsCPFactory = new TLSClientParametersFactory(); } return tlsCPFactory; }

Target:
Consider using a Singleton pattern here. For an example within the CONNECT codebase, see X12EntityExceptionBuilder.java.
Source:
public static XmlForm parse(String xml, boolean strict) throws IOException { ObjectMapper objectMapper = new XmlMapper(); if (!strict) { objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); //For production, ignore unknown stuff } XmlForm form = objectMapper.readValue(xml, XmlForm.class); System.out.println(form); //Debug only return form; }

Target:
Maybe incorportate it into debug logging instead? `log.fine`?