auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected boolean copyObject(String src, String dst) { try { LOG.info("Copying to {}", src, dst); mClient.copyObject(mBucketNameInternal, src, mBucketNameInternal, dst); return true; } catch (CosClientException e) { LOG.error("Failed to rename file to {}", src, dst, e); return false; } }

Target:
`LOG.debug` please to avoid overhead on operations.
Source:
public RepositorySearchDialog(Collection<String> existingDirs) { this(existingDirs, false, false); }

Target:
Since the logic switch, this should be true (former behavior).
Source:
public DelegatingResourceDescription getCreatableProperties() { DelegatingResourceDescription description = super.getCreatableProperties(); description.addProperty("name"); description.addProperty("location"); description.addProperty("description"); return description; }

Target:
Aren't the name and description properties already added by the super class?
Source:
private JsonParser getParser(String data) throws IOException { // If the first character is { or [, assume this is // JSON data and use a JsonParser. Otherwise assume // YAML and use a YAMLParser. Character firstChar = data.charAt(0); if (firstChar == '{' || firstChar == '[') { return this.jsonFactory.createParser(data); } else { return this.yamlFactory.createParser(data); } }

Target:
Character should be "char" https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#charAt(int) This is returning a char (primitive type) and that is why the "=="test works I think, if it was returning Character (object wrapper for char) we would need to use ".equals"
Source:
public void testGenerateDroolsTestOption() { ScoreDirectorFactoryConfig config = new ScoreDirectorFactoryConfig(); assertThat(config.isGenerateDroolsTestOnError()).isNull(); config.setGenerateDroolsTestOnError(true); assertThat((boolean) config.isGenerateDroolsTestOnError()).isTrue(); config.setGenerateDroolsTestOnError(Boolean.FALSE); assertThat((boolean) config.isGenerateDroolsTestOnError()).isFalse(); config.setGenerateDroolsTestOnError(null); assertThat(config.isGenerateDroolsTestOnError()).isNull(); }

Target:
Redundant cast.
Source:
private RawText getRawText(ObjectId id, Repository repo) throws IOException { if (id.equals(ObjectId.zeroId())) return new RawText(new byte[] {}); return new RawText(repo.openBlob(id).getCachedBytes()); }

Target:
Style-nit: Use curly brackets and wrap the return to next line.
Source:
private static String getUserAgentSuffix() { String suffix = ";" + USER_AGENT_SUFFIX; return suffix; }

Target:
We can make this inline. ```suggestion return ";" + USER_AGENT_SUFFIX; ```
Source:
public Builder setDataSize(Estimate dataSize) { this.dataSize = requireNonNull(dataSize, "dataSize can not be null"); return this; }

Target:
you don't validate in other builders method (and you don't have to)
Source:
public boolean isExpired(Date invocationDate) { if (getExpires() != null) { Date currentInvocationDate = invocationDate == null ? new Date() : invocationDate; return getExpires().before(currentInvocationDate); } return false; }

Target:
Statement can be rewritten inline.
Source:
public void stop() { if (isRunning()) { process.destroy(); try { if (stdout !=null) { stdout.close(); } if (stdin !=null) { stdin.close(); } } catch (IOException e) { throw new RuntimeException(e.getMessage(),e); } finally { running.set(false); } } }

Target:
Is this really needed?
Source:
public boolean equals(Object object) { if (object == null || object.getClass() != getClass()) { return false; } if (object == this) { return true; } MacroId rhs = (MacroId) object; return new EqualsBuilder() .append(getId(), rhs.getId()) .append(getSyntax(), rhs.getSyntax()) .isEquals(); }

Target:
Actually since MacroId is not really supposed to be extended you could replace this with a `if (!(object instanceof MacroId))`. Can't be null if it's an instance of MacroId. Also I would put it after the `if (object == this)` test instead of before.
Source:
Map<String, Object> getExtraInformation() { return extraInformation; }

Target:
this is public API, we can't lower the visibility without deprecating first
Source:
public int hashCode() { return Objects.hash(pointer, ownerName, owner, readers, writers); }

Target:
neat.
Source:
private String getFriendsPath( SourcePathResolver sourcePathResolver, ImmutableList<SourcePath> friendPathsSourcePaths) { // https://youtrack.jetbrains.com/issue/KT-29933 ImmutableSortedSet<String> absoluteFriendPaths = ImmutableSortedSet.copyOf( friendPathsSourcePaths .stream() .map(path -> sourcePathResolver.getAbsolutePath(path).toString()) .collect(Collectors.toSet())); return "-Xfriend-paths=" + absoluteFriendPaths.stream().reduce("", (path1, path2) -> path1 + "," + path2); }

Target:
What about the same when the list is empty, it still adds `-Xfriend-paths=` option?
Source:
public Target(String targetUriAsString) { super(); Assert.hasText(targetUriAsString, "The provided targetUriAsString must neither be null nor empty."); this.targetUri = URI.create(targetUriAsString); }

Target:
Do we need super(), if the class is not inheriting from a super class?
Source:
public PropertyInvertedRegexTester(IPersonAttributesGroupTestDefinition definition) { super(definition); final String propertyName = definition.getTestValue(); String regexExpression = PropertiesManager.getProperty (propertyName, ""); if (StringUtils.isBlank(regexExpression)) { logger.error("Unable to find property name in portal.properties or has empty value." + " PAGS PropertyInvertedRegexTester will always return true for attribute {}", propertyName, definition.getAttributeName()); } setPattern(regexExpression); }

Target:
Minor, but rather than duplicating lines 44 - 51, perhaps put them in a private method invoked by both constructors, or have this constructor invoke the other.
Source:
public final boolean doesProvideNewPage() { if (provision == null) { throw new IllegalStateException("Page instance not yet resolved"); } return getProvision().doesProvideNewPage(); }

Target:
Looking bad indeed, I fixed later during my work on the branch: https://github.com/apache/wicket/pull/210/commits/b64f2b4b2cb50a594cabb50a0c1eeca43485f6b9#diff-36b11db0d92a540368a080c520de953aL177 The three states looks overcomplicated. There's no place in Wicket core needing to test such flag for the value "OLD".
Source:
private Handler getHandler() { if (mHandler == null) { // Use current main looper mHandler = new Handler(mContext.getMainLooper()); } return mHandler; }

Target:
This doesn't look thread-safe.
Source:
@SuppressWarnings("UnusedDeclaration") @Deprecated public void setDebugging(boolean debugging) { setIndicatorsEnabled(debugging); setLoggingEnabled(debugging); }

Target:
Let's remove this behavior. `setDebugging` will only affect the indicators.
Source:
public List<ServerTemplate> load() { synchronized (store) { return store.values().stream().map(e -> cloneServerTemplate(e)).collect(Collectors.toList()); } }

Target:
I guess we no longer need `store` to be of `ConcurrentHashMap` implementation if we are fully locking it.
Source:
public String getLearnerMaster() { QuorumPeer.QuorumServer learnerMaster = observer.getCurrentLearnerMaster(); InetSocketAddress address = learnerMaster.addr.getReachableOrOne(); if (learnerMaster == null || address == null) { return "Unknown"; } return address.getAddress().getHostAddress() + ":" + address.getPort(); }

Target:
if `learnerMaster` is `null` here then you'll get a NPE on the `learnerMaster.addr.getReachableOrOne()` above.
Source:
default <R> Task<R> flatMap(final String desc, final Function1<? super T, Task<R>> func) { ArgumentUtil.requireNotNull(func, "function"); final Task<Task<R>> nested = map("map: " + desc, func); nested.getShallowTraceBuilder().setSystemHidden(true); nested.getShallowTraceBuilder().setTaskType("nestedTask"); return flatten(desc, nested); }

Target:
I think we should drop redundant "Task" suffix from the task types e.g.: "nestedTask" -> "nested" "withSideEffectTask" -> "withSideEffect" "timeoutTask" -> "timeout" "withTimeoutTask" -> "withTimeout"
Source:
protected List<String> findStringsInFileCommon(String regexp, boolean stopOnFirst, int searchLimit, File fileToSearch) throws Exception { return findStringsInFileCommon(regexp, stopOnFirst, searchLimit, fileToSearch, Project.MSG_INFO); }

Target:
As stated above, I don't see the need for this method to throw an exception.
Source:
public void notifyAboutStartProcess(String id) { Long processInstanceId = Long.parseLong(id); newProcessInstanceEvent.fire(new NewProcessInstanceEvent(serverTemplateId, deploymentId, processInstanceId, processDefId, processName, 1)); final String message = Constants.INSTANCE.ProcessStarted(processInstanceId.longValue()); notificationEvent.fire(new NotificationEvent(message, NotificationEvent.NotificationType.SUCCESS)); close(); }

Target:
can you pass null in here for the status, I recently refactored similar code, and status should not be part of the event.
Source:
protected void process(final SpaceReference source, final SpaceReference destination) { visitDocuments(source, new Visitor<DocumentReference>() { @Override public void visit(DocumentReference oldChildReference) { DocumentReference newChildReference = oldChildReference.replaceParent(source, destination); if (MoveJob.this.hasAccess(Right.VIEW, newChildReference)) { maybeMove(oldChildReference, newChildReference); } } }); }

Target:
I don't understand what this check is doing here. maybeMove is already taking check of checking rights.
Source:
public void processEvent(DiscoveryServiceEvent event) throws LogReplicationDiscoveryServiceException { log.info("Process event {}", event.getType()); switch (event.type) { case DISCOVER_INIT_TOPOLOGY: startDiscovery(); break; case ACQUIRE_LOCK: processLockAcquire(); break; case RELEASE_LOCK: processLockRelease(); break; case DISCOVERED_TOPOLOGY: processTopologyChangeNotification(event); break; case UPGRADE: processUpgrade(event); break; default: log.error("Invalid event type {}", event.type); } }

Target:
same, we can delete LogReplicationDiscoveryServiceException.java file now.
Source:
public void deleteError(final ProgramError error) { synchronized (errors) { errors.remove(error); eventBus.publish(new ProgramErrorDeletedEvent(error)); } }

Target:
Don't really like firing events when holding locks on things... If anything that receives a ProgramErrorDeletedEvent tries to access the ErrorManager (which is not altogether unreasonable!) you'll end up with a nasty deadlock. Could we just make errors a ConcurrentSkipListSet and drop all the synchronization?
Source:
public LamiTableContentProvider() { fCurrentEntries = checkNotNull(Collections.emptyList()); }

Target:
Can remove checkNotNull, we have external @NonNull annotation on Collections.emptyList().
Source:
public ArticlePageObject clickGetInfoLink() { switchToIFrame(); waitForElementByElement(getInfoLink); //Opens new tab to Template namespace getInfoLink.click(); switchOutOfIFrame(); return new ArticlePageObject(driver); }

Target:
in case of switching, in my opinion it's better to us etry/finnally like that: ``` switchToIFrame(); try { waitForElementByElement(getInfoLink); //Opens new tab to Template namespace getInfoLink.click(); return new ArticlePageObject(driver); }finally { switchOutOfIFrame(); } ``` it's clearer in reading
Source:
@Test public void decorateSimpleRabbitListenerContainerFactory_appends_as_first_when_absent() { SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory(); factory.setAdviceChain(new CacheInterceptor()); assertThat(rabbitTracing.decorateSimpleRabbitListenerContainerFactory(factory).getAdviceChain()) .hasSize(2) .matches(adviceArray -> asList(adviceArray).get(0) instanceof TracingRabbitListenerAdvice); }

Target:
would this work? (also removing the import) ```suggestion .matches(adviceArray -> adviceArray[0] instanceof TracingRabbitListenerAdvice); ```
Source:
private static List<IResource> getReadonlyFiles(IResource[] resources) { List<IResource> readOnlyFiles= new ArrayList<IResource>(); for (int i= 0; i < resources.length; i++) { IResource resource= resources[i]; ResourceAttributes resourceAttributes= resource.getResourceAttributes(); if (resource.getType() == IResource.FILE && resourceAttributes != null && resourceAttributes.isReadOnly()) readOnlyFiles.add(resource); } return readOnlyFiles; }

Target:
Use ArrayList<>
Source:
void clean(K key) { List<V> data = getDataMap().get(key); if (data != null) { data.clear(); } getDataMap().remove(key); }

Target:
I think this is not necessary as the GC will remove it as soon as there is no more reference on the Object
Source:
public static boolean isMemoryDeviceHotUnpluggable(VmDevice memoryDevice) { if (!isMemory(memoryDevice)) { throw new RuntimeException("Memory device expected but device " + memoryDevice + " obtained."); } return getSpecParamsIntValue(memoryDevice, SPEC_PARAM_SIZE).isPresent() && getSpecParamsIntValue(memoryDevice, SPEC_PARAM_NODE).isPresent(); }

Target:
IllegalArgumentException sounds better here.
Source:
public boolean connectorExists(String id) { try { List<ConnectorConfiguration> list = configPersistence.load(ImmutableMap.of(Constants.CONNECTOR_PERSISTENT_ID, id)); if (list.isEmpty()) { return false; } return true; } catch (PersistenceException e) { throw new RuntimeException(e); } }

Target:
Would be nice if you add here an exception text. Something like "unable to load the list of connector configurations"
Source:
public void testUpdateStmtBuilder() { printStatement("update foo set \"column['looks_like_nested']\"=1"); printStatement("update foo set foo.a='b'"); printStatement("update bar.foo set bar.foo.t=3"); printStatement("update foo set col['x'] = 3"); printStatement("update foo set col['x'] = 3 where foo['x'] = 2"); printStatement("update schemah.foo set foo.a='b', foo.b=foo.a"); printStatement("update schemah.foo set foo.a=abs(-6.3334), x=true where x=false"); printStatement("update foo set foo='a' returning id"); printStatement("update foo set foo='a' where x=false returning id"); printStatement("update foo set foo='a' returning id AS foo"); printStatement("update foo set foo='a' returning id + 1 AS foo, id -1 as bar"); }

Target:
can we maybe have separate test cases for the returning clause?
Source:
public void setSetPath(String path) { setPath.set(requireNonNull(path, "path is null")); }

Target:
nit: I know that in other parts of this class we put the requireNonNull calls inside another method call, but let's not do it here for the sake of slightly better readability: ``` requireNonNull(path, "path is null"); setPath.set(path); ```
Source:
public EnvVars getEnvironment() throws IOException, InterruptedException { if (cachedEnvironment != null) { return cachedEnvironment; } cachedEnvironment = EnvVars.getRemote(getChannel()); return cachedEnvironment; }

Target:
Something like this: ``` public EnvVars getEnvironment() throws IOException, InterruptedException { EnvVars cachedEnvironment = this.cachedEnvironment; if (cachedEnvironment != null) { return cachedEnvironment; cachedEnvironment = EnvVars.getRemote(getChannel()); // all non-null values should be equivalent so in a race it doesn't matter who wins this.cachedEnvironment = cachedEnvironment; return cachedEnvironment; } ```
Source:
public int getMaxCapacity() { readLock.lock(); try { return maxCapacity; } finally { readLock.unlock(); } }

Target:
why should add lock here?
Source:
public void testGetAllForVdsGroupWithPermissionsForUnpriviligedUser() { List<VDS> result = dao.getAllForVdsGroup(existingVds.getvds_group_id(), UNPRIVILEGED_USER_ID, true); assertNotNull(result); assertTrue(result.size() == 0); }

Target:
Can you use isEmpty()?
Source:
private static DataSource createC3P0DataSource(String name, Map<Object, Object> properties) { ComboPooledDataSource ds = new ComboPooledDataSource(false); ds.setDataSourceName(name); ds.setIdentityToken(name); new BeanMap(ds).putAll(properties); C3P0Registry.reregister(ds); try { checkDataSource(ds, name); } catch (SQLException e) { throw new RuntimeException("Failed check data source", e); } return ds; }

Target:
Я еще люблю в сообщение вставлять изначальный exception, nипа "Failed to check data source " + e.toString(), e).
Source:
protected Control createPageControls(Composite parent) { setTitle(Messages.RemoveReviewerDialog_Remove_Reviewer); Label label = new Label(parent, SWT.CENTER); label.setText( NLS.bind(Messages.RemoveReviewerDialog_Are_You_Sure_You_Want_To_Remove, userToRemove.getDisplayName())); return parent; }

Target:
no need to center it, just give it SWT.NONE
Source:
public List<PermissionSubject> getPermissionCheckSubjects() { List<PermissionSubject> list = new ArrayList<PermissionSubject>(); Guid storagePoolId = getVdsGroup() == null || getVdsGroup().getstorage_pool_id() == null ? null : getVdsGroup().getstorage_pool_id().getValue(); list.add(new PermissionSubject(storagePoolId, VdcObjectType.StoragePool, getActionType().getActionGroup())); QuotaHelper.addQuotaPermissionSubject(list, getStoragePool(), getQuotaId()); return list; }

Target:
I think you need to call super otherwise you loose the permissions that you need to check by default.
Source:
public void onInit( String clientName, Map<String,Object> credentials ) throws IOException { packer.packStructHeader( 1, INIT.signature() ); packer.pack( clientName ); packer.pack( ValueUtils.asMapValue( credentials ) ); onMessageComplete.onMessageComplete(); }

Target:
This is actually wrong but it is an error that has propagated to all drivers. The init struct has size 2 and not size 1. We are saved by ignoring the struct size when we read the init message.
Source:
public SecurityGroupExtensionProvider(NeutronSecurityGroupExtension neutronSecurityGroupExtension, NovaSecurityGroupExtension novaSecurityGroupExtension) { this.neutronSecurityGroupExtension = neutronSecurityGroupExtension; this.novaSecurityGroupExtension = novaSecurityGroupExtension; }

Target:
Remove the public modifier
Source:
private static ExpressionTree getComparedWithNullExpression(ExpressionTree expression, Tree.Kind kind) { ExpressionTree comparedExpression = getExpressionEqualNullWithAnd(expression, kind); if (comparedExpression == null) { comparedExpression = getExpressionNotEqualNullWithOr(expression, kind); if (comparedExpression == null) { comparedExpression = getExpressionComparedWithFunction(expression, kind); if (comparedExpression == null) { return null; } } } return comparedExpression; }

Target:
@vilchik-elena Do we need this block?
Source:
private void scheduleRefresh(Duration delay) { // already stopped? avoids rejection exception if (executor.isShutdown()) { return; } executor.schedule((Runnable) this::refresh, delay.toMillis(), TimeUnit.MILLISECONDS); }

Target:
Is the `(Runnable)` needed?
Source:
public static void main(String[] args) { LocalQueryRunner queryRunner = createLocalQueryRunner(ImmutableMap.of("reorder_joins", "false")); new SqlConsecutiveJoinBenchmark(queryRunner).runBenchmark(new SimpleLineBenchmarkResultWriter(System.out)); }

Target:
Technically, you should `queryRunner.close()` (or t-w-r). This would ensure proper cleanup of any temp files (or whatevers) it might have created
Source:
public void beforeStartingVertx(VertxOptions options) { }

Target:
Shouldn't they be protected not public?
Source:
public Builder body(String json) { checkNotNull(json, "body required"); checkArgument(json.getBytes().length <= getInteger(MESSAGE_BODY_MAX_IN_BYTES), "json size must be <= %s bytes", getInteger(MESSAGE_BODY_MAX_IN_BYTES)); this.body = new JsonBall(json).toString(); return self(); }

Target:
Ah, so I guess that lack of a Guice context here (and above) is the reason for the system properties? How do we solve that elsewhere in jclouds? Would we inject some kind of factory object via Guice?
Source:
private String getTokenFromHeader(HttpServletRequest request) { String token = null; String headerValue = request.getHeader(SsoConstants.HEADER_AUTHORIZATION); if (headerValue != null && headerValue.startsWith(BEARER)) { token = headerValue.substring("Bearer".length()).trim(); } return token; }

Target:
s/"Bearer"/BEARER
Source:
public static CDIProvider getCDIProvider() { if (configuredProvider != null) { return configuredProvider; } else { // Discover providers and cache if (discoveredProviders == null) { synchronized (lock) { if (discoveredProviders == null) { findAllProviders(); } } } configuredProvider = discoveredProviders.stream() .filter(c -> c.getCDI() != null) .findAny().orElseThrow(() -> new IllegalStateException("Unable to access CDI")); return configuredProvider; } }

Target:
This method should not be public or what's the point?
Source:
public void testIsDrawable_Stage() throws Exception { testIsDrawable(CaseManagementDiagram.class, AdHocSubprocess.class, true); }

Target:
The Exception is never thrown.
Source:
public static boolean customImageExists(String storage, String key) { final AzureBlobClient azureBlob = ContextBuilder.newBuilder("azureblob") .credentials(storage, key) .buildApi(AzureBlobClient.class); try { return azureBlob.containerExists("system"); } catch (Exception e) { e.printStackTrace(); return false; } finally { Closeables2.closeQuietly(azureBlob); } }

Target:
The container exists method should already return false [if the container exists call returns a 404](https://github.com/jclouds/jclouds/blob/master/providers/azureblob/src/main/java/org/jclouds/azureblob/AzureBlobClient.java#L156). Worth removing the catch, as it might be caused by other errors that should be taken into acount?
Source:
public void enter() { mUseEap = (IkeSessionOptions.IKE_AUTH_METHOD_EAP == mIkeSessionOptions.getLocalAuthConfig().mAuthMethod); super.enter(); }

Target:
Nit: By convention, this is almost always the first thing called, unless there's a explicit reason why it needs to happen after (which is usually a code smell)
Source:
public static Predicate<Expression> isInferenceCandidate() { return expression -> { expression = normalizeInPredicateToEquality(expression); if (expression instanceof ComparisonExpression && DeterminismEvaluator.isDeterministic(expression) && !NullabilityAnalyzer.mayReturnNullOnNonNullInput(expression) && !isDynamicFilter(expression)) { ComparisonExpression comparison = (ComparisonExpression) expression; if (comparison.getType() == ComparisonExpressionType.EQUAL) { // We should only consider equalities that have distinct left and right components return !comparison.getLeft().equals(comparison.getRight()); } } return false; }; }

Target:
you can static import these functions.
Source:
public void startMasters() throws Exception { mMaster = LocalAlluxioMaster.create(mWorkDirectory, true); mMaster.start(); CommonUtils.PROCESS_TYPE.set(CommonUtils.ProcessType.CLIENT); }

Target:
why is this needed?
Source:
public Proxy getProxy() { if (mProxyHost == null) return null; Proxy.Type type = null; switch (mProxyType) { case TYPE_HTTP: type = Proxy.Type.HTTP; break; case TYPE_SOCKS: type = Proxy.Type.SOCKS; break; } return new Proxy(type, new InetSocketAddress(mProxyHost, mProxyPort)); }

Target:
mind the code style
Source:
public HttpRequest setMethod(HttpMethod method) { ObjectUtil.checkNotNull(method, "method"); this.method = method; return this; }

Target:
nit: you can merge both lines above as `checkNotNull` will return the given argument
Source:
public Set<VmDeviceGeneralType> getDeviceTypesWithProperties(Version version) { if (!FeatureSupported.deviceCustomProperties(version)) { return Collections.emptySet(); } Set<VmDeviceGeneralType> types; EnumMap<VmDeviceGeneralType, Map<String, Pattern>> map = deviceProperties.get(version); if (map.isEmpty()) { // no device type has any properities types = Collections.emptySet(); } else { // prevent client to modify types = Collections.unmodifiableSet(map.keySet()); } return types; }

Target:
a matter of taste - types can be avoided for the sake of return statements from the if-else block.
Source:
public SWTBotSiriusDiagramEditor(final IEditorReference reference, final SWTWorkbenchBot bot) throws WidgetNotFoundException { super(reference, bot); GraphicalViewer graphicalViewer = UIThreadRunnable.syncExec(new Result<GraphicalViewer>() { @Override public GraphicalViewer run() { final IEditorPart editor = partReference.getEditor(true); return editor.getAdapter(GraphicalViewer.class); } }); ReflectionHelper.setFieldValueWithoutException(this, "viewer", new SWTBotSiriusGefViewer(graphicalViewer), this.getClass().getSuperclass()); }

Target:
generic has come with mars. Consequently that code won't compile against previous platform
Source:
public CreateAllSnapshotsFromVmParameters() { needsLocking = true; snapshotType = SnapshotType.REGULAR; saveMemory = true; diskIdsToIgnoreInChecks = Collections.emptySet(); }

Target:
I'd prefer that we handled it (the snapshot type) in a separate change.
Source:
public SchedulerTask<?> createTaskInstance( String taskType ) throws IllegalArgumentException { try { return lookupTask( taskType ); } catch ( ComponentLookupException e ) { this.logger.debug( "Failed to load Schedule Task: " + taskType, e ); throw new IllegalArgumentException( "Could not create task of type" + taskType, e ); } }

Target:
afacit vvv is all noise
Source:
public PapyrusStereotypedElementItemProviderDecorator(ComposeableAdapterFactory adapterFactory) { super(adapterFactory); labelProviderService = new LabelProviderServiceImpl(); try { labelProviderService.startService(); } catch (ServiceException ex) { Activator.getDefault().getLog().log( new Status(IStatus.WARNING, Activator.PLUGIN_ID, "Unable to start Papyrus Label Provider Service", ex)); //$NON-NLS-1$ } }

Target:
It worries me a bit to imagine that _each_ decorator will start its own service (whatever that means, I'm not familiar with papyrus services) Can you check whether this is a common way of using services? Would it be possible to share a common instance somehow between decorators?
Source:
default SourceMap sourceMap() { return null; }

Target:
Why not rely on `Optional`, rather than introducing another method which could lead to NPEs?
Source:
public static void setupDefaultTestCluster() throws Exception { config = DrillConfig.create(cloneDefaultTestConfigProperties()); classpathScan = ClassPathScanner.fromPrescan(config); openClient(); // turns on the verbose errors in tests // sever side stacktraces are added to the message before sending back to the client test("ALTER SESSION SET `exec.errors.verbose` = true"); emptyDirCreating(); }

Target:
Why do we create empty directory for all tests that extend this class? I guess need to create it only for those tests that need it.
Source:
private static String parseAnnotationFieldTypeName(final Supplier<Class<?>> theTypeSupplier, final String errorMessage) { try { theTypeSupplier.get(); throw new RuntimeException(errorMessage); } catch (MirroredTypeException mte) { return mte.getTypeMirror().toString(); } }

Target:
As I am looking at the code, this is not necessary wrong, but maybe it would be better to throw new RuntimeException() in the end of the method. It's up to you what do you prefer.
Source:
default StreamPriority getStreamPriority() { return StreamPriority.DEFAULT; }

Target:
return `null` instead when there is no priority
Source:
protected void configure() { bind(EventDao.class).to(EventDaoInMemory.class).asEagerSingleton(); bind(Bootstrap.class); }

Target:
?? Pourquoi cette ligne. Bootstrap est déjà une classe concrète...
Source:
public static void onAdvancementEvent(AdvancementEvent event) { if (ENABLED && event.getAdvancement().getDisplay() != null && event.getAdvancement().getDisplay().shouldAnnounceToChat()) { logger.info("{} got the advancement", event.getEntityPlayer().getDisplayNameString(), event.getAdvancement().getDisplayText().getUnformattedText()); } }

Target:
Second `ENABLED` check is not necessary if you have the first one.
Source:
public ExampleEndpointsProvider() { // Put custom code here to get endpoints // In our case they will be hardcoded try { JHttpEndpoint httpEndpoint = new JHttpEndpoint(new URI("https://jagger.griddynamics.net:443")); endpoints.add(httpEndpoint); } catch (URISyntaxException e) { throw new IllegalStateException(e); } }

Target:
let's use URI.create and avoid try/catch
Source:
public SlackUserProperty() { this.userId = null; this.disableNotifications = false; }

Target:
do we need any content in this constructor at all?
Source:
public void onStreamCreate(IMediaStream stream) { if (!stream.isTranscodeResult()) { PacketListener listener = new PacketListener(); WMSProperties props = stream.getProperties(); synchronized (props) { props.setProperty(STREAM_ACTION_LISTENER_PROPERTY, listener); } stream.addLivePacketListener(listener); } }

Target:
do return
Source:
public long getEstimatedSizeInBytes() { int result = INSTANCE_SIZE; result += sizeOf(levelOffsets); result += tree.sizeOf(); for (T item : items) { result += item.getEstimatedSizeInBytes(); } return result; }

Target:
result -> size
Source:
public boolean respondsTo(RunEvent event) { Run r = event.getEventObject(); if (event.getEventType().equals(MisoEventType.RUN_FAILED) && r.getHealth().equals(HealthType.Failed)) { log.info("Run " + r.getAlias() + ": " + event.getEventMessage()); return true; } return false; }

Target:
`==` instead of `.equals` (in both instances) would make this null-safe
Source:
public boolean isEnabled() { final boolean res = super.isEnabled() || isDirty(); return res; }

Target:
en profiter pour enlever cette variable intermédiaire?
Source:
private void updateSslVerifyUser(boolean value) { StoredConfig userConfig = GlobalConfigCache.getInstance() .getUserConfig(); try { userConfig.load(); updateSslVerify(userConfig, value); } catch (IOException | ConfigInvalidException e) { // Log it, but otherwise ignore here. LOG.error(MessageFormat.format(JGitText.get().userConfigFileInvalid, userConfig, e)); } }

Target:
If I understand this change correctly, this shouldn't be needed anymore?
Source:
private boolean isUserBrickAdapter(BaseAdapter baseAdapter) { return baseAdapter instanceof UserBrickAdapter; }

Target:
this method could be static i guess? more relevant: is this method necessary? i only see one usage
Source:
private FormulaEditorFragment addResourceToActiveFormulaInFormulaEditor(CategoryListItem categoryListItem) { FormulaEditorFragment formulaEditorFragment = ((FormulaEditorFragment) getFragmentManager() .findFragmentByTag(FormulaEditorFragment.FORMULA_EDITOR_FRAGMENT_TAG)); formulaEditorFragment.addResourceToActiveFormula(categoryListItem.nameResId); return formulaEditorFragment; }

Target:
Please check if the fragment exists. It could lead to a null-pointer exception.
Source:
public final ReviewCategoryStrategy reviewCategoryStrategy() { String s = reviewCategeoryStrategyRaw(); return s != null ? ReviewCategoryStrategy.valueOf(s) : null; }

Target:
Shouldn't this return ReviewCategoryStrategy.NONE? Otherwise why do we have ReviewCategoryStrategy.NONE if null means NONE too?
Source:
public Iterable<ConnectorFactory> getConnectorFactories() { return ImmutableList.of(new HiveConnectorFactory(name, getClassLoader(), Optional.of(metastore))); }

Target:
`metastore` is nullable here
Source:
public void testDBConnectionTimeMetrics() { metrics.setDBConnectionTime(14); assertEquals(14, testUtil.getGaugeValue("dbConnectionTime")); }

Target:
Did you apply saveaction?
Source:
protected void createCacheManagers() throws Throwable { ConfigurationBuilder builder = getDefaultClusteredCacheConfig(getCacheMode(), true); builder.clustering().stateTransfer().chunkSize(200).sync().replTimeout(45, TimeUnit.SECONDS); createClusteredCaches(4, cacheName(), builder); }

Target:
I think I like 20 better, to exercise the key migration code more.
Source:
private String getByAccountName(CodeReviewCommit codeReviewCommit) { Account account = getAccount(codeReviewCommit); if (account != null && account.getFullName() != null) { return " by " + account.getUserName(); } return ""; }

Target:
getFullName()
Source:
public void findByUndefinedSchema() throws Exception { context.turnOffAuthorisationSystem(); getClient().perform(get("/api/core/metadatafields/search/bySchema") .param("schema", "undefined")) .andExpect(status().isOk()) .andExpect(content().contentType(contentType)) .andExpect(jsonPath("$.page.size", is(20))) .andExpect(jsonPath("$.page.totalElements", is(0))); }

Target:
I believe the Auth system should remain on in this method.
Source:
private void addAll(QuantileDigest digest, long... values) { requireNonNull(values, "values is null"); for (long value : values) { digest.add(value); } }

Target:
private static
Source:
protected Object encodeCommand(Command command) { initDevicePassword(command, LaipacProtocolDecoder.DEFAULT_DEVICE_PASSWORD); switch (command.getType()) { case Command.TYPE_CUSTOM: return formatCommand(command, "{%s}", Command.KEY_DATA); case Command.TYPE_POSITION_SINGLE: return formatCommand(command, "AVREQ,{%s},1", Command.KEY_DEVICE_PASSWORD); case Command.TYPE_REBOOT_DEVICE: return formatCommand(command, "AVRESET,{%s},{%s}", Command.KEY_UNIQUE_ID, Command.KEY_DEVICE_PASSWORD); default: break; } return null; }

Target:
Move this to default.
Source:
public void close() throws IOException { if (selectObjectContentResult != null) { selectObjectContentResult.close(); selectObjectContentResult = null; selectObjectRequest = null; } }

Target:
We shouldn't need to check or clear any fields here, as `SelectObjectContentResult` is a `Closeable` which guarantees that `close()` is idempotent: > If the stream is already closed then invoking this method has no effect.
Source:
@Override public boolean isDisposed() { return inner == null; }

Target:
`get()`. (Btw since `inner` is plain, this check may end up hoisted and you'd never see it turning null).
Source:
public void close() throws IOException { if (s3Object != null) { s3Object.close(); } }

Target:
I think that we need `super.close()` here.
Source:
public void loadChunk(int x, int z) { w.loadChunk(z, z); }

Target:
(z, z) certainly doesn't look right.
Source:
public GeneratorUtil(TypeOracle typeOracle, Logger logger, GeneratorContext generatorContext) { this.typeOracle = typeOracle; this.logger = logger; this.generatorContext = generatorContext; }

Target:
rm public
Source:
protected boolean failPassthroughVnicHotPlug() { if (VmInterfaceType.pciPassthrough.equals(VmInterfaceType.forValue(getParameters().getNic().getType()))) { addCanDoActionMessage(EngineMessage.HOT_PLUG_UNPLUG_PASSTHROUGH_VNIC_NOT_SUPPORTED); return true; } return false; }

Target:
replace equals with == for enums.
Source:
public List<Map> getStageReachedCounts(Context context) throws SQLException { return workspaceItemDAO.getStageReachedCounts(context); }

Target:
It would be great if this map could use generics so we know what it contains.
Source:
Evaluator( final ObjectMapper mapper, final AsyncTaskExecutor asyncTaskExecutor, final long timeoutLength) { this.mapper = mapper; this.asyncTaskExecutor = asyncTaskExecutor; this.timeoutLength = timeoutLength; }

Target:
usually this `) {` is on the next line
Source:
public MetaMasterSync(Address masterAddress, MetaMasterMasterClient masterClient) throws IOException { // TODO(lu) should avoid throw exception in Java constructor to avoid half-baked class instances mMasterAddress = masterAddress; mMasterClient = masterClient; mHeartbeatTimeoutMs = (int) Configuration.getMs(PropertyKey.MASTER_HEARTBEAT_TIMEOUT_MS); mLastSuccessfulHeartbeatMs = System.currentTimeMillis() - mHeartbeatTimeoutMs; }

Target:
do we still need to throw exception here? if not, you can remove the next TODO
Source:
public void sendLayerDeleted(String layerName) { listeners.stream().forEachOrdered(listener->{ listener.layerDeleted(layerName); }); }

Target:
Seems me a ```` listeners.forEach(listener -> layerDeleted(layerName)); ```` would have been at the same time more compact, readable, and faster (streams are very slow)
Source:
public List<SqlIdentifier> getProjectionFields(MetadataType metadataLevel, OptionManager options) { List<SqlIdentifier> columnList = new ArrayList<>(); columnList.add(new SqlIdentifier(options.getString(ExecConstants.IMPLICIT_FQN_COLUMN_LABEL), SqlParserPos.ZERO)); columnList.add(new SqlIdentifier(options.getString(ExecConstants.IMPLICIT_LAST_MODIFIED_TIME_COLUMN_LABEL), SqlParserPos.ZERO)); return columnList; }

Target:
Please immutable collection.
Source:
protected TypedTransaction(Transaction tx, Encoder encoder, TypeLayer tl) { super((Snapshot)tx, encoder, tl); this.tx = tx; this.encoder = encoder; this.tl = tl; }

Target:
can TypedSnapshotBase constructor take SnapshotBase instead of Snapshot?
Source:
public int hashCode() { int result = name != null ? name.hashCode() : 0; result = 31 * result + (permissions != null ? permissions.hashCode() : 0); result = 31 * result + mask; return result; }

Target:
`permissions` can't be `null`, otherwise the constructor would throw a NPE.
Source:
public EEFTabbedPropertySheetPage(Object contributor, String contributorId) { if (contributor instanceof IEEFTabbedPropertySheetPageContributor) { this.contributor = (IEEFTabbedPropertySheetPageContributor) contributor; } else { this.contributor = new ContributorWrapper(contributor, contributorId); } this.registry = EEFTabbedPropertyRegistry.getDefault(this.contributor.getContributorId()); }

Target:
this.contributor
Source:
public List<String> getSuggestions(String input) { return WorldEdit.getInstance().getPlatformManager() .queryCapability(Capability.GAME_HOOKS).getWorlds().stream() .map(World::getId) .filter(world -> world.startsWith(input)) .collect(Collectors.toList()); }

Target:
You should probably extract the world-stream extraction to its own method.
Source:
protected void executeCommand() { //disconnect the connection from vdsm boolean isStorageDisconnectSucceeded = disconnectStorage(); if(isStorageDisconnectSucceeded) { String connectionId = getConnection().getid(); if(StringUtils.isNotEmpty(connectionId)) { //remove the connection record from db getDbFacade().getStorageServerConnectionDao().remove(connectionId); setSucceeded(true); } } }

Target:
I don't understand something - now we will perform the this command for one host and then the connection will be removed from db, how we will perform the disconnect for other hosts? the load of connection will return null..no? you should take care of that i guess.
Source:
public void testNotEliminateSorts() { @Language("SQL") String sql = "SELECT quantity, row_number() OVER (ORDER BY quantity) FROM lineitem ORDER BY tax"; PlanMatchPattern pattern = anyTree( sort( window(windowMatcherBuilder -> windowMatcherBuilder .specification(windowSpec) .addFunction(functionCall("row_number", Optional.empty(), ImmutableList.of())), anyTree(LINEITEM_TABLESCAN_Q)))); assertUnitPlan(sql, pattern); }

Target:
curious: why remove `anyTree`?
Source:
public Program getAssociatedProgram(Artifact artifact) { String extension = getAssociatedExtension(artifact); Program program = ProgramFinder.findProgram(extension.toLowerCase()); if (program == null) { throw new OseeArgumentException("No program associated with the extension [%s] found on your local machine.", extension); } return program; }

Target:
Perform this operation in the custom ProgramFinder.findProgram() method instead.
Source:
public final Iterable<N> toDepthFirstIterable() { return () -> AbstractTree.this.depthFirstIterator(); }

Target:
Please replace all the occurrences of `AbstractTree.this`. Indeed, the code style we are using does not recommend to add `this` as a prefix of a function call when the function is in the current object.
Source:
void put(final K key, final V value) { clusterRegistry.put(scope, key, value); System.out.println("putting key "+key+" ffrom thread "+Thread.currentThread().getName()); localCacheInsert(key, value); }

Target:
This is definitely a leftover that must be removed.
Source:
public static String getWarningMessages(String filename){ String warningMessage = ""; if (getErrorMessage(filename).length() == 0 && filename.length() > 0) { if (!filename.matches("[A-Za-z][A-Za-z0-9_]*")) { // check to make sure if filename has no spaces String errorMessage = MESSAGES.whitespaceProjectNameError(); filename = filename.replaceAll("( )+", " ").replace(" ","_"); warningMessage = errorMessage + ". \n '" + filename + "' will be used if continued."; } } return warningMessage; }

Target:
Missed a space here between the `)` and `{`
Source:
public @NonNull TraceSessionComponent[] getSessions() { List<ITraceControlComponent> compenents = getChildren(TraceSessionGroup.class); if (compenents.size() > 0) { TraceSessionGroup group = (TraceSessionGroup)compenents.get(0); List<ITraceControlComponent> sessions = group.getChildren(TraceSessionComponent.class); return sessions.toArray(new @NonNull TraceSessionComponent[sessions.size()]); } return new @NonNull TraceSessionComponent[0]; }

Target:
this doesn't seem to change anything for me?
Source:
private static void cacheColors(Display display) { BG_COLOR_RGB= JFaceColors.getInformationViewerBackgroundColor(display).getRGB(); FG_COLOR_RGB= JFaceColors.getInformationViewerForegroundColor(display).getRGB(); Color hyperlinkText= JFaceColors.getHyperlinkText(display); Color activeHyperlinkText= JFaceColors.getActiveHyperlinkText(display); if (hyperlinkText != null) { LINK_COLOR_RGB= hyperlinkText.getRGB(); } if (activeHyperlinkText != null) { ACTIVE_LINK_COLOR_RGB= activeHyperlinkText.getRGB(); } }

Target:
Minor: Move declaration before the if block where it is used?
Source:
private IRadioButton<T> findFirstButtonInFieldTree(IFormField f) { if (f instanceof IRadioButton) { return (IRadioButton<T>) f; //TODO: mnick } else if (f instanceof ICompositeField) { for (IFormField sub : ((ICompositeField) f).getFields()) { IRadioButton<T> b = findFirstButtonInFieldTree(sub); if (b != null) { return b; } } } return null; }

Target:
you can use TypeCastUtility.getGenericsParameterClass(getClass(), IHolder.class); to check the type parameter
Source:
public void testGenerateXpathSuppressionOptionEmptyConfig() throws Exception { final String expected = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<!DOCTYPE suppressions PUBLIC\n" + " \"-//Puppy Crawl//DTD Suppressions Xpath Experimental 1.2//EN\"\n" + " \"http://checkstyle.sourceforge.net/dtds/" + "suppressions_1_2_xpath_experimental.dtd\">\n" + "<suppressions>\n" + "</suppressions>\n"; exit.checkAssertionAfterwards(() -> { assertEquals("Unexpected output log", expected, systemOut.getLog()); assertEquals("Unexpected system error log", "", systemErr.getLog()); }); Main.main("-c", getPath("InputMainConfig-empty.xml"), "--generate-xpath-suppression", getPath("InputMainComplexityOverflow.java")); }

Target:
fix name
Source:
public String getPackageName() { if (clazz.getPackage() != null) { return clazz.getPackage().getName(); } return null; }

Target:
Can this method return null? Or should it return empty string?
Source:
public void testIsStringLiteral() { Set<ASTLiteral> literals = getNodes(ASTLiteral.class, TEST1); ASTLiteral literal = literals.iterator().next(); assertTrue(literal.isStringLiteral()); assertEquals("String", literal.getTypeImage()); }

Target:
This could also be `java.lang.String`.
Source:
public ImmutableMap<K, V> getAllPresent(final Iterable<K> keys) { ImmutableMap.Builder builder = ImmutableMap.builder(); for (K key : keys ) { V value = getIfPresent(key); if (value != null) { builder.put(key, value); } } return builder.build(); }

Target:
formatting weird
Source:
public void configure(ServerHttpSecurity http) { ReactiveAuthenticationManager authenticationManager = getAuthenticationManager(); X509PrincipalExtractor principalExtractor = getPrincipalExtractor(); AuthenticationWebFilter filter = new AuthenticationWebFilter(authenticationManager); filter.setServerAuthenticationConverter(new ServerX509AuthenticationConverter(principalExtractor)); http.addFilterAt(filter, SecurityWebFiltersOrder.AUTHENTICATION); }

Target:
Please make this protected to avoid exposing methods that consumers of the API do not care about.
Source:
public void action(AuthenticationFlowContext context) { if (DisplayUtils.isConsole(context)) { ConsoleOTPFormAuthenticator.SINGLETON.action(context); return; } validateOTP(context); }

Target:
Would it not be better to obtain this from the session? With this approach it's not pluggable.
Source:
private void handleResourceChange(GitResourceVariantTreeSubscriber subscriber, Repository which, Collection<IFile> resources) { for (GitSynchronizeData gsd : gsds) { if (which.equals(gsd.getRepository())) { if (!resources.isEmpty()) refreshResources(subscriber, resources); else refreshRepository(subscriber); } } }

Target:
A null check is needed also. An NPE will be thrown if reopening a very large project. java.lang.NullPointerException at org.eclipse.egit.core.synchronize.GitSubscriberMergeContext.handleResourceChange(GitSubscriberMergeContext.java:141) at org.eclipse.egit.core.synchronize.GitSubscriberMergeContext.access$1(GitSubscriberMergeContext.java:137) at org.eclipse.egit.core.synchronize.GitSubscriberMergeContext$2.indexDiffChanged(GitSubscriberMergeContext.java:69) at org.eclipse.egit.core.internal.indexdiff.IndexDiffCache.notifyListeners(IndexDiffCache.java:94) at org.eclipse.egit.core.internal.indexdiff.IndexDiffCache.access$0(IndexDiffCache.java:86) at org.eclipse.egit.core.internal.indexdiff.IndexDiffCache$1.indexDiffChanged(IndexDiffCache.java:81) at org.eclipse.egit.core.internal.indexdiff.IndexDiffCacheEntry.notifyListeners(IndexDiffCacheEntry.java:313) at org.eclipse.egit.core.internal.indexdiff.IndexDiffCacheEntry.access$6(IndexDiffCacheEntry.java:306) at org.eclipse.egit.core.internal.indexdiff.IndexDiffCacheEntry$3.run(IndexDiffCacheEntry.java:171) at org.eclipse.core.internal.jobs.Worker.run(Worker.java:54)
Source:
public static Set<Path> getIncludedFieldsOfRootEntityForSort(CompositeMetadata root, Sort rootSort) { Set<Path> ret=new HashSet<Path>(); if(rootSort!=null) { SortFieldInfo[] sfi=SortFieldInfo.buildSortFields(rootSort,root.getFieldTreeRoot()); for(SortFieldInfo fi:sfi) ret.add(fi.getName()); } return ret; }

Target:
Don't necessarily need the type info in the right hand assignment anymore. Only mention it because you use both ways throughout.
Source:
public LocalCluster(String jarFileName, int siteCount, int hostCount, int kfactor, int clusterId, BackendTarget target, FailureState failureState, boolean debug, boolean isRejoinTest, Map<String, String> env) { // NOTE: isRejoinTest is unused this(null, null, jarFileName, siteCount, hostCount, kfactor, clusterId, target, failureState, debug, env); }

Target:
Why remove unused at only one level below if its not used at all remove all together.
Source:
public void execute(String userName) { FollowModeManager currentFollowModeManager = followModeManager; User userToFollow = findUser(userName); if (currentFollowModeManager == null) { return; } User currentlyFollowedUser = followModeManager.getFollowedUser(); if ((currentlyFollowedUser != null && !currentlyFollowedUser.equals(userToFollow)) || (currentlyFollowedUser == null && userToFollow != null)) { currentFollowModeManager.follow(userToFollow); } actionPerformed(); }

Target:
I would prefer to move this logic into the `FollowModeManager`
Source:
@Override public Appendable write(Appendable appendable, Context context) throws IOException { String sep = ""; for (TypeName className : typeNames) { appendable.append(sep); className.write(appendable, context); sep = " & "; } return appendable; }

Target:
nit: `sep` –> `separator` ?
Source:
public void flush() throws IOException { entryLogManager.flushCurrentLogs(); entryLogManager.flushRotatedLogs(); }

Target:
for single-log manager, it is better to flush `rotated logs` before flushing `current logs`, because the way how it rotates files and do the checkpoint. I would prefer keeping existing logic unchanged to reduce the risks. besides that, why not provide `flush` method in EntryLogManager? so different entry log manager implementation can implement its own flushing logic rather than exposing this knowledge to EntryLogger. If you provide `flush` method, it is possible that you don't need to expose `flushCurrentLogs` and `flushRotatedLogs`.
Source:
public void disableWireframe() { boolean refreshTaskList = false; EnableFaceCulling faceCullingStateChange = new EnableFaceCulling(); if (!getDesiredStateChanges().contains(faceCullingStateChange)) { addDesiredStateChange(faceCullingStateChange); refreshTaskList = true; } if (getDesiredStateChanges().contains(wireframeStateChange)) { removeDesiredStateChange(wireframeStateChange); refreshTaskList = true; } if (refreshTaskList) { worldRenderer.requestTaskListRefresh(); } }

Target:
Also notice OpaqueObjectsNode.java needs the same treatment.