auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected <T extends Connection> void parseConnectionList(EClass conType, EList<T> connectionlist, String parentNodeName) throws XMLStreamException, TypeImportException { processChildren(parentNodeName, name -> { if (name.equals(LibraryElementTags.CONNECTION_ELEMENT)) { T connection = parseConnection(conType); if (null != connection) { connectionlist.add(connection); } proceedToEndElementNamed(LibraryElementTags.CONNECTION_ELEMENT); return true; } return false; }); }

Target:
call on constant
Source:
private void parseServiceSequence(final FBType type) throws TypeImportException, XMLStreamException { ServiceSequence serviceSequence = LibraryElementFactory.eINSTANCE.createServiceSequence(); readNameCommentAttributes(serviceSequence); processChildren(LibraryElementTags.SERVICE_SEQUENCE_ELEMENT, name -> { if (name.equals(LibraryElementTags.SERVICE_TRANSACTION_ELEMENT)) { parseServiceTransaction(serviceSequence, type); return true; } return false; }); type.getService().getServiceSequence().add(serviceSequence); }

Target:
call equals on constant
Source:
private void parseST(final STAlgorithm st) throws TypeImportException, XMLStreamException { String text = getAttributeValue(LibraryElementTags.TEXT_ATTRIBUTE); if (text != null) { st.setText(text); } else { throw new TypeImportException(Messages.FBTImporter_ST_TEXTNOTSET_EXCEPTION); } proceedToEndElementNamed(LibraryElementTags.ST_ELEMENT); }

Target:
order of operands
Source:
private void parseInternalVars(final BaseFBType type) throws TypeImportException, XMLStreamException { processChildren(LibraryElementTags.INTERNAL_VARS_ELEMENT, name -> { if (name.equals(LibraryElementTags.VAR_DECLARATION_ELEMENT)) { VarDeclaration v = parseVarDeclaration(); type.getInternalVars().add(v); return true; } return false; }); }

Target:
call equals on constant
Source:
private void parseSegmentNodeChildren(Segment segment) throws XMLStreamException, TypeImportException { processChildren(LibraryElementTags.SEGMENT_ELEMENT, name -> { if (name.equals(LibraryElementTags.ATTRIBUTE_ELEMENT)) { if (isColorAttributeNode()) { parseColor(segment); } else { parseGenericAttributeNode(segment); } proceedToEndElementNamed(LibraryElementTags.ATTRIBUTE_ELEMENT); return true; } return false; }); }

Target:
call equals on constant
Source:
public DeferredItem(Rectangle bounds, RGBAColor backgroundColor, RGBAColor foregroundColor, int alpha, int lineWidth) { fBounds = bounds; fLineWidth = lineWidth; if (backgroundColor == null) { fBgColor = OPAQUE; } else if (backgroundColor.getAlpha() != alpha) { fBgColor = new RGBAColor(backgroundColor.getRed(), backgroundColor.getGreen(), backgroundColor.getBlue(), alpha); } else { fBgColor = backgroundColor; } fFgColor = foregroundColor; }

Target:
When filtering is applied, the received RGBAColor has a lower alpha.
Source:
protected void drawBorder(GC gc) { Rectangle bounds = getBounds(); gc.drawRoundRectangle(bounds.x-1, bounds.y-1, bounds.width+2, bounds.height+2, fArc, fArc); }

Target:
Original code does not have these increased bounds? also, spaces
Source:
public void skipTree() { if (currVisit != null) currVisit.ptr = currVisit.buf.length; }

Target:
Please add
Source:
public XYAxis(org.eclipse.swtchart.IAxis axis) { fAxis = axis; }

Target:
not needed. Is there a way to decouple even more so that we don't need to pass the o.e.swtchart class? Adapter, resolver, consumer, not sure exactly how.
Source:
public FBNetworkContextMenuProvider(final DiagramEditorWithFlyoutPalette editor, final ActionRegistry registry, final ZoomManager zoomManager, Palette palette) { super(editor.getViewer(), zoomManager, registry); this.palette = palette; this.editor = editor; editor.getViewer().getControl().addMenuDetectListener(new MenuDetectListener() { @Override public void menuDetected(MenuDetectEvent e) { pt = getViewer().getControl().toControl(e.x, e.y); } }); }

Target:
why did you remove the lambda
Source:
public void setActiveEditor(IEditorPart editor) { ActionRegistry registry = editor.getAdapter(ActionRegistry.class); IActionBars bars = getActionBars(); for (String id : globalActionKeys) { setGlobalActionHandler(registry, bars, id); } super.setActiveEditor(editor); }

Target:
these two should also go into the setGlobalActionHandler method.
Source:
protected void getDataRightsOverride() { overrideClassification = DataRightsClassification.noOverride; for (DataRightsClassification classification : DataRightsClassification.values()) { if (classification.getDataRightsClassification().equals(publishingOptions.overrideDataRights)) { overrideClassification = classification; } } }

Target:
can you "break;" out of this for loop?
Source:
private IWorkingSetUpdater2 getUpdater() { WorkingSetDescriptor descriptor = getDescriptor(); WorkingSetManager manager = getWorkingSetManager(); if (manager != null && descriptor != null) { IWorkingSetUpdater updater = manager.getUpdater(descriptor); if (updater instanceof IWorkingSetUpdater2) { return (IWorkingSetUpdater2) updater; } } return null; }

Target:
in adaptElements this is only done if manager != null, so maybe this should be also moved inside if(manger != null) here
Source:
public void commitOutput() throws IOException { try (OutputStream os = response.getOutputStream()) { try (InputStream is = getInputStream()) { if (is != null) { Utils.transferContent(is, os); } os.flush(); } } }

Target:
In the original version, both "in" and "out" were not closed at the end. Why do we close them now?
Source:
switch (platform) { case "win32": //$NON-NLS-1$ COLUMN_TRIM= 4; break; case "carbon": //$NON-NLS-1$ COLUMN_TRIM= 24; break; case "cocoa": //$NON-NLS-1$ default: COLUMN_TRIM= 3; break; }

Target:
either handle cocoa like carbon or remove carbon on the fly maybe change "carbon" to "cocoa" by separate change before? carbon is unsupported.
Source:
public boolean isConstexpr() { ICPPASTDeclSpecifier declSpec = getDeclSpecifier(); if (declSpec == null) { ICPPASTFunctionDeclarator dtor = getPreferredDtor(); return dtor != null ? dtor.isConstexpr() : false; } return declSpec.isConstexpr(); }

Target:
Is this ever actually reached? It seems to me we only have a lambda declarator associated with CPPImplicitFunctions, and CPPImplicitFunction overrides isConstexpr().
Source:
int getLineHeight(int lineIndex) { LineSizeInfo line = getLineSize(lineIndex); if (line.needsRecalculateHeight()) { // here we are in "variable line height", the call of calculate which uses TextLayout is very slow // so use the average line height of all calculated lines. This should be good enough for scrolling. if (isVariableHeight(lineIndex)) { return Math.round(averageLineHeight); } else { line.height = getLineHeight() + getLineSpacing(lineIndex); } } return line.height; }

Target:
If we do that, then this method doesn't return the actual line height any more, but an estimation. That's IMO not something we want to do as this method is expected to return correct value in multiple places. If you want to deal with average height, please introduce a new method and make it used when it's suitable.
Source:
public FileDiff(final Repository repo, final RevCommit c, final DiffEntry entry) { repository = repo; diffEntry = entry; commit = c; base = null; }

Target:
Delegate to the new Constructor?
Source:
public static void migrateOsgiLaunchConfiguration(ILaunchConfigurationWorkingCopy configuration) throws CoreException { ILaunchConfigurationWorkingCopy wc = getWorkingCopy(configuration); convertToSet(wc, IPDELauncherConstants.WORKSPACE_BUNDLES, IPDELauncherConstants.SELECTED_WORKSPACE_BUNDLES); convertToSet(wc, IPDELauncherConstants.TARGET_BUNDLES, IPDELauncherConstants.SELECTED_TARGET_BUNDLES); convertToSet(wc, IPDELauncherConstants.DESELECTED_WORKSPACE_PLUGINS, IPDELauncherConstants.DESELECTED_WORKSPACE_BUNDLES); }

Target:
seems unnecessary
Source:
protected void activateDefaultView(String deepLinkPath) { boolean isStartup = m_attachedCount <= 1; if (safeHandleDeepLink(deepLinkPath)) { // NOP } else if (isStartup) { interceptDefaultView(); } }

Target:
Would rearranging this method make it more readable? if (safeHandleDeepLink(deepLinkPath)) { return; } if (m_attachedCount <= 1) { // startup interceptDefaultView(); }
Source:
public Object getParent(Object element) { if (element instanceof FileDiffRegion || element instanceof Folder) { return parents.get(element); } return null; }

Target:
Is this still needed? We don't add any other elements, so parent.get(anythingElse) should return null anyway.
Source:
private Folder computeRootFolder(String path) { return rootFolders.computeIfAbsent(path, key -> { Folder newFolder = new Folder(key); return newFolder; }); }

Target:
This could be replaced by Folder::new.
Source:
public static synchronized void logWarning(String message,Throwable ex) { if (IntroPlugin.getDefault().isDebugging() && LOG_WARN) { getDefault().getLog().warn(message, ex); } }

Target:
LOG_WARN should be the first argument
Source:
public static synchronized void logDebug(String message) { if (IntroPlugin.getDefault().isDebugging() && LOG_INFO) { getDefault().getLog().info(message); } }

Target:
LOG_INFO should be the first argument
Source:
public FilteredCheckboxTree(Composite parent, int treeStyle, PatternFilter filter, boolean useNewLook) { super(parent, treeStyle, filter, useNewLook); }

Target:
In this case, I think we should deprecate this constructor and add the fastLookup boolean
Source:
private FilterCache() { // Load in the background. Use a daemon thread since this instantiation // may occur very early; the JobManager may perhaps even be still // suspended. loader = new Thread(this::loadFromPreferences); loader.setDaemon(true); loader.start(); }

Target:
Is the background loading the only reason, why the loading is done in the constructor (and via a separate thread)? I would have thought that compared to loading the content for the view, getting these few entries should not be too expensive. Did you measure how much time would be lost for this one-time initialization?
Source:
public void set(FilterableNode node, String filter) { try { loader.join(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; } cache.computeIfAbsent(node.getRepository().getDirectory(), k -> new ConcurrentHashMap<>()).put(node.getType(), filter); node.setFilter(filter); }

Target:
If not done in the background, these four join-calls could be replaced by simple ensureCacheInitialized() calls.
Source:
private ISeries createSeries() { IBarSeries series = (IBarSeries) fChart.getSeriesSet().createSeries(SeriesType.BAR, Messages.AbstractSegmentStoreDensityViewer_SeriesLabel); series.setVisible(true); series.setBarPadding(0); Color color = getColorForRGB(BAR_COLOR); series.setBarColor(color); return series; }

Target:
inline the call?
Source:
public boolean visit(MethodDeclaration node) { Block body= node.getBody(); if (body == null) return false; Selection selection= getSelection(); int nodeStart= body.getStartPosition(); int nodeExclusiveEnd= nodeStart + body.getLength(); // if selection node inside of the method body ignore method if (((nodeStart >= selection.getOffset()) || (selection.getExclusiveEnd() >= nodeExclusiveEnd))) return false; return super.visit(node); }

Target:
In this case readability is improved imho - in many other case it it not so clear.
Source:
private void updateLabels() { if ((null != transition) && (null != transition.getComment()) && !transition.getComment().isEmpty()) { tooltipContent.setText(transition.getComment()); } tooltipContent.setText("[not set]"); revalidate(); repaint(); }

Target:
according to the model of GEF transition should not get null. Because the Editpart is created for a non null transition and that editpart creates the figure -> tooltip figure
Source:
protected Command getDeleteCommand(final GroupRequest request) { if (getHost() instanceof Link) { return new DeleteLinkCommand((Link) getHost().getModel()); } return null; }

Target:
why is this not a getHost().getModel() unlike the other edits?
Source:
private static AdvancedInformation executeAut(AutLaunch launch) { AdvancedInformation info = null; try { // try to obtain advanced error information from AUT final GetAdvancedInfo advInfoCmd = TeslaFactory.eINSTANCE .createGetAdvancedInfo(); final Object obj = launch.execute(advInfoCmd); if (obj instanceof AdvancedInformation) info = (AdvancedInformation) obj; } catch (Exception e) { return (AdvancedInformation) RcpttPlugin.createStatus(e); } return info; }

Target:
ClassCastException
Source:
private static void write(String content, File file, Charset charset) throws IOException { Writer writer = new OutputStreamWriter(new FileOutputStream(file), charset); writer.write(content); writer.close(); }

Target:
You can use a try resource here try (Writer writer = new OutputStreamWriter(new FileOutputStream(file), charset);) { writer.write(content); }
Source:
private Change getChange(RenameResourceWizard refactoringWizard) { refactoringWizard.setChangeCreationCancelable(true); refactoringWizard.setInitialComputationContext(new IRunnableContext() { @Override public void run(boolean fork, boolean cancelable, IRunnableWithProgress runnable) throws InvocationTargetException, InterruptedException { runnable.run(new NullProgressMonitor()); } }); return refactoringWizard.internalCreateChange(InternalAPI.INSTANCE, new CreateChangeOperation(new CheckConditionsOperation(refactoringWizard.getRefactoring(), CheckConditionsOperation.FINAL_CONDITIONS), RefactoringStatus.FATAL), true); }

Target:
haven't tried, but should be possible to write this as lambda from very beginning, before someone starts another "inner class to lambda" mass change?
Source:
public CaseNameRewriter() { this.upperCase = true; }

Target:
The one-argument constructor can just be called here instead: `this(true)`
Source:
private static void cleanCredentialStore() { File dir = new File(BASE_STORE_DIRECTORY); dir.mkdirs(); File file = new File(BASE_STORE_DIRECTORY + "/mycredstore.cs"); file.delete(); }

Target:
Just minor but no need to call `dir.mkdirs()` here. This clean up method just needs to check if the file exists and if so, delete it.
Source:
public void testObtainCertificateChain() throws Exception { server = setupTestObtainCertificate(false); AcmeAccount account = populateAccount(ACCOUNT_3_V2); String domainName = "fjsljghasldfjgkv2.com"; // randomly generated domain name obtainCertificateChain(null, -1, account, domainName); }

Target:
Same here, a new `setupTestObtainCertificate()` method could be added that calls `setupTestObtainCertificate(false)` by default.
Source:
public Set<String> getSupportedExtensions() { return supportedExts; }

Target:
maybe we can simply return 'null' here as `supportedExts` is not set anywhere, so it will be null anyway... as a result that variable does not have to be declared at all?
Source:
public Builder setMaxReconnectAttempts(int maxReconnectAttempts) throws IllegalArgumentException { checkNotNullParam("reconnectAttempts", maxReconnectAttempts); if (maxReconnectAttempts < -1) { throw audit.badReconnectAttemptsNumber(maxReconnectAttempts); } this.maxReconnectAttempts = maxReconnectAttempts; return this; }

Target:
This null check can be removed since ```maxReconnectAttempts``` is an ```int```
Source:
public static void cleanUpLdapFiles() throws Exception { File workingDirLDIF = new File(LDAP_DIRECTORY_LOCATION); if (workingDirLDIF.exists() == false) { workingDirLDIF.mkdirs(); } Files.copy(Paths.get(workingDirLDIF + LDIF_LOCATION + ".bak"), Paths.get(workingDirLDIF + LDIF_LOCATION), StandardCopyOption.REPLACE_EXISTING); }

Target:
If the directory doesn't exist, the .bak file won't exist so this if statement can be removed and replaced with a check to make sure the directory does exist.
Source:
public PublicKey getPublicKey(String kid, URL url) { if (!checkRemote(url)) { return null; } Map<String, RSAPublicKey> urlKeys = keys.get(url); if (urlKeys == null) { return null; } PublicKey pk = urlKeys.get(kid); if (pk == null) { log.warn("Unknown kid: " + kid); return null; } return pk; }

Target:
Looks like this should be in a synchronized block. Perhaps the ```checkRemote``` method could be refactored slightly so it returns the key if found directly and null otherwise.
Source:
public MappedRoleMapper() { this.reverseRoleMap = new LinkedHashMap<>(); this.removeMapped = true; //not keeping any delegate roles as there is no way to avoid configuration conflicts this.removeNonMapped = true; //this functionality is possible to recreate by manually combining role mappers this.keyRoles = Roles.NONE; }

Target:
This should not be on fields as this is custom-role-mapper specific - not related when used as mapped-role-mapper in subsystem.
Source:
public boolean equals(Object other) { if (! (other instanceof MaskedPasswordAlgorithmSpec)) return false; MaskedPasswordAlgorithmSpec otherSpec = (MaskedPasswordAlgorithmSpec) other; return otherSpec == this || Arrays.equals(initialKeyMaterial, otherSpec.initialKeyMaterial) && iterationCount == otherSpec.iterationCount && Arrays.equals(salt, otherSpec.salt) && initializationVector == otherSpec.initializationVector; }

Target:
This should use Arrays.equals()
Source:
public TimberClientHandler(TimberClient client, ClientBootstrap bootstrap) { // Do we need to call super()? Since we extend SimpleChannelUpstreamHandler // it is likely the answer is yes. super(); this.client = client; this.bootstrap = bootstrap; timer = new HashedWheelTimer(); }

Target:
Redundant - super() is always called anyway.
Source:
public void testEquals() throws Exception { assertTrue( new Coordinate(1,"foo", "bar", "baz").equals(new Coordinate(1, "foo", "bar", "baz")) ); }

Target:
There exists an assertEquals().
Source:
private Properties loadStringProperties(String body) { Properties properties = new Properties(); try { properties.load(new StringReader(body)); } catch (IOException e) { e.printStackTrace(); } return properties; }

Target:
Is this intended to return an empty Properties object even if an exception occurs?
Source:
public static String getGroupId(GroupApi groupApi) { for ( GroupState state : groupApi.listGroupStates() ) { Group g = groupApi.get(state.getId()); for ( ScalingPolicyResponse policy : g.getScalingPolicies() ) { if (policy.getName().equals(NAME)) return g.getId(); } } throw new RuntimeException("Group not found"); }

Target:
[minor] IllegalArgException?
Source:
public static String getPolicyId(PolicyApi policyApi) { for ( ScalingPolicyResponse policy : policyApi.list() ) { if (policy.getName().equals(NAME)) return policy.getId(); } throw new RuntimeException("Policy not found"); }

Target:
[minor] IllegalArgException?
Source:
public static void main(String[] args) { UploadDirectoryToCDN uploadDirToCDN = new UploadDirectoryToCDN(); try { uploadDirToCDN.init(args); uploadDirToCDN.uploadDirectory(args[2], args[3]); uploadDirToCDN.enableCdnContainer(args[3]); } catch (Exception e) { e.printStackTrace(); } finally { uploadDirToCDN.close(); } }

Target:
Move this to the `UploadDirectoryToCDN` constructor and make the `storage` and `rackspace` variables `final`?
Source:
public BlobDetail call() throws Exception { Blob blob = storage.blobBuilder(toBeUploadedBlobDetail.getRemoteBlobName()) .payload(toBeUploadedBlobDetail.getLocalFile()) .contentType("") .build(); String eTag = storage.putBlob(container, blob); BlobDetail uploadedBlobDetail = new BlobDetail( toBeUploadedBlobDetail.getRemoteBlobName(), toBeUploadedBlobDetail.getLocalFile(), eTag); return uploadedBlobDetail; }

Target:
Hmm...will this allow all the files to render correctly? Don't we need to preserve content types?
Source:
private void generateFileList(File localDir, String remotePath, List<BlobDetail> blobDetails) { for (File localFile: localDir.listFiles()) { if (localFile.isFile()) { String remoteBlobName = remotePath + localFile.getName(); blobDetails.add(new BlobDetail(remoteBlobName, localFile)); } else { generateFileList(localFile, remotePath + localFile.getName() + "/", blobDetails); } } }

Target:
Bit of a nit, but since you end up using this expression in both branches, pull it up before the `if`?
Source:
public static void main(String[] args) { CreateDatabase createDatabase = new CreateDatabase(); try { createDatabase.init(args); Instance instance = createDatabase.getInstance(); createDatabase.createDatabase(instance); } catch (Exception e) { e.printStackTrace(); } finally { createDatabase.close(); } }

Target:
[style] `} catch {`? And same for `} finally {`? But not a big deal - leave this way if you prefer
Source:
public void setSize(int width, int height) { super.setSize(width, height); validate(); if (isDisplayable()) { scrollView(); loadBackgroundImage(); } }

Target:
Loading background image every time map size changes e.g. on every unfold operation does not look like sensible, does it?
Source:
public void actionPerformed(final ActionEvent e) { final Controller controller = Controller.getCurrentController(); final MapStyle mapStyle = controller.getModeController().getExtension(MapStyle.class); final MapModel model = controller.getMap(); mapStyle.setProperty(model, MapStyle.RESOURCES_BACKGROUND_IMAGE, MapStyle.CLEAR_BACKGROUND_IMAGE); }

Target:
I like that you use an identifier here. However I would expect its value to be equal to null.
Source:
public static String toString(Values vals) { if(vals != null){ String output ="["; for(int i = 0 ; i < vals.size() ; i++){ Object actObj = vals.get(i); output += actObj.toString(); if(i+1 != vals.size()) output += ", "; else output +="]"; } return output; } else return "null"; }

Target:
In this case, put the default in the else part. So you do not need negation.
Source:
private ILaserTarget getTarget() { if (targetPos != null) { return (ILaserTarget) world.getTileEntity(targetPos); } return null; }

Target:
Don't blindly cast -- check if the returned tile entity actually is an ILaserTarget (it might change before you get updated)
Source:
public void update() { smoothedTank.tick(getWorld()); if (tank.getFluidAmount() != fluidAmountPrev) { fluidAmountPrev = tank.getFluidAmount(); comparatorLevel = MathUtil.scaledClamp(tank.getFluidAmount(), tank.getCapacity(), 15); markDirty(); } }

Target:
Perhaps compare with the previous comparator level rather than the previous amount of fluid?
Source:
protected boolean canReplaceBiome(int biomeId) { Biome biome = Biome.getBiomeForId(biomeId); if (biome == null) { if (BCLib.DEV) //don't spam outside of dev, it's way to noisy BCLog.logger.warn("Couldn't find a biome with an ID of " + biomeId); return false; } return BiomeDictionary.getTypes(biome).containsAll(REQUIRED_TYPES); }

Target:
Just removing the log would be fine actually, we don't have any use for it in dev
Source:
protected void drawItemStackAt(ItemStack stack, int x, int y) { RenderHelper.enableGUIStandardItemLighting(); RenderHelper.disableStandardItemLighting(); itemRender.renderItemAndEffectIntoGUI(mc.thePlayer, stack, x, y); itemRender.renderItemOverlayIntoGUI(mc.fontRendererObj, stack, x, y, null); }

Target:
Why do you need to enable and then disable? In theory you can just call disable and then it should work (provided you have no direct GL11 calls anywhere)
Source:
public AxisAlignedBB getRenderBoundingBox() { return box == null ? super.getRenderBoundingBox() : BoundingBoxUtil.makeFrom(getPos(), box); }

Target:
BoundingBoxUtil checks to see if box is null, and if it is it just uses "pos". So you don't need the null check, and can replace this with ``` java public AxisAlignedBB getRenderBoundingBox() { return BoundingBoxUtil.makeFrom(getPos(), box); } ``` and it won't ever throw an NPE.
Source:
protected final void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { drawForegroundLayer(); GlStateManager.translate(-guiLeft, -guiTop, 0); mouse.setMousePosition(mouseX, mouseY); for (IGuiElement element : guiElements) { element.drawForeground(); } tooltips.drawForeground(); GlStateManager.translate(guiLeft, guiTop, 0); }

Target:
Swapping these around breaks all other GUI's.
Source:
public void clear() { for (DimensionProperty p : properties) { if(p!=null) p.clear(); } properties.clear(); }

Target:
Need
Source:
private boolean isQuarriableBlock(int bx, int by, int bz) { Block block = worldObj.getBlock(bx, by, bz); return !BlockUtil.canChangeBlock(block, worldObj, bx, by, bz) || BuildCraftAPI.isSoftBlock(block, worldObj, bx, by, bz) || (block.getBlockHardness(worldObj, bx, by, bz) > MAX_BREAK_HARDNESS); }

Target:
Only I seen in this lines a logical rubbish?
Source:
private void setTarget(int x, int y, int z) { this.targetX = x; this.targetY = y; this.targetZ = z; Block b = worldObj.getBlock(x, y - 1, z); this.nextDigRequiredEnergy = DIG_BASE_REQUIRED_ENERGY + (b.getBlockHardness(null, 0, 0, 0) * DIG_HARDNESS_ENERGY_MULTIPLIER); }

Target:
Terrible idea. Pass in the proper parameters, since you have them.
Source:
public Supplier<ValueType> getPipelined(final Object key, final Pipeline pipeline) { final String redisKey = generateRedisKey(turnObjectIntoKeyType(key)); final Response<String> valAsString; valAsString = pipeline.get(redisKey); pipeline.expire(redisKey, valueTtl); return new ValueSupplier(valAsString); }

Target:
Is there a reason this can't be one line? Genuinely asking
Source:
public List getLoggerNameList() { List<String> copy = new ArrayList<String>(); synchronized (loggers) { copy.addAll(loggers.keySet()); } return copy; }

Target:
Same as above. I think something like ``` java return new ArrayList<String>(loggers.keySet()); ``` is enough
Source:
public Iterable<SubstitutableLogger> getLoggers() { return loggers.values(); }

Target:
Maybe return a copy? ``` java return new ArrayList<SubstitutableLogger>(loggers.values()); ```
Source:
public MapExpressionMethods() { context = new StandardEvaluationContext(); context.addMethodResolver(new PartitionKeyMethodResolver()); context.addPropertyAccessor(new MapPartitionKeyPropertyAccessor()); }

Target:
I think we need to get reference to an evaluation context that already has even other functions/methods registered with it - at least in the XD context as #jsonPath is registered in SI by default now. I could see one wanting to base a directory name based on the value returned by jsonPath. Perhaps there needs to be an overloaded ctor so that in an XD context, we can contribute to the 'standard/shared' evaluation context.
Source:
private void tearDown() { try { processDestroyer.clean(); tmpDir.dispose(); } catch (IOException e) { throw new UncheckedIOException(e); } catch (InterruptedException e) { e.printStackTrace(System.err); } }

Target:
Test methods can more simply just `throws Exception`.
Source:
public static String formatStopDistance(float distance) { int distanceSmoots = (int) (distance * TourUtils.METERS_TO_SMOOTS); float distanceMiles = distance * TourUtils.METERS_TO_MILES; String milesString = String.valueOf(distanceMiles).substring(0, 3); return distanceSmoots + " miles (" + milesString + " smoots) "; }

Target:
I think you have these variables mixed up, should be switched
Source:
public void setMainLoopActionBarTitle(int mainLoopStopNum, int mainLoopStopsSize) { setTitle(getResources().getString(R.string.stop_nav_main_loop) + " " + mainLoopStopNum + " of " + mainLoopStopsSize); }

Target:
You can pass values into a string resource to avoid this. See the "Formatting strings" section of http://developer.android.com/guide/topics/resources/string-resource.html
Source:
public void onLoadFinished(Loader<Cursor> loader, Cursor data) { data.moveToFirst(); route.buildFromCursor(data, DBAdapter.getInstance()); data.close(); stops = route.getStops(); int currentStop = predictionViewPager.getCurrentItem(); stopViewPagerAdapter.updatePredictions(currentStop, stops.get(currentStop).getPredictions()); updateMapItems((ArrayList) route.getVehicles(), false); }

Target:
Don't need to call here either
Source:
public Contact(String start_first_name, String start_last_name, String start_phone_number, String start_second_phone) { if (start_first_name == null){ start_first_name = ""; } if (start_last_name == null){ start_last_name = ""; } if (start_phone_number == null){ start_phone_number = ""; } if (start_second_phone == null){ start_second_phone = ""; } first_name = start_first_name; last_name = start_last_name; phone_number = start_phone_number; second_phone = start_second_phone; }

Target:
I thought we were only going to allow null args for lastName and secondPhone? We shouldn't be able to construct a firstName or phoneNumber with null -- I think we should be throwing a RuntimeException() in those if statements instead of changing it to "".
Source:
public static void reLogin() throws UnknownHostException, ClassNotFoundException, SQLException{ Login login = new Login(); login.setVisible(true); System.out.println("Got HEre"); }

Target:
Why do you make this method chain throw exceptions up the stack when you just bury them in the end? If you never intend to do any handling of these exceptions, can you just handle them inside of the reLogin() method so the calls are cleaner?
Source:
public double get(int i, int j) { ensureIndexesAreInBounds(i, j); return getOrElse(i, j, 0.0); }

Target:
Yeah. I missed the double check in sparse vector. Please, remove that too. This is a performance penalty doing this check two times.
Source:
public double max() { double max = Double.NEGATIVE_INFINITY; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { if (get(i, j) > max) { max = get(i, j); } } } return max; }

Target:
How about do not call get twice. It might be expensive for sparse entries. Like this: ``` java double value = get(i, j); if (value > max) { max = value; } ```
Source:
public void eachNonZeroInColumn(int j, MatrixProcedure procedure) { int k = columnPointers[j], i = k; while (i < columnPointers[j + 1]) { procedure.apply(rowIndices[i], j, values[i]); i++; } }

Target:
So, now it looks correct, but I still don't see the reason of having this `k` variable. For what it is? And I would prefer having a `for` loop like (equivalent to your `while` loop but much clear): ``` java for (int i = columnPointers[j]; i < columnPointers[j + 1]; i++) { procedure.apply(rowIndices[i], j, values[i]); } ```
Source:
public void eachNonZero(VectorProcedure procedure) { for (int i = 0; i < cardinality; i++) { if (Math.abs(values[i])>Vectors.EPS) procedure.apply(indices[i], values[i]); } }

Target:
It is not necessary to check value in compressed vector on zero. It is guaranteed that only non-zero values are store. Which means, that we only need to rename `each` to `eachNonZero` in `CompressedVector` class. Please also make sure that `MatrixMarketStream` uses the proper iteration method. TIP: It should be `eachNonZero`.
Source:
public Vector shuffle(){ return self.shuffle(); }

Target:
Missed space before `{`.
Source:
public void undoQuote() { PostgreSQLDbSupport dbSupport = new PostgreSQLDbSupport(null); assertEquals("abc", dbSupport.unQuote("\"abc\"")); assertEquals("abc", dbSupport.unQuote("abc\"")); assertEquals("abc", dbSupport.unQuote("\"abc")); assertEquals("a\"b\"c", dbSupport.unQuote("a\"b\"c")); assertEquals("a\"b\"c", dbSupport.unQuote("\"a\"b\"c")); }

Target:
Why is this and all other cases from line 34 to 37 necessary?
Source:
public String unQuote(final String quoted) { if (quoted == null || quoted.length() <= 2) { return quoted; } String result = quoted.startsWith("\"") ? quoted.substring(1) : quoted; return result.endsWith("\"") ? result.substring(0, result.length() - 1) : result; }

Target:
Can you make this package-private and add JavaDoc?
Source:
private static <ViewModelType extends ViewModel> Method getInitializeMethod(ViewModelType viewModel) { for (Method method : viewModel.getClass().getDeclaredMethods()) { if(method.isAnnotationPresent(Initialize.class)) { method.setAccessible(true); return method; } } return null; }

Target:
The refactoring looks good.
Source:
private static GoAssignmentStatement getValidAssignmentParent(@Nullable PsiElement element) { return ObjectUtils.nullizeByCondition(PsiTreeUtil.getNonStrictParentOfType(element, GoAssignmentStatement.class), assignment -> assignment == null || !assignment.isValid() || !isAssignmentEqualsSized(assignment)); }

Target:
I think it's better: ``` GoAssignmentStatement assignment = PsiTreeUtil.getNonStrictParentOfType(element, GoAssignmentStatement.class); return assignment != null && assignment.isValid() && isAssignmentEqualsSized(assignment) ? assignment : null; ``` Please, use lambdas if it give some gain in readability
Source:
protected void checkFile(@NotNull GoFile file, @NotNull ProblemsHolder problemsHolder) { super.checkFile(file, problemsHolder); ProgressManager.checkCanceled(); if (!GoTestFinder.isTestFile(file)) return; for (GoImportSpec importSpec : file.getImports()) { if (importSpec.isCImport()) { problemsHolder.registerProblem(importSpec, "Usage of cgo in tests is not supported.", new GoDeleteImportQuickFix()); } } }

Target:
checkCancelled is called for every element via `com.intellij.psi.PsiElementVisitor#visitElement`, so it doesn't make sense to invoke it just after `super.visit*`.
Source:
public void check(@Nullable GoSignature o, @NotNull ProblemsHolder holder) { super.check(o, holder); if (o == null) return; Set<String> names = getParamNames(o); GoResult result = o.getResult(); if (result == null) return; GoParameters parameters = result.getParameters(); if (parameters == null) return; checkParameters(holder, parameters, names); }

Target:
are you sure? looks like o.getParamters will be checked twice and also they will be checked even if `GoDuplicateArgumentInspection` is disabled.
Source:
protected void checkFile(@NotNull GoFile file, @NotNull ProblemsHolder problemsHolder) { super.checkFile(file, problemsHolder); if (!GoTestFinder.isTestFile(file)) return; for (GoImportSpec importSpec : file.getImports()) { if (importSpec.isCImport()) { problemsHolder.registerProblem(importSpec, "Usage of cgo in tests is not supported.", new GoDeleteImportQuickFix()); } } }

Target:
`super.checkFile` does nothing
Source:
public static GoFunctionDeclaration createFunctionDeclarationFromText(@NotNull Project project, @NotNull String name, @NotNull String text, @Nullable String expectedType) { if (expectedType == null) { expectedType = ""; } else { expectedType += " "; } GoFile file = createFileFromText(project, "package a; func " + name + "(" + text + ") " + expectedType + "{\n}"); return ContainerUtil.getFirstItem(file.getFunctions()); }

Target:
use ternary operator
Source:
protected GoVisitor buildGoVisitor(@NotNull final ProblemsHolder holder, @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitDeferStatement(@NotNull GoDeferStatement o) { PsiElement parent = PsiTreeUtil .getParentOfType(o, GoForStatement.class, GoFunctionLit.class, GoFunctionDeclaration.class, GoMethodDeclaration.class, GoFile.class); if (parent instanceof GoForStatement) { holder.registerProblem(o, "Possible resource leak, \"defer\" is called in a for loop.", ProblemHighlightType.WEAK_WARNING); } } }; }

Target:
Why do you need (GoFunctionDeclaration.class, GoMethodDeclaration.class, GoFile.class)? Is this some optimization? If so then I think it isn't needed.
Source:
public String getQuickNavigateInfo(PsiElement element, PsiElement originalElement) { if (element instanceof GoNamedElement) { String result = getSignature(element); if (result != "") { return result; } } return super.getQuickNavigateInfo(element, originalElement); }

Target:
1. do not use != for comparing 2. StringUtil#nullize
Source:
public static boolean isTestPackageName(@Nullable String packageName) { return packageName != null && packageName.length() > GoConstants.TEST_SUFFIX.length() && packageName.endsWith(GoConstants.TEST_SUFFIX); }

Target:
length checking looks redundant
Source:
public FormattingModel createModel(@NotNull PsiElement element, @NotNull CodeStyleSettings settings) { // TODO decide if this is a good thing to do or not. // Given the go docs and the community enforce the rules for tabs // The plugin should try and emulate the gofmt behavior, which replaces spaces with tabs for idents // For more detail see: http://golang.org/doc/effective_go.html#formatting if (settings.getIndentOptions() != null) { settings.getIndentOptions().USE_TAB_CHARACTER = true; settings.getIndentOptions().SMART_TABS = false; } Block block = new GoFormattingBlock(element.getNode(), null, Indent.getNoneIndent(), null, settings, createSpacingBuilder(settings)); return FormattingModelProvider.createFormattingModelForPsiFile(element.getContainingFile(), block, settings); }

Target:
GoLanguageCodeStyleSettingsProvider should be used for setting default values
Source:
public static void broadcast(Set<Team> teams, String msg) { Iterator<Team> it = teams.iterator(); while(it.hasNext()) { sendMsg(it.next(), msg); } }

Target:
einfacher: for(Team t : teams){...
Source:
public void testValidIsNotHonoredValidateValue() { Validator validator = TestUtil.getValidatorUnderTest(); Customer customer = new Customer(); Order order = new Order(); customer.addOrder( order ); Set<ConstraintViolation<Customer>> constraintViolations = validator.validateValue( Customer.class, "orders", Collections.singleton(order) ); assertNumberOfViolations( constraintViolations, 0 ); }

Target:
Given this is testing `validateValue()`, the `customer` instance could be removed altogether.
Source:
public void parallelValueExtractorDefinitionsCausesException() { Validator validator = Validation.byDefaultProvider() .configure() .addValueExtractor( new IWrapper21ValueExtractor0() ) .addValueExtractor( new IWrapper211ValueExtractor0() ) .addValueExtractor( new IWrapper212ValueExtractor0() ) .addValueExtractor( new IWrapper22ValueExtractor0() ) .addValueExtractor( new IWrapper221ValueExtractor0() ) .addValueExtractor( new Wrapper2ValueExtractor1() ) .buildValidatorFactory() .getValidator(); validator.validate( new CascadingEntity2( null ) ); }

Target:
Are all of them needed? Seems like two extractors would be enough to cause this situation?
Source:
public Optional<@NotNull @NotBlank String> returnStringOptional() { return stringOptional; }

Target:
An optional of not null is a bit painful. Use another constraint perhaps? Do we have one test on the payload business btw. (applying it to the wrapper)?
Source:
public void testAllComposingConstraintsMustBeApplicableToAnnotatedType() { validator.validate( new Shoe( 41 ) ); fail( "Shoe defines @NotEmpty on an int. Validation should have failed." ); }

Target:
For the record, there is actually one benefit of the try/catch approach compared to _expectedExceptions_ . Using _expectedExceptions_ makes the test shorter, but also harder to debug for a developer, since I can for example not set a breakpoint in the catch clause to inspect the exception. It is also less explicit. Also the explicit fail() gives additional information.
Source:
public void testOverriddenAttributesMustMatchInType() { validator.validate( new DummyEntityWithZipCode( "foobar" ) ); fail( "Wrong attribute override in composite constraint. An Exception should have been thrown." ); }

Target:
I find the fail w/o the try/catch misleading. IMO it is either try/catch or just _ expectedExceptions _
Source:
protected PopupPresenter() { this(null); }

Target:
Please don't use null here. Just pass "" and make stateKey always concatenate.
Source:
public boolean isType(TileEntity tile, EnumFacing dir) { if (tile instanceof IGridHost && tile.hasCapability(LPStorageMonitorableAccessor.STORAGE_MONITORABLE_ACCESSOR_CAPABILITY, dir)) { IGridNode tempNode = ((IGridHost) tile).getGridNode(AEPartLocation.fromFacing(dir)); //for some reason when AE loads (5 ticks) this is null if (tempNode == null) //should not be a problem because interfaces are still treated like IInvertoryHandler return false; return true; } return false; }

Target:
replace with `return ((IGridHost) tile).getGridNode(AEPartLocation.fromFacing(dir)) != null;`
Source:
public int getSizeInventory() { if (cached == null) { initCache(); } if(cached.size() == 0) return 1; return cached.size(); }

Target:
spacing, code style
Source:
public boolean isType(TileEntity tile, EnumFacing dir) { if(tile instanceof IGridHost && tile.hasCapability(LPStorageMonitorableAccessor.STORAGE_MONITORABLE_ACCESSOR_CAPABILITY, dir)) { return true; } return false; }

Target:
Formatting
Source:
public boolean hasCapability(Capability<?> capability, @Nullable EnumFacing facing) { if (capability == CapabilityEnergy.ENERGY) { return true; } if (capability != null && (capability == MJ_CONN || capability == MJ_RECV)) { return true; } return super.hasCapability(capability, facing); }

Target:
you don't need the check for null here
Source:
public <T> T getCapability(Capability<T> capability, @Nullable EnumFacing facing) { if (capability == CapabilityEnergy.ENERGY) { return (T) energyInterface; } if (capability != null && (capability == MJ_CONN || capability == MJ_RECV)) { return (T) mjReceiver; } return super.getCapability(capability, facing); }

Target:
Why is it bad to check if null equals to any of these fields?
Source:
private char getChar() { int rndNum = baseProducer.randomBetween(0, 35); if (rndNum < 10) return (char)(49 + rndNum); else return (char)(65 + rndNum - 10); }

Target:
Plase add `{}` to improve readability.
Source:
public static CSPDirective fromValue(String value) { if (Strings.isEmpty(value)) return null; for (int i = 0; i < values().length; i++) { if (value.equals(values()[i].getValue())) return values()[i]; } return null; }

Target:
missing curly braces? (also in some other places)
Source:
public static void writeOpenTag(final Response response, IValueMap attributes) { response.write(INLINE_OPEN_TAG_START); if (attributes != null) { response.write(" "+attributes.toString()); } response.write(">\n"); }

Target:
`toString()` call is redundant here, missing white-spaces
Source:
public OnLoadHeaderItem setNonce(String nonce) { Args.notNull(nonce, "nonce"); this.nonce = nonce; return this; }

Target:
nonEmpty
Source:
public void executeBehavior(final Class<?> testClass, final AbstractAjaxBehavior behavior, final String filename) throws Exception { assert(behavior != null); log.info("=== " + testClass.getName() + " : " + behavior.toString() + " ==="); executeBehavior(behavior); assertResultPage(testClass, filename); }

Target:
This looks wrong.
Source:
public void deferred() throws Exception { tester.getApplication().setHeaderResponseDecorator(new IHeaderResponseDecorator() { @Override public IHeaderResponse decorate(IHeaderResponse response) { return new ResourceAggregator(new JavaScriptDeferHeaderResponse(response)); } }); executeTest(DeferredPage.class, "DeferredPageExpected.html"); }

Target:
this can be simplified to be ``` tester.getApplication().setHeaderResponseDecorator(response -> new ResourceAggregator(new JavaScriptDeferHeaderResponse(response))); ```
Source:
public void setXValues(String... values) { if (xValues == null) { xValues = new ArrayList<>(); } xValues.clear(); xValues.addAll(Arrays.asList(values)); }

Target:
`.clear()` could be in an `else` clause
Source:
public void setSizes(String... sizes) { if (this.sizes == null) { this.sizes = new ArrayList<>(); } this.sizes.clear(); this.sizes.addAll(Arrays.asList(sizes)); }

Target:
could be in `else`
Source:
protected void buildSrcAttribute(final ComponentTag tag, IModel<?> srcModel) { if (srcModel != null) { tag.put("src", srcModel.getObject().toString()); } }

Target:
The first statement remains valid :) `srcModel.getObject()` is still not tested for nullity...
Source:
public FileSystemResourceReference(String name, Path path) { super(Args.notNull(name, "name")); Args.notNull(path, "path"); this.path = path; }

Target:
org.apache.wicket.request.resource.ResourceReference#ResourceReference(java.lang.Class<?>, java.lang.String, java.util.Locale, java.lang.String, java.lang.String) cares about the non-null name. No need to check it here too.
Source:
public StringResourceModel(final String resourceKey, final Component component) { Args.notNull(resourceKey, "resource key"); this.resourceKey = resourceKey; this.component = component; }

Target:
To make the migration easier I think it would be good to have one more constructor: `public StringResourceModel(final String resourceKey, final Component component, final IModel<?> model)`.
Source:
public void before() { tester = new WicketTester(application); WebApplication webApplication = tester.getApplication(); webApplication.getWicketFilter().setFilterPath(""); }

Target:
Why get it again? You already have a reference to it.
Source:
protected TextField<Integer> newHoursTextField(final String id, IModel<Integer> model, Class<Integer> type) { TextField<Integer> hoursTextField = new TextField<Integer>(id, model, type); hoursTextField.add(getMaximumHours() == 24 ? RangeValidator.range(0, 23) : RangeValidator .range(1, 12)); hoursTextField.setLabel(new Model<>(HOURS)); return hoursTextField; }

Target:
Hi. Could you please use diamond operator? We try to use it wherever is possible. Thank you.
Source:
public void add(final SampleResult sample) { synchronized (buffer) { buffer.add(sample); dataChanged = true; CorrelationRecorder.setBuffer(buffer); } }

Target:
This does not look correct in terms of isolation of objects. Why is this call needed ?
Source:
public ResultData customizeResult(ResultData result) { if (extraOptions == null) { return new MapResultData(); } MapResultData customizedResult = new MapResultData(); customizedResult.setResult(DATA_CTX_RESULT, result); MapResultData extraResult = new MapResultData(); extraOptions.getProperties() .forEach((key, value) -> extraResult.setResult(key, new ValueResultData(value))); customizedResult.setResult(DATA_CTX_EXTRA_OPTIONS, extraResult); return customizedResult; }

Target:
This is changing the behaviour. Previously it would add the `result` as `DATA_CTX_RESULT`.
Source:
private boolean arrayMatched(JSONArray value) { if (value.isEmpty() && "[]".equals(getExpectedValue())) { return true; } boolean foundMatch = Arrays.stream(value.toArray()) .anyMatch(subj -> (subj == null && isExpectNull()) || isEquals(subj)); return foundMatch || isEquals(value); }

Target:
Does this change incur a performance penalty during load testing phase?
Source:
private static String deleteLineBreak(String postdata) { String repl = ""; if (postdata != null) { Matcher m = deleteLinePattern.matcher(postdata); repl = m.replaceAll(""); } return repl; }

Target:
I'd go for directly returning the results instead of using a variable and reassigning it.
Source:
public void addHeader(String name, String value) { if (name != null && name.equalsIgnoreCase("COOKIE")) { this.cookieInHeaders = value; } else if (name != null && !HEADERS_TO_IGNORE.contains(name)) { headers.put(name, value); } }

Target:
Actually, my intention to place `"COOKIE"` in front, was to make the `null` check unnecessary here. `if ("COOKIE".equalsIgnoreCase(name)) { ... }` would be enough. If a `null` value is problematic for the set-contains check, we could return early from this method when `name` is `null`.
Source:
public boolean getEnabled(String actionCommand) { if (ActionNames.ADD.equals(actionCommand)) return guiComp.canBeAdded(); else return true; }

Target:
Please use braces. Checkstyle should pick this up.
Source:
private static String getYarnApiAddress(Configuration conf) { Set<String> yarnApiAddresses = getYarnApiAddresses(conf); try { for (String yarnApiAddress : yarnApiAddresses) { if (successfulConnection(yarnApiAddress)) { return yarnApiAddress; } } } catch (IOException e) { LOG.error("Error getting yarn api address:", e); } return ""; }

Target:
If you used an `Optional` here (which represents the notion that you may not get an RM), you could turn [these lines](https://github.com/LiveRamp/cascading_ext/pull/90/files#diff-5796ba38ae3b31ff5eab085bca3465e8R83-R89) into ``` getYarnApiAddress(conf).map(x -> getYarnAppInfo(x, appId)) ```
Source:
public static MerlinsBeard from(Context context) { ConnectivityManager connectivityManager = (ConnectivityManager) context.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE); AndroidVersion androidVersion = new AndroidVersion(); ResponseCodeValidator validator = new ResponseCodeValidator.DefaultEndpointResponseCodeValidator(); EndpointPinger pinger = EndpointPinger.withCustomEndpointAndValidation(Endpoint.from(ENDPOINT), validator); Ping ping = new Ping(Endpoint.defaultEndpoint(), new EndpointPinger.ResponseCodeFetcher(), validator); return new MerlinsBeard(connectivityManager, androidVersion, pinger, ping); }

Target:
Maybe? ```suggestion EndpointPinger pinger = EndpointPinger.withCustomEndpointAndValidation(Endpoint.defaultEndpoint(), validator); ```
Source:
public void reset() { if (snackbar != null) { snackbar.dismiss(); snackbar = null; } }

Target:
`if (null) { return }` ?