auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected boolean canDoAction() { if (!(validate(hostExists()) && validate(hostStatusValid()))){ return false; } return true; }

Target:
you can simplify it with a single line by replacing the method's body with: return validate(hostExists()) && validate(hostStatusValid());
Source:
public List<ID3v2ChapterFrameData> getChapters() { if (obseleteFormat) { return Collections.emptyList(); } return extractChapterFrameData(ID_CHAPTER); }

Target:
Changing from returning null to returning an empty collection changes the SDK's interface, which might affect applications that are using it. I'd prefer not to make a breaking change unless it's absolutely neccessary.
Source:
ImageEditorPanel(MainFrame mainFrame, BufferedImage image, String name) { this.image = image; this.name = name; setTransferHandler(new ImageTransferHandler(mainFrame)); checkImage(); setOpaque(false); setLayout(new BorderLayout()); loadSupport(); buildImageViewer(); buildStatusPanel(); }

Target:
checkImage(); should be below buildStatusPanel(); loadSupport(); buildImageViewer(); buildStatusPanel(); checkImage();
Source:
public void setIdentifiers(List<Identifier> identifiers) { Identifiers = identifiers; }

Target:
Shouldn't this be this.variableName. This is a Potential Null pointer Exception.
Source:
public String getActionClass( ) { return environmentVariables.get( actionClass ); }

Target:
Seems like a lot of work just to verify that the json is valid. Perhaps there is some 3rd party utility to do that for us? Something to consider
Source:
public void handleMessage(Message msg) { switch (msg.what) { case EVENT_QUALIFIED_NETWORKS_CHANGED: synchronized (this) { AsyncResult ar = (AsyncResult) msg.obj; List<QualifiedNetworks> networks = (List<QualifiedNetworks>) ar.result; updateAvailableNetworks(networks); } break; default: loge("Unexpected event " + msg.what); break; } }

Target:
Why not use the synchronized in updateAvailableNetworks?
Source:
private void saveStateParamForIdpToRequestSession(String state, String idpOriginKey, HttpServletRequest request) { if (request != null) { request.getSession().setAttribute("xoauth-state-" + idpOriginKey, state); } }

Target:
Is there any value to this null check? Even if it is null, this operation doesn't make any sense if we can't access the session.
Source:
private void logMeasureByResource(Resource resource, Measure measure) { if (LOG.isDebugEnabled()) { Measure alreadySaved = MEASURES_BY_RESOURCE.get(resource); if (alreadySaved == null) { MEASURES_BY_RESOURCE.put(resource, measure); } else { LOG.debug("Measure already saved for resource {}", measure, resource); } } }

Target:
![MAJOR](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/severity-major.png) Make "logMeasureByResource" a "static" method. [![rule](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/rule.png)](https://dory.sonarsource.com/coding_rules#rule_key=squid%3AS2325)
Source:
private List<ProducerBatch> getChildrenProducerBatch() { if (childrenProducerBatch == null) { return Collections.emptyList(); } return childrenProducerBatch; }

Target:
If we could get rid of null check, `addChildrenProducerBatch` and `getChildrenProducerBatch` could be removed as well.
Source:
private String getSetting(String settingName) { SettingKey key = settingKeyDAO.findByName(settingName); if (key != null) { Setting setting = settingDAO.findByKey(key); if (setting != null) return setting.getValue(); } return null; }

Target:
Use braces - see https://www.dwheeler.com/essays/apple-goto-fail.html
Source:
public float getPrefHeight () { // Min of borders + text height or drawable height layout = new GlyphLayout(style.font, model.getValue().toString()); return Float.max(style.background.getMinHeight(), style.background.getTopHeight() + style.background.getBottomHeight() + layout.height); }

Target:
`Float.max()` is since 1.8 so it won't work on Android and GWT. Use `Math.max()` instead.
Source:
private void removeIncludeExcludeWithHandler() { new PushButton("Remove...").click(); new WaitUntil(new ShellIsAvailable("Confirmation")); new DefaultShell("Confirmation"); new PushButton("OK").click(); }

Target:
no need for the wait, DefaultShell already has the wait inside
Source:
public synchronized void onClosedSource(String tableName, int partition) { boolean removed = m_dataSourcesClosing.remove(tableName, partition); if (exportLog.isDebugEnabled()) { if (removed) { exportLog.debug("Closed " + tableName + ", partition " + partition); } else { exportLog.info("Closed untracked " + tableName + ", partition " + partition + " (ok on shutdown)"); } } }

Target:
This will only be logged if debug is enabled since it is in this block you might want to reorder if statements ``` if (!m_dataSourcesClosing.remove(tableName, partition)) <log info message> else if (log.isDebugEnabled()) <log closed message> ```
Source:
public String getJBossDiscoveryDirectory() { // use commandline override -Djboss.discovery.directory.url String directory = System.getProperty(JBOSS_DISCOVERY_DIRECTORY, null); if (directory == null) { IPropertiesProvider pp = PropertiesHelper.getPropertiesProvider(); try { directory = pp.getValue(JBOSS_DISCOVERY_DIRECTORY, new NullProgressMonitor()); } catch (CoreException e) { throw new RuntimeException(e); } } return directory; }

Target:
shouldn't there be a default so this never happens ?
Source:
public void setActive(boolean active) { getImage().setActive(true == active); }

Target:
No need... getImage().setActive(active)
Source:
public MainDrawerHandler(WikiDrawerLayout slidingPane, Activity parentActivity) { this.slidingPane = slidingPane; this.parentActivity = parentActivity; ButterKnife.bind(this.slidingPane); setUpViews(); }

Target:
What does this call do?
Source:
public KeyStore loadKeyStore() throws IOException, GeneralSecurityException { KeyStore ks = keyStoreInstance(); InputStream inputStream = null; try { inputStream = new FileInputStream(new File(keyStorePath)); ks.load(inputStream, passwordStringToCharArray(keyStorePassword)); return ks; } finally { forceClose(inputStream); } }

Target:
We can use try-with-resources now. I know this is only a refactoring but we can take this opportunity to clean up code
Source:
private List<GlusterVolumeEntity> getEligibleVolumesList(Set<GlusterVolumeEntity> upVolumesWithSuggestedCapacityAndNotInMasterCluster, Set<GlusterVolumeEntity> existingSessionSlaveVolumes) { List<GlusterVolumeEntity> eligibleVolumes = new ArrayList<GlusterVolumeEntity>(); upVolumesWithSuggestedCapacityAndNotInMasterCluster.removeAll(existingSessionSlaveVolumes); eligibleVolumes.addAll(upVolumesWithSuggestedCapacityAndNotInMasterCluster); return eligibleVolumes; }

Target:
you could just return upVolumesWithSuggestedCapacityAndNotInMasterCluster here
Source:
public EclipseReferencePointManager() { referencePointToProjectMapper = new ConcurrentHashMap<IReferencePoint, org.eclipse.core.resources.IProject>(); }

Target:
please use the Diamond Operator for initialization
Source:
public void setSchedulerService(SchedulerService schedulerService) throws InitialisationException { this.schedulerService = schedulerService; initialise(); }

Target:
this doesn't belong here
Source:
public void evictExpiredEntries(int expirationPercentage) { long now = Clock.currentTimeMillis(); int maxIterationCount = getMaxIterationCount(size(), expirationPercentage); int evictedCount = 0; int maxRetry = 3; int loop = 0; while (true) { evictedCount += evictExpiredInternal(maxIterationCount, now); if (evictedCount >= maxIterationCount) { break; } loop++; if (loop > maxRetry) { break; } } }

Target:
`while (loop < maxRetry)` will get rid of the extra `if break` condition.
Source:
public static IJBoss7ManagerService findService(String runtimeType) { forceStart("org.jboss.ide.eclipse.as.core"); forceStart("org.jboss.ide.eclipse.as.management.as71"); forceStart("org.jboss.ide.eclipse.as.management.wildfly8"); try { return JBoss7ManagerUtil.getService(runtimeType); } catch(JBoss7ManangerException ise) { return null; } }

Target:
Why forceStart call is required when org.jboss.ide.eclipse.as.management.as71 is declared as a dependency for test plugin?
Source:
private List<Iterator<Entry<KeyType>>> getGroupersIterator(boolean sorted) { return groupers.stream() .map(grouper -> { synchronized (grouper) { return grouper.iterator(sorted); } }).collect(Collectors.toList()); }

Target:
Should break line before dot
Source:
private void waitForAppToFinish() { workers.shutdown(); try { boolean finishedInTime = workers. awaitTermination(durationMs + APPLICATION_TIMEOUT_IN_MS, TimeUnit.MILLISECONDS); String livenessState = finishedInTime ? "Success" : "Fail"; Correctness.recordOperation("Liveness, " + livenessState, false); if (!finishedInTime) { System.exit(0); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } finally { taskProducer.shutdownNow(); checkpointer.shutdownNow(); } }

Target:
Shouldn't you return an error code in this case?
Source:
public Boolean scriptExists(final String sha1, final String key) { return new JedisClusterCommand<Boolean>(connectionHandler, timeout, maxRedirections) { @Override public Boolean execute(Jedis connection) { return connection.scriptExists(sha1); } }.run(1,key); }

Target:
I think .run(key) is more faster than this if we keep JedisClusterCommand.run(String or byte[]).
Source:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mSubscriptions = new Disposable[2]; mRepository = (Repository) getArguments().getSerializable("repo"); mRef = getArguments().getString("ref"); }

Target:
Maybe it would be better to use some sort of map? That way we would avoid potential out of bounds exceptions when someone adds new subscription but doesn't update that declaration.
Source:
public void dispatchInvalidateOptionsMenu() { if (BuildConfig.DEBUG) Log.d(TAG, "[dispatchInvalidateOptionsMenu]"); mActivity.getWindow().invalidatePanelMenu(Window.FEATURE_OPTIONS_PANEL); if (mMenu != null) { mMenu.invalidate(); } }

Target:
Either no brackets or put invalidate on its own line.
Source:
public Collection<String> getSupportedCategories() { return Collections.unmodifiableCollection(SUPPORTED_CATEGORIES); }

Target:
Since the categories never change, it would be better to make the value of `SUPPORTED_CATEGORIES` unmodifiable from the start.
Source:
public List<Runnable> shutdownNow() { shutdown = true; List<Runnable> runnableList = new LinkedList<>(); runnableList.addAll(executorService.shutdownNow()); runnableList.addAll(blockedTasks); controllerThread.interrupt(); return runnableList; }

Target:
Shouldn't you interrupt the controller first?
Source:
public WorkQueue.Executor get() { CurrentUser user = userProvider.get(); WorkQueue.Executor executor = queues.getInteractiveQueue(); if (user.isBatchUser()) { executor = queues.getBatchQueue(); } return executor; }

Target:
Style-nit: Don't assign then replace. Instead use a proper if-else: if (user.isBatchUser) { return queues.getBatchQueue(); } else { return queues.getInteractiveQueue(); }
Source:
final AppConfig getAppConfig(CascadeStrategy defaultStrategy) throws ConfigException { return DefaultAppConfig.builder() .withDefaultCascadingStrategy(defaultStrategy) .withApplicationConfigName(DefaultAppConfig.DEFAULT_APP_CONFIG_NAME) .build(); }

Target:
Is there any reason to explicitly set to the default?
Source:
public static String moduleToJsonString(Module module) throws IOException { JsonFactory jsonFactory = createJsonFactory(); StringWriter writer = new StringWriter(); JsonGenerator jsonGenerator = jsonFactory.createJsonGenerator(writer); jsonGenerator.useDefaultPrettyPrinter(); jsonGenerator.writeObject(module); String result = writer.getBuffer().toString(); return result; }

Target:
```suggestion return writer.getBuffer().toString(); ```
Source:
private String createResults() { QueryResults queryResults = new QueryResults( "20160128_214710_00012_rk68b", server.url("/query.html?20160128_214710_00012_rk68b").uri(), null, null, ImmutableList.of(new Column("_col0", BigintType.BIGINT)), ImmutableList.of(ImmutableList.of(123)), StatementStats.builder().setState("FINISHED").build(), //new StatementStats("FINISHED", false, true, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, null), null, null, null, null); return QUERY_RESULTS_CODEC.toJson(queryResults); }

Target:
please squash this with first commit
Source:
protected HashMap<String, Object> buildGitEnv(String url, String username, String password, boolean mirror) { return new HashMap<String, Object>() {{ put("origin", url); put(SCHEME, GitRepository.SCHEME.toString()); put("replaceIfExists", true); put("username", username); put("password", password); put(MIRROR, mirror); }}; }

Target:
Program to interface, not to implementation - please change return type to `Map<String, Object>`
Source:
public void setDefinitions(List<Definition> definitions) { this.m_definitions = definitions; }

Target:
this.m_
Source:
protected void cleanUp(UserAccount userAccount) { SalesforceAnalyticsManager.reset(userAccount); RestClient.clearCaches(userAccount); UserAccountManager.getInstance().clearCachedCurrentUser(userAccount); }

Target:
We also need to clear the cache when user switching occurs.
Source:
protected static int parseFraction(String string, int sign, String text) { if (string == null || string.length() == 0) { return 0; } try { string = (string + "000000000").substring(0, 9); return Integer.parseInt(string) * sign; } catch (NumberFormatException | ArithmeticException e) { throw (DateTimeParseException) new DateTimeParseException( "Text cannot be parsed to a PeriodAndDuration: fraction", text, 0).initCause(e); } }

Target:
I'm probably missing something, why not using the constructor taking a Throwable?
Source:
public IASTName[] getNames() { IASTName[] result = new IASTName[fQualifierPos + (fLastName == null ? 1 : 2)]; int idx = 0; for (ICPPASTNameSpecifier nameSpecifier : getQualifier()) if (nameSpecifier instanceof IASTName) result[idx++] = (IASTName) nameSpecifier; else throw new UnsupportedOperationException("Can't use getNames() on a " + //$NON-NLS-1$ "qualified name that includes a decltype-specifier. Use " + //$NON-NLS-1$ "getQualifier() and getLastName() instead"); //$NON-NLS-1$ if (fLastName != null) result[fQualifierPos + 1] = fLastName; return result; }

Target:
Please always use curly braces in 'for' statements.
Source:
private String getConsoleModelErrorMessage(Object sender, ErrorCodeEventArgs e) { String translatedError = consoleErrorCodeTranslator.translateErrorCode(e.getErrorCode()); if (sender instanceof SpiceConsoleModel) { return ConstantsManager.getInstance() .getMessages() .errConnectingVmUsingSpiceMsg(translatedError); } else if (sender instanceof RdpConsoleModel) { return ConstantsManager.getInstance() .getMessages() .errConnectingVmUsingRdpMsg(translatedError); } throw new IllegalArgumentException("Message recieved from an unknown model " + sender.getClass().getName()); //$NON-NLS-1$ }

Target:
who catches that? I'd return a message instead;
Source:
public final void setExtendedExpiresOn(final Date extendedExpiresOn) { this.mExtendedExpiresOn = extendedExpiresOn; }

Target:
> this [](start = 8, length = 4) no this. please
Source:
public static void mkdir(final File d, boolean skipExisting) throws IOException { if (skipExisting && d.exists() && d.isDirectory()) return; if (!d.mkdir()) throw new IOException(MessageFormat.format( JGitText.get().mkDirFailed, d.getAbsolutePath())); }

Target:
I would put this on the failure path: if (!d.mkdir()) { if (skipExisting && d.isDirectory()) return; throw new IOException(...); } Because odds are the caller wants to make a new directory and we can reasonably assume it doesn't exist yet. If it does, we'll fail on the mkdir and check its mode, if its a directory, we're fine, if its not, we fail.
Source:
protected void initDiskVmElement() { setDiskVmElement(new DiskVmElement(new VmDeviceId(null, null))); }

Target:
IMHO can you a no-argument C'tor.
Source:
public void setHtmlTemplate(FreemarkerTemplate htmlTemplate) { if (this.getUseFreemarkerTemplate()) { set(LANDING_PAGE_HTML_TEMPLATE, htmlTemplate); } }

Target:
better to remove if if statement, just set the value, the user of the entity can than use the getUseFreemarkerTemplate function to choose to use the template of not.
Source:
public PhysicalOperation visitExchange(ExchangeNode node, LocalExecutionPlanContext context) { checkArgument(node.getScope() == LOCAL, "Only local exchanges are supported in the local planner"); if (node.getOrderingScheme().isPresent()) { return createLocalMerge(node, context); } else { return createLocalExchange(node, context); } }

Target:
nit: it seems like we prefer to not put else after return elsewhere in the codebase
Source:
public void onCreated(Iterable<CacheEntryEvent<? extends K, ? extends V>> events) throws CacheEntryListenerException { for (Object event1 : events) { CacheEntryEvent event = (CacheEntryEvent) event1; Assert.assertEquals(EventType.CREATED, event.getEventType()); this.created.incrementAndGet(); event.getKey(); event.getValue(); event.getSource(); } }

Target:
This could be typed as CacheEntryEvent<? extends K, ? extends V> and the cast wouldn't be needed on the next line.
Source:
private static PendingIntent buildIntent(Context context, long keyId) { Intent intent = new Intent(BROADCAST_ACTION_PASSPHRASE_CACHE_SERVICE); intent.putExtra(EXTRA_KEY_ID, keyId); //request code should be unique for each call for pending intent so we have taken requestcode //as keyId which is unique for each call as keyId is unique for each passphrase long requestcode = keyId; return PendingIntent.getBroadcast(context, (int)requestcode, intent, PendingIntent.FLAG_CANCEL_CURRENT); }

Target:
this line is redundant, you can use keyId directly
Source:
public boolean hasTxLogs() throws RuntimeException { File[] files = storeDir.listFiles( LogFiles.FILENAME_FILTER ); if ( files == null ) { throw new RuntimeException( "Files was null. Incorrect directory or I/O error?" ); } return files.length > 0; }

Target:
Does it make sense to declare `throws RuntimeException`?
Source:
public void setTaskScheduler(TaskScheduler taskScheduler) { setTaskScheduler(taskScheduler); }

Target:
??? Does it work? Really it has to be `super.`. IDEA shows the recursion for me
Source:
public Constant(Sort sort, String value) { super(sort, null); this.value = value; }

Target:
Oh right, I remember, the parser does some funky stuff internally with the Token and KList classes. Okay. I am persuaded that it makes sense to go this route for now. Please make sure it is clear that developers should never call this constructor from outside the parser kernel, then.
Source:
private void addCriteriaForFlows(final OnmsCriteria criteria, final Boolean hasFlows) { if (hasFlows == null) { return; } criteria.add(Restrictions.eq("node.hasFlows", hasFlows)); }

Target:
This is a duplicated check, as this is only invoked after `command.hasFlows()` is true, so not required to invoke it again. If you absolutely want this check, I'd opt for ```java if (hasFlows != null) { ... } ``` as it is much easier to read.
Source:
public List<String> getJobsForAnExtension(final String extensionName) throws FalconException { List<ExtensionJobsBean> extensionJobs = metaStore.getJobsForAnExtension(extensionName); if (null != extensionJobs && !extensionJobs.isEmpty()){ List<String> extensionJobNames = new ArrayList<>(); for (ExtensionJobsBean extensionJobsBean: extensionJobs) { extensionJobNames.add(extensionJobsBean.getJobName()); } return extensionJobNames; } else { return null; } }

Target:
It is always good to return an empty list instead. Avoids NPEs
Source:
public void handleEvent(EventBundle events) { for (Event event : events) { if (DOCUMENT_REMOVED.equals(event.getName())) { DocumentEventContext context = (DocumentEventContext) event.getContext(); DocumentModel docModel = context.getSourceDocument(); if (DOCUMENT_ROUTE_DOCUMENT_TYPE.equals(docModel.getType())) { deleteOrphanTasks(context.getCoreSession(), docModel.getId()); } } } }

Target:
This test is not needed since the event bundle is filtered regarding the events defined to trigger the listener in its descriptor.
Source:
public Set<Order> getOrders() { if (orders == null) { orders = new LinkedHashSet<Order>(); } return orders; }

Target:
Yes am assuming it should be a SortedSet and the ordering would be based on the sortWeight of the orders.
Source:
private void executeIdentifier(IdentifierTree tree) { Symbol symbol = tree.symbol(); SymbolicValue value = programState.getValue(symbol); if (value == null) { value = constraintManager.createSymbolicValue(tree); programState = programState.stackValue(value); learnIdentifierNullConstraints(tree, value); programState = programState.put(symbol, value); } else { programState = programState.stackValue(value); programState = programState.put(symbol, value); } }

Target:
The call to `put` can be extracted from the `if-else` statement in order to remove the duplication.
Source:
public AutoRegisterModules(String pluginName, PluginGuiceEnvironment env, JarFile jarFile, ClassLoader classLoader) { this.pluginName = pluginName; this.env = env; this.jarFile = jarFile; this.classLoader = classLoader; this.sshGen = env.hasSshModule() ? env.newSshModuleGenerator() : null; this.httpGen = env.hasHttpModule() ? env.newHttpModuleGenerator() : null; }

Target:
Not needed in this change.
Source:
public boolean checkIfJobHasTasks(Guid jobId) { List<Step> steps = step.getStepsByJobIdForVdsmAndGluster(jobId); return steps.size() > 0; }

Target:
Please use: return !steps.isEmpty();
Source:
public String getUserNameForChannel(UUID channelId) throws UnauthenticatedException { try (LockResource clientsLockShared = new LockResource(mClientsLock.readLock())) { if (mChannels.containsKey(channelId)) { AuthenticatedChannelInfo clientInfo = mChannels.get(channelId); return mChannels.get(channelId).getUserName(); } else { throw new UnauthenticatedException( String.format("Client:%s needs to be authenticated", channelId.toString())); } } }

Target:
nit: extra space
Source:
public static boolean isValidSingleVersion( final String version ) { boolean result = true; if ( version == null || version.trim().length() < 1 ) { result = false; } try { SingleVersion singleVersion = new VersionParser( version ).single(); } catch ( final ParseException e ) { result = false; } catch ( final TokenMgrError e ) { result = false; } return result; }

Target:
I'd just go ahead and return false here. The logic you have here doesn't prevent trying to parse when the input value is null or empty. And when you have that fixed, go ahead and merge at will. :smiley:
Source:
public void handle(DataServerConnection connection, int rpcType, ByteBuf pBody, ByteBuf dBody, ResponseSender sender) throws RpcException { switch (rpcType) { case RpcType.REQ_RUNTIME_FILTER_VALUE : { handleRuntimeFilterRequest(pBody, dBody, sender); } case RpcType.REQ_RECORD_BATCH_VALUE : { handleRecordBatchRequest(pBody, dBody, sender); } default: throw new RpcException("Not yet supported."); } }

Target:
`break` statement is missing here and below
Source:
public Builder addModifiers(Modifier... modifiers) { this.modifiers.addAll(Arrays.asList(modifiers)); return this; }

Target:
`Collections.addAll` saves the wrapper object... although we don't need to go full-on nit picky on allocations like we would something in a library.
Source:
public void testCreate() throws StripeException { Map<String, Object> params = new HashMap<String, Object>(); params.put("amount", 100); params.put("currency", "usd"); params.put("destination", "acct_123"); Transfer transfer = Transfer.create(params); assertNotNull(transfer); verifyRequest( APIResource.RequestMethod.POST, "/v1/transfers", params ); }

Target:
should be named `resource`
Source:
private boolean isGlobalFailure(ITestResult result) { ITestNGMethod m = result.getMethod(); return m.isBeforeTestConfiguration() || m.isBeforeSuiteConfiguration(); }

Target:
static here and later
Source:
private static void validateEmail(String value) throws WSSecurityException { final EmailValidator validator = EmailValidator.getInstance(); if (!validator.isValid(value)) { throw new WSSecurityException(ErrorCode.FAILURE, "Not a valid email address."); } }

Target:
no need to create a variable here. Use EmailValidator.getInstance().isvalid()
Source:
private void addAll(Object array) throws JSONException { if (array.getClass().isArray()) { int length = Array.getLength(array); this.myArrayList.ensureCapacity(length); for (int i = 0; i < length; i += 1) { this.put(JSONObject.wrap(Array.get(array, i))); } } else { throw new JSONException( "JSONArray initial value should be a string or collection or array."); } }

Target:
change to ```java this.myArrayList.ensureCapacity(this.myArrayList.size() + length); ```
Source:
public static synchronized IBinder makeConnector(Context context) { if (sConnector == null) { sConnector = new TetheringConnector(context); } return sConnector; }

Target:
I don't think this should be public (NetworkStack version is still public for legacy reasons)
Source:
protected void setSplitterPosition(int leftWidth, int rightWidth) { try { if (lockSplitter.acquire()) { double total = leftWidth + rightWidth; if (total > 0) { double d = leftWidth / total; getSwingContainer().setDividerLocation(d); getSwingContainer().setResizeWeight(d); } } } finally { lockSplitter.release(); } }

Target:
Can leftWidth ever be negative?
Source:
public void process(CtElement element) { if(element instanceof CtPackage && element != getFactory().Package().getRootPackage()){ ((CtPackage) element).setSimpleName("newtest"); } }

Target:
there is a confusion, the goal is that client code indeed never has to write this. so the implementation RootPackage.setSimpleName would simply be ... empty. do you see what I mean?
Source:
public CommandContext withoutCompensationContext() { return withCompensationContext(new DefaultCompensationContext()); }

Target:
shouldn't it be return withCompensationContext(new *NoOpCompensationContext*()) or even return withCompensationContext(NoOpCompensationContext.getInstance())
Source:
public <T> Model<T> getOrNull(Class<T> type, @CheckForNull Class<?> propertyOwner, @Nullable String property) throws NotExportableException { Model m = models.get(type); if(m==null && type.getAnnotation(ExportedBean.class) != null) { m = new Model<T>(this, type, propertyOwner, property); } return m; }

Target:
`@CheckForNull` return. And why is this declared to throw `NotExportableException`?
Source:
public void beforeParamAndAfterParamAreRun() { fLog = ""; final Result result = JUnitCore.runClasses(BeforeParamAndAfterParam.class); assertEquals(0, result.getFailureCount()); assertEquals("beforeClass before(A) first(A) second(A) afterParam " + "before(B) first(B) second(B) afterParam afterClass ", fLog); }

Target:
It would be great to have tests for 1. Multiple `@BeforeParam` methods 1. Multiple `@AfterParam` methods 1. `@AfterParam` methods with parameters 1. `@BeforeParam` methods without parameters 1. Parameterized tests with more than one parameter
Source:
public void setup() { Section section = new Section(new Shell(), SWT.NONE); event = new ExpansionEvent(section, true); expansionEventConsumer = new ExpansionEventConsumer(); }

Target:
shell should be disposed in teardown
Source:
public void testGenerateGroupId() { String user = System.getProperty("user.name"); String vcloudGroupId = JcloudsLocation.generateGroupId("vcloud"); assertTrue(vcloudGroupId.startsWith("br-")); String fooGroupId = JcloudsLocation.generateGroupId("foo"); if (!"brooklyn".equals(user)) assertTrue(fooGroupId.startsWith("brooklyn-"+user)); }

Target:
What happens if the user is "brooklyn"? Is it sensible behaviour? Can/should we add an else block with an assertion for that?
Source:
private void checkPasswordValidity(DocumentModel userModel) throws InvalidPasswordException { String schema = dirService.getDirectorySchema(userDirectoryName); String passwordField = dirService.getDirectory(userDirectoryName).getPasswordField(); Property passwordProperty = userModel.getProperty(String.format("%s:%s", schema, passwordField)); if (passwordProperty.isDirty()) { String clearPassword = passwordProperty.getValue(String.class); if (StringUtils.isNotBlank(clearPassword) && !validatePassword(clearPassword)) { throw new InvalidPasswordException(); } } }

Target:
`protected`, to allow easy subclassing.
Source:
protected void cancel() { setWindow(null); setConfirmWindow(null); }

Target:
There is no harm in setting the confirmWindow to null, but since you are not actually setting it, there is no need to set it to null.
Source:
public RemoveUnregisteredVmCommand(T parameters, CommandContext cmdContext) { super(parameters, cmdContext); setStorageDomainId(parameters.getStorageDomainId()); }

Target:
already done in the super?
Source:
public String skipString() throws IOException { return tokenizer.readString(); }

Target:
tokenizer.skipString() I guess. No need to convert Utf8 to String here, just use the stream.skip().
Source:
public AbstractCursorWrappingIndexHits( int size, float score ) { this.size = size; this.score = score; }

Target:
Why public?
Source:
public ReportDocument(String targetDir, String testName, int testsSize, boolean separateClusterCharts) { super(targetDir, String.format("test_%s.html", testName), "Test " + testName); this.testSize = testsSize; this.testName = testName; this.separateClusterCharts = separateClusterCharts; }

Target:
'testsSize' is not very descriptive name, please use something like 'maxConfigurations' (is it really number of configurations that have executed this test?)
Source:
public void populateExpressionProperty(FactModelTree factModelTree) { if (factModelTree.getSimpleProperties().containsValue(ConstantsHolder.EXPRESSION_CLASSNAME)) { return; } final String expressionName = factModelTree.getFactName() + ConstantsHolder.EXPRESSION_SUFFIX; long count = factModelTree.getSimpleProperties().keySet().stream().filter(key -> key.startsWith(expressionName)).count(); factModelTree.addSimpleProperty(count > 0 ? expressionName + "_" + count : expressionName, ConstantsHolder.EXPRESSION_CLASSNAME); }

Target:
@yesamer Please, do not do that, and follow what we agreed upon: a fixed static part (ScesimExpression) followed by "-" and a randomly generated two digit number. Beside that, for each "Object" there can be only one "expression" property, so that count has no meaning; if you need to take this in account, there is something wrong in the code
Source:
public VmCommand(T parameters) { super(parameters); setVmId(parameters.getVmId()); setReason(parameters.getReason()); }

Target:
why this is in vmCommand? should be in stopBase command
Source:
public String retrieve(VeluxBridgeProvider bridge) { logger.trace("retrieve() called."); logger.trace("retrieve() About to query device status."); BCgetDeviceStatus.Response response = bridge.bridgeCommunicate(new BCgetDeviceStatus()); if ((response == null) || (!response.getResult())) { logger.trace("retrieve() finished with failure."); return null; } else { logger.trace("retrieve() finished successfully with result {}.", response.getDeviceStatus()); return response.getDeviceStatus(); } }

Target:
"else" is redundant here. Consider dropping it.
Source:
private static int getNeededNumberOfUsbControllers(int numberOfSlots) { int numOfcontrollers = numberOfSlots / SLOTS_PER_CONTROLLER; if (numOfcontrollers == 0) { numOfcontrollers = 1; } return numOfcontrollers; }

Target:
whole function can be return math.max(numberOfSlots / SLOTS_PER_CONTROLLER, 1);
Source:
public synchronized Long size() { final File file = path.toFile(); Long size = (file.exists() && !file.isDirectory()) ? file.length() : 0l; if (childSize < 0l || childModCount > lastSizeCheck) { Long childSize = 0l; lastSizeCheck = childModCount; for (FileCopyResult child : children) { childSize += child.size(); } this.childSize = childSize; } size += childSize; return size; }

Target:
can this be primitive long to avoid the unnecessary wrapping?
Source:
public RngDeviceParameters(VmRngDevice rngDevice, boolean vm) { if (rngDevice == null) { throw new IllegalArgumentException("RNG Device must be specified."); } this.rngDevice = rngDevice; isVm = vm; }

Target:
please no exceptions in the constructor
Source:
private static boolean isInContext(Pair<IErrorParserNamed, Integer> pair, int context) { return (pair.second & context) == context; }

Target:
Simpler: (pair.second & context) != 0
Source:
private void removeAlwaysOn(IActionSetDescriptor descriptor) { if (descriptor == null) { return; } if (!alwaysOnActionSets.contains(descriptor)) { return; } alwaysOnActionSets.remove(descriptor); if (page != null) { page.perspectiveActionSetChanged(this, descriptor, ActionSetManager.CHANGE_HIDE); } }

Target:
Hard to say in Gerrit (I still have to pull in the change into Eclipse) but the checks are already done in the protected addAlwaysOff method. Is this method called in places where these checks are not already done?
Source:
public void createGroupUnionForIndirectRelationship() throws Exception { System.out.println(CLASS_NAME + "createGroupUnionForIndirectRelationship"); Vo vo = setUpVo(); groupsManagerBl.createGroup(sess, vo, group2); groupsManagerBl.createGroup(sess, group2, group3); groupsManagerBl.createGroup(sess, group3, group4); groupsManagerBl.createGroupUnion(sess, group4, group2, false); }

Target:
I think there is an invalid order of the groups. The way it is implemented now, this test creates this relation: 2 | 3 | 4 And calling `createGroupUnion(sess, group4, group2, false)` tries to import members from group2 to group4. This causes a cycle, and I am not sure if we can detect this in the current implementation. Also, the test passes because of the error which I have pointed out above. ```suggestion groupsManagerBl.createGroupUnion(sess, group2, group4, false); ```
Source:
private SelectionListener createListener() { final SelectionListener listener = new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { resetProperties(); } @Override public void widgetDefaultSelected(SelectionEvent e) { // nothing to do } }; return listener; }

Target:
final missing
Source:
public void testOur404Handler(String wiki, String inputPath, String expectedPath) { String wikiBase = urlBuilder.getUrlForWiki(wiki); String inputUrl = wikiBase + inputPath; String expectedUrl = expectedPath; if (!expectedUrl.startsWith("http://")) { expectedUrl = wikiBase + expectedUrl; } driver.get(inputUrl); String actualUrl = driver.getCurrentUrl(); Assertion.assertEquals(actualUrl, expectedUrl); }

Target:
I would flip the condition since the special case is when we have protocol, not otherwise: ``` java if (expectedUrl.startsWith("http://")) { expectedUrl = expectedPath } ```
Source:
public void closeDirty() { try { close(false); } catch (final RuntimeException e) { log.warn(String.format("Ignoring uncaught error in unclean close of standby task %s", id), e); } log.info("Closed dirty"); }

Target:
What exception is possibly thrown from this close(false) call?
Source:
public boolean renderClouds(int cloudTicks, float partialTicks) { net.minecraftforge.client.IRenderHandler renderer = this.client.world.provider.getCloudRenderer(); if (renderer != null) { renderer.render(partialTicks, this.client.world, this.client); return true; } return cloudRenderer.render(cloudTicks, partialTicks); }

Target:
Just `IRenderHandler` (use an import)
Source:
private ValueType getResultILType(GenContext ctx) { Arrow a = (Arrow) this.type; if( isGeneric() && a.getResult() instanceof UnresolvedType && ((UnresolvedType) a.getResult()).getName().equals(this.genTypeName) ) { return new NominalType(new Variable(GENERIC_PREFACE), GENERIC_MEMBER); } return ((Arrow)type).getResult().getILType(ctx); }

Target:
Don't need this if statement either
Source:
public Entity getControllingPassenger() { List<Entity> _passengers = getPassengers(); if(_passengers.isEmpty()) { setDriverState(false); return null; } else { setDriverState(true); return _passengers.get(0); } }

Target:
that seems like a hack to me. Shouldn't the boolean `driver` indicate if the seat is the driver seat? Which doesn't change based on the presence of a actual driver entity. I did not take a deeper look at this, but my assumption is that the boolean is not correctly set after reloading the entity from a save file
Source:
public Limit(@Nonnull final Long limit, final Operator child) { super(child); this.limit = Objects.requireNonNull(limit, "limit"); Preconditions.checkArgument(limit >= 0L, "limit must be non-negative"); toEmit = this.limit; done = false; }

Target:
I don't think you need this new flag. You should immediately return `null` from `fetchNextReady()` if the child has already been closed, which you can test with `child.isOpen()` or `child.eos()`. @jingjingwang do you agree?
Source:
public void add(Key k, Value v) { if (key == null) { key = k; timeStamps.add(k.getTimestamp()); values.add(v); size++; } else if (key.compareRow(k.getRow()) == 0 && key.compareColumnFamily(k.getColumnFamily()) == 0) { timeStamps.add(k.getTimestamp()); values.add(v); } else { //TODO: what happens here } }

Target:
Not quite (did not check column qualifier or visibility), you can use `key.equals(k, PartialKey.ROW_COLFAM_COLQUAL_COLVIS)` and it checks row and all three column fields.
Source:
public STGroup getTemplates() { if (templates == null) { templates = loadTemplates(); String version = getVersion(); if (version == null || !version.equals(Tool.VERSION)) { gen.tool.errMgr.toolError(ErrorType.INCOMPATIBLE_TOOL_AND_TEMPLATES, version, Tool.VERSION, language); } } return templates; }

Target:
The version check should come before the call to `loadTemplates()`.
Source:
private boolean isException(String value) { return value.length() == 4 || Integer.parseInt(value) < 8; }

Target:
This line triggers a `java.lang.NumberFormatException` for the following code: ``` $a = 012_345; ```
Source:
public LatLng getGoogleMapsLocation() { ParseGeoPoint pGP = (ParseGeoPoint) getClient().get("location"); return new LatLng(pGP.getLatitude(), pGP.getLongitude()); }

Target:
Same here...one thing I've noticed is that if location == null NPE exceptions get thrown. We should probably check on null here.
Source:
public void saveSMA(IAtsChangeSet changes) { super.saveSMA(changes); try { ActionArtifact parentAction = getParentActionArtifact(); if (parentAction != null) { ActionArtifactRollup rollup = new ActionArtifactRollup(parentAction); rollup.resetAttributesOffChildren(); changes.add(parentAction); } } catch (Exception ex) { OseeLog.log(Activator.class, OseeLevel.SEVERE_POPUP, "Can't reset Action parent of children", ex); } }

Target:
If the parent is null, this does nothing and the caller/log gets no indication that there was a problem. Is this desired?
Source:
public List getArquivosOriginais() { return arquivosIniciais; }

Target:
usar generics no tipo de retorno
Source:
private static long combineFilters(long[] filters) { if (filters == null) { return 0; } int combined = 0; for (int i = 0; i < filters.length; i++) { combined |= filters[i]; } return combined; }

Target:
nit ```java for (long filter : filters) { combined |= filter; }
Source:
private boolean matchExpressionAndColumnRef(AbstractExpression statementExpr, ColumnRef indexColRef, StmtTableScan tableScan) { if (statementExpr instanceof TupleValueExpression) { TupleValueExpression tve = (TupleValueExpression)statementExpr; if (tve.getTableAlias().equals(tableScan.getTableAlias()) && tve.getColumnName().equals(indexColRef.getColumn().getTypeName())) { // NB: m_emptyBindings is a null list. That means // we matched, but with no bindings. return true; } } return false; }

Target:
Extra whitespace forming neat little columns makes the code arguably HARDER to read and inarguably harder to write and maintain -- turning future single-line changes into multi-line mostly whitespace changes , so PLEASE DESIST.
Source:
public static void log(Throwable e) { log(new Status(IStatus.ERROR, PLUGIN_ID, IStatus.OK, e.getLocalizedMessage(), e)); }

Target:
Why localized? We usually don't localize log message, if somebody gets a translated IOException in the log would be hard to understand later when they submit the bug
Source:
private boolean isNotTimeshiftedOrHd(Channel channel) { boolean timeshifted = MoreObjects.firstNonNull(channel.getTimeshifted(), false); boolean hd = MoreObjects.firstNonNull(channel.getHighDefinition(), false); return !(timeshifted || hd); }

Target:
You can use Boolean.TRUE.equals(obj) if you want, though it's less explicit, so I don't mind :-)
Source:
default CacheContainerAdmin administration() { throw new UnsupportedOperationException(); }

Target:
So we lose the typing on `CacheContainerAdmin`, should we define that on this method or as a generic on `CacheContainer` at least?
Source:
public RegistrationData findByToken(Context context, String token) throws SQLException { CriteriaBuilder criteriaBuilder = getCriteriaBuilder(context); CriteriaQuery criteriaQuery = getCriteriaQuery(criteriaBuilder, RegistrationData.class); Root<RegistrationData> registrationDataRoot = criteriaQuery.from(RegistrationData.class); criteriaQuery.select(registrationDataRoot); criteriaQuery.where(criteriaBuilder.equal(registrationDataRoot.get(RegistrationData_.token), token)); return uniqueResult(context, criteriaQuery, true, RegistrationData.class, -1, -1); }

Target:
Original query was not cacheable. This one is. I think the third param should be false.
Source:
public static void setReindexOnConfigChange(IProject project, boolean shouldReindexOnConfigChange) { if (shouldReindexOnConfigChange != getReindexOnConfigChange(project)) { getProjectPreferences(project).putBoolean(KEY_REINDEX_ON_CONFIG_CHANGE, shouldReindexOnConfigChange); CCoreInternals.savePreferences(project, true); } }

Target:
Saving preferences inside a setter is not appropriate. Please follow the pattern used for other preferences.
Source:
public void beforeBlockElement(ProgramState currentState, Tree element) { T tree = getTree(element); if (tree != null) { boolean isProblem = isProblem(tree, currentState); if (!isProblem) { problemMap.put(tree, true); } else if (!problemMap.containsKey(tree)) { problemMap.put(tree, false); } } }

Target:
@vilchik-elena It looks like problemMap is actually a noProblemMap. Suggestion: invert the meaning of the Boolean: true for problem, false for no problem.
Source:
public String toString() { return toStringHelper(this) .omitNullValues() .add("outputSymbolAliases", this.outputSymbolAliases) .add("expectedOutputSymbolCount", expectedOutputSymbolCount) .add("expectedRows", expectedRows) .toString(); }

Target:
extra `this.`
Source:
public void testSinglePartUnknownEncoding_throwsUnsupportedEncodingException() throws Exception { MimeMessage msg = parseWithoutRecurse(toStream( "From: <adam@example.org>\r\n" + "To: <eva@example.org>\r\n" + "Subject: Testmail\r\n" + "MIME-Version: 1.0\r\n" + "Content-type: text/plain\r\n" + "Content-Transfer-Encoding: utf-8\r\n" + "\r\n" + "dGhpcyBpcyBzb21lIG1vcmUgdGVzdCB0ZXh0Lg==\r\n")); checkAddresses(msg.getFrom(), "adam@example.org"); checkAddresses(msg.getRecipients(RecipientType.TO), "eva@example.org"); streamToString(MimeUtility.decodeBody(msg.getBody())); }

Target:
These two checks seem unrelated to the actual check you want to perform.
Source:
public UpdateSite createDefaultUpdateSite() { return new UpdateSite(PREDEFINED_UPDATE_SITE_ID, config.getUpdateCenterUrl() + "update-center.json"); }

Target:
I'd make this `protected`.
Source:
private void assertCorrectGetManagedInterfaceForVdsResult(VdsNetworkInterface result) { assertNotNull(result); assertTrue(result.getIsManagement()); }

Target:
You can make this method private
Source:
public static RequestControlAdminRequest readFrom(DataInputStream stream, AdminRequest adminRequest) throws IOException { Short versionId = stream.readShort(); if (!versionId.equals(VERSION_V1)) { throw new IllegalStateException("Unrecognized version for RequestControlAdminRequest: " + VERSION_V1); } RequestOrResponseType requestType = RequestOrResponseType.values()[stream.readShort()]; boolean enable = stream.readByte() == 1; return new RequestControlAdminRequest(requestType, enable, adminRequest); }

Target:
Define a constant for `1`?
Source:
public void buildDependencyGraph(AbstractProject owner, DependencyGraph graph) { // Can only add dependencies in Hudson 1.341 or higher if (!canDeclare(owner)) return; for (BuildTriggerConfig config : configs) { List<AbstractProject> projectList = Util.filter(config.getProjectList(owner.getParent(), null), AbstractProject.class); for (AbstractProject project : projectList) ParameterizedDependency.add(owner, project, config, graph); } }

Target:
Are you expecting to get Workflow jobs here? If so, I think it will not work.
Source:
public DAnalysis getDAnalysis() { DAnalysis dAnalysis = null; DRepresentation representation = getRepresentation().get(); DRepresentationDescriptor representationDescriptor = new DRepresentationQuery(representation).getRepresentationDescriptor(); EObject rootContainer = EcoreUtil.getRootContainer(representationDescriptor, false); if (rootContainer instanceof DAnalysis) { dAnalysis = (DAnalysis) rootContainer; } return dAnalysis; }

Target:
This method returns an Option<DRepresentation>, so the API clearly says it can be null. You must check 'if getRepresentation().some()" before.
Source:
public ASTNode(HasLocation hasLocation) { this(hasLocation.getLocation()); metadataSet = new HashSet<>(); }

Target:
Unnecessary; the call to this(...) does it
Source:
public synchronized void dispose() { for (Entry<String, IObservableValue> entry : expressionMap.entrySet()) { entry.getValue().dispose(); } super.dispose(); }

Target:
You should also clear the map. The EMF observable value holds the EObject after even after disposal which may prevent the GC to collect the model if this observable is retained. For similar reasons, please set 'match' to null here.
Source:
private void visitParameterDef(DetailAST parameterDef) { final DetailAST grandParentAST = parameterDef.getParent().getParent(); if (grandParentAST.getType() == TokenTypes.METHOD_DEF && isCheckedMethod(grandParentAST) && isVerifiable(grandParentAST) && !AnnotationUtil.containsAnnotation(grandParentAST, "Override")) { checkClassName(parameterDef); } }

Target:
As discussed in main issue, this should be in the check for the entire method. Maybe this should be moved to the `isCheckedMethod` method?
Source:
public static boolean hasPushStatusBug(int[] version) { int cmp = compare(version, v1_7_8_6); if (cmp < 0) return true; // Everything before 1.7.8.6 is known broken. else if (cmp == 0) return false; // 1.7.8.6 contained the bug fix. if (compare(version, v1_7_9) <= 0) return true; // 1.7.9 shipped before 1.7.8.6 and has the bug. return false; // 1.7.9.1 and later are fixed. }

Target:
The implementation can just "return false".
Source:
protected void addListeners() { this.resourceSetListener = new UpdateTableContentListener(getTableManager(), this); getTableEditingDomain().addResourceSetListener(this.resourceSetListener); }

Target:
Why removing the NPE check?
Source:
public static ExpectedCondition<WebDriverElement> visible(final Hook hook) { return new ExpectedCondition<WebDriverElement>() { @Override public WebDriverElement apply(WebDriver driver) { try { WebElement element = findElement(hook, driver); return element.isDisplayed()? createWebDriverElement(hook, element, driver) : null; } catch (CandybeanException e) { return null; } catch (StaleElementReferenceException e) { return null; } } @Override public String toString() { return "visibility of " + hook; } }; }

Target:
Let's use multi-catch here.
Source:
public ApplicationListener<?> xdInitializer(ApplicationContext context) { XdConfigLoggingInitializer delegate = new XdConfigLoggingInitializer(true); delegate.setEnvironment(context.getEnvironment()); if (zooKeeperConnection != null) { delegate.setZkConnectString(zooKeeperConnection.getClient().getZookeeperClient().getCurrentConnectionString()); } return new SourceFilteringListener(context, delegate); }

Target:
Not really the fault of this PR, but it feels really weird to have everything in the Environment **except** the zk connection string
Source:
public String[] getCodecs() { return this.codecs.toArray(new String[]{}); }

Target:
specify array length (based on codecs.size) to optimize. http://stackoverflow.com/a/5982478/4142153