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

Target:
protected boolean copyObject(String src, String dst) { try { LOG.debug("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; } }
Source:
public RepositorySearchDialog(Collection<String> existingDirs) { this(existingDirs, false, START false); END } Since the logic switch, this should be true (former behavior).

Target:
public RepositorySearchDialog(Collection<String> existingDirs) { this(existingDirs, false, true); }
Source:
public DelegatingResourceDescription getCreatableProperties() { DelegatingResourceDescription description = super.getCreatableProperties(); START description.addProperty("name"); END description.addProperty("location"); description.addProperty("description"); return description; } Aren't the name and description properties already added by the super class?

Target:
public DelegatingResourceDescription getCreatableProperties() { DelegatingResourceDescription description = super.getCreatableProperties(); description.addProperty("location"); return description; }
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. START Character firstChar = data.charAt(0); END if (firstChar == '{' || firstChar == '[') { return this.jsonFactory.createParser(data); } else { return this.yamlFactory.createParser(data); } } 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"

Target:
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. char firstChar = data.charAt(0); if (firstChar == '{' || firstChar == '[') { return this.jsonFactory.createParser(data); } else { return this.yamlFactory.createParser(data); } }
Source:
public void testGenerateDroolsTestOption() { ScoreDirectorFactoryConfig config = new ScoreDirectorFactoryConfig(); assertThat(config.isGenerateDroolsTestOnError()).isNull(); config.setGenerateDroolsTestOnError(true); START assertThat((boolean) config.isGenerateDroolsTestOnError()).isTrue(); END config.setGenerateDroolsTestOnError(Boolean.FALSE); assertThat((boolean) config.isGenerateDroolsTestOnError()).isFalse(); config.setGenerateDroolsTestOnError(null); assertThat(config.isGenerateDroolsTestOnError()).isNull(); } Redundant cast.

Target:
public void testGenerateDroolsTestOption() { ScoreDirectorFactoryConfig config = new ScoreDirectorFactoryConfig(); assertThat(config.isGenerateDroolsTestOnError()).isNull(); config.setGenerateDroolsTestOnError(true); assertThat(config.isGenerateDroolsTestOnError()).isTrue(); config.setGenerateDroolsTestOnError(Boolean.FALSE); assertThat(config.isGenerateDroolsTestOnError()).isFalse(); config.setGenerateDroolsTestOnError(null); assertThat(config.isGenerateDroolsTestOnError()).isNull(); }
Source:
private RawText getRawText(ObjectId id, Repository repo) throws IOException { START if (id.equals(ObjectId.zeroId())) return new RawText(new byte[] {}); END return new RawText(repo.openBlob(id).getCachedBytes()); } Style-nit: Use curly brackets and wrap the return to next line.

Target:
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()); }
Source:
private static String getUserAgentSuffix() { String suffix = ";" + USER_AGENT_SUFFIX; START return suffix; END } We can make this inline. ```suggestion return ";" + USER_AGENT_SUFFIX; ```

Target:
private static String getUserAgentSuffix() { return ";" + USER_AGENT_SUFFIX; }
Source:
public Builder setDataSize(Estimate dataSize) { START this.dataSize = requireNonNull(dataSize, "dataSize can not be null"); END return this; } you don't validate in other builders method (and you don't have to)

Target:
public Builder setDataSize(Estimate dataSize) { this.dataSize = dataSize; return this; }
Source:
public boolean isExpired(Date invocationDate) { if (getExpires() != null) { Date currentInvocationDate = invocationDate == null ? new Date() : invocationDate; START return getExpires().before(currentInvocationDate); END } return false; } Statement can be rewritten inline.

Target:
public boolean isExpired(Date invocationDate) { if (getExpires() != null) { return getExpires().before(invocationDate == null ? new Date() : invocationDate); } return false; }
Source:
public void stop() { if (isRunning()) { process.destroy(); try { if (stdout !=null) { START stdout.close(); END } if (stdin !=null) { stdin.close(); } } catch (IOException e) { throw new RuntimeException(e.getMessage(),e); } finally { running.set(false); } } } Is this really needed?

Target:
public void stop() { if (isRunning()) { process.destroy(); running.set(false); } }
Source:
public boolean equals(Object object) { START if (object == null || object.getClass() != getClass()) { END return false; } if (object == this) { return true; } MacroId rhs = (MacroId) object; return new EqualsBuilder() .append(getId(), rhs.getId()) .append(getSyntax(), rhs.getSyntax()) .isEquals(); } 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.

Target:
public boolean equals(Object object) { if (object == this) { return true; } if (!(object instanceof MacroId)) { return false; } MacroId rhs = (MacroId) object; return new EqualsBuilder() .append(getId(), rhs.getId()) .append(getSyntax(), rhs.getSyntax()) .isEquals(); }
Source:
START Map<String, Object> getExtraInformation() { END return extraInformation; } this is public API, we can't lower the visibility without deprecating first

Target:
public Map<String, Object> getExtraInformation() { return extraInformation; }
Source:
public int hashCode() { START return Objects.hash(pointer, ownerName, owner, readers, writers); END } neat.

Target:
public int hashCode() { return Objects.hash(pointer, ownerName); }
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=" START + absoluteFriendPaths.stream().reduce("", (path1, path2) -> path1 + "," + path2); END } What about the same when the list is empty, it still adds `-Xfriend-paths=` option?

Target:
private String getFriendsPath( SourcePathResolver sourcePathResolver, ImmutableList<SourcePath> friendPathsSourcePaths) { if (friendPathsSourcePaths.isEmpty()) { return ""; } // 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); }
Source:
public Target(String targetUriAsString) { START super(); END Assert.hasText(targetUriAsString, "The provided targetUriAsString must neither be null nor empty."); this.targetUri = URI.create(targetUriAsString); } Do we need super(), if the class is not inheriting from a super class?

Target:
public Target(String targetUriAsString) { Assert.hasText(targetUriAsString, "The provided targetUriAsString must neither be null nor empty."); this.targetUri = URI.create(targetUriAsString); }
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); START } END 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.

Target:
public PropertyInvertedRegexTester(IPersonAttributesGroupTestDefinition definition) { super(definition); setPattern(definition.getAttributeName(), definition.getTestValue()); }
Source:
public final boolean doesProvideNewPage() { if (provision == null) { START throw new IllegalStateException("Page instance not yet resolved"); END } return getProvision().doesProvideNewPage(); } 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".

Target:
public final boolean doesProvideNewPage() { return getProvision().doesProvideNewPage(); }
Source:
private Handler getHandler() { START if (mHandler == null) { END // Use current main looper mHandler = new Handler(mContext.getMainLooper()); } return mHandler; } This doesn't look thread-safe.

Target:
private synchronized Handler getHandler() { if (mHandler == null) { // Use current main looper mHandler = new Handler(mContext.getMainLooper()); } return mHandler; }
Source:
@SuppressWarnings("UnusedDeclaration") @Deprecated public void setDebugging(boolean debugging) { setIndicatorsEnabled(debugging); START setLoggingEnabled(debugging); END } Let's remove this behavior. `setDebugging` will only affect the indicators.

Target:
@SuppressWarnings("UnusedDeclaration") @Deprecated public void setDebugging(boolean debugging) { setIndicatorsEnabled(debugging); }
Source:
public List<ServerTemplate> load() { synchronized (store) { return store.values().stream().map(e -> cloneServerTemplate(e)).collect(Collectors.toList()); START } END } I guess we no longer need `store` to be of `ConcurrentHashMap` implementation if we are fully locking it.

Target:
public List<ServerTemplate> load() { synchronized (store) { return store.values().stream().map(this::cloneServerTemplate).collect(Collectors.toList()); } }
Source:
public String getLearnerMaster() { QuorumPeer.QuorumServer learnerMaster = observer.getCurrentLearnerMaster(); InetSocketAddress address = learnerMaster.addr.getReachableOrOne(); START if (learnerMaster == null || address == null) { END return "Unknown"; } return address.getAddress().getHostAddress() + ":" + address.getPort(); } if `learnerMaster` is `null` here then you'll get a NPE on the `learnerMaster.addr.getReachableOrOne()` above.

Target:
public String getLearnerMaster() { QuorumPeer.QuorumServer learnerMaster = observer.getCurrentLearnerMaster(); if (learnerMaster == null || learnerMaster.addr.isEmpty()) { return "Unknown"; } InetSocketAddress address = learnerMaster.addr.getReachableOrOne(); return address.getAddress().getHostAddress() + ":" + address.getPort(); }
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); START nested.getShallowTraceBuilder().setTaskType("nestedTask"); END return flatten(desc, nested); } I think we should drop redundant "Task" suffix from the task types e.g.: "nestedTask" -> "nested" "withSideEffectTask" -> "withSideEffect" "timeoutTask" -> "timeout" "withTimeoutTask" -> "withTimeout"

Target:
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); return flatten(desc, nested); }
Source:
protected List<String> findStringsInFileCommon(String regexp, boolean stopOnFirst, int searchLimit, File fileToSearch) START throws Exception { END return findStringsInFileCommon(regexp, stopOnFirst, searchLimit, fileToSearch, Project.MSG_INFO); } As stated above, I don't see the need for this method to throw an exception.

Target:
protected List<String> findStringsInFileCommon(String regexp, boolean stopOnFirst, int searchLimit, File fileToSearch) { return findStringsInFileCommon(regexp, stopOnFirst, searchLimit, fileToSearch, Project.MSG_INFO); }
Source:
public void notifyAboutStartProcess(String id) { Long processInstanceId = Long.parseLong(id); newProcessInstanceEvent.fire(new NewProcessInstanceEvent(serverTemplateId, deploymentId, processInstanceId, processDefId, processName, START 1)); END final String message = Constants.INSTANCE.ProcessStarted(processInstanceId.longValue()); notificationEvent.fire(new NotificationEvent(message, NotificationEvent.NotificationType.SUCCESS)); close(); } can you pass null in here for the status, I recently refactored similar code, and status should not be part of the event.

Target:
public void notifyAboutStartProcess(String id) { Long processInstanceId = Long.parseLong(id); newProcessInstanceEvent.fire(new NewProcessInstanceEvent(serverTemplateId, deploymentId, processInstanceId, processDefId, processName, null)); final String message = Constants.INSTANCE.ProcessStarted(processInstanceId.longValue()); notificationEvent.fire(new NotificationEvent(message, NotificationEvent.NotificationType.SUCCESS)); close(); }
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); START if (MoveJob.this.hasAccess(Right.VIEW, newChildReference)) { END maybeMove(oldChildReference, newChildReference); } } }); } I don't understand what this check is doing here. maybeMove is already taking check of checking rights.

Target:
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); maybeMove(oldChildReference, newChildReference); } }); }
Source:
START public void processEvent(DiscoveryServiceEvent event) throws LogReplicationDiscoveryServiceException { END 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); } } same, we can delete LogReplicationDiscoveryServiceException.java file now.

Target:
public void processEvent(DiscoveryServiceEvent event) { log.info("Process event {}", event.getType()); switch (event.getType()) { 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.getType()); } }
Source:
public void deleteError(final ProgramError error) { synchronized (errors) { errors.remove(error); START eventBus.publish(new ProgramErrorDeletedEvent(error)); END } } 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?

Target:
public void deleteError(final ProgramError error) { errors.remove(error); eventBus.publish(new ProgramErrorDeletedEvent(error)); }
Source:
public LamiTableContentProvider() { fCurrentEntries = START checkNotNull(Collections.emptyList()); END } Can remove checkNotNull, we have external @NonNull annotation on Collections.emptyList().

Target:
public LamiTableContentProvider() { fCurrentEntries = Collections.emptyList(); }
Source:
public ArticlePageObject clickGetInfoLink() { switchToIFrame(); waitForElementByElement(getInfoLink); //Opens new tab to Template namespace getInfoLink.click(); switchOutOfIFrame(); START return new ArticlePageObject(driver); END } 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

Target:
public ArticlePageObject clickGetInfoLink() { switchToIFrame(); try { waitForElementByElement(getInfoLink); //Opens new tab to Template namespace getInfoLink.click(); return new ArticlePageObject(driver); } finally { switchOutOfIFrame(); } }
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) START .matches(adviceArray -> asList(adviceArray).get(0) instanceof TracingRabbitListenerAdvice); END } would this work? (also removing the import) ```suggestion .matches(adviceArray -> adviceArray[0] instanceof TracingRabbitListenerAdvice); ```

Target:
@Test public void decorateSimpleRabbitListenerContainerFactory_appends_as_first_when_absent() { SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory(); factory.setAdviceChain(new CacheInterceptor()); // the order of advices is important for the downstream interceptor to see the tracing context assertThat(rabbitTracing.decorateSimpleRabbitListenerContainerFactory(factory).getAdviceChain()) .hasSize(2) .matches(adviceArray -> adviceArray[0] instanceof TracingRabbitListenerAdvice); }
Source:
private static List<IResource> getReadonlyFiles(IResource[] resources) { START List<IResource> readOnlyFiles= new ArrayList<IResource>(); END 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; } Use ArrayList<>

Target:
private static List<IResource> getReadonlyFiles(IResource[] resources) { List<IResource> readOnlyFiles= new ArrayList<>(); for (IResource resource : resources) { ResourceAttributes resourceAttributes= resource.getResourceAttributes(); if (resource.getType() == IResource.FILE && resourceAttributes != null && resourceAttributes.isReadOnly()) readOnlyFiles.add(resource); } return readOnlyFiles; }
Source:
void clean(K key) { List<V> data = getDataMap().get(key); if (data != null) { START data.clear(); END } getDataMap().remove(key); } I think this is not necessary as the GC will remove it as soon as there is no more reference on the Object

Target:
void clean(K key) { getDataMap().remove(key); }
Source:
public static boolean isMemoryDeviceHotUnpluggable(VmDevice memoryDevice) { if (!isMemory(memoryDevice)) { START throw new RuntimeException("Memory device expected but device " + memoryDevice + " obtained."); END } return getSpecParamsIntValue(memoryDevice, SPEC_PARAM_SIZE).isPresent() && getSpecParamsIntValue(memoryDevice, SPEC_PARAM_NODE).isPresent(); } IllegalArgumentException sounds better here.

Target:
public static boolean isMemoryDeviceHotUnpluggable(VmDevice memoryDevice) { if (!isMemory(memoryDevice)) { throw new IllegalArgumentException("Memory device expected but device " + memoryDevice + " obtained."); } return getSpecParamsIntValue(memoryDevice, SPEC_PARAM_SIZE).isPresent() && getSpecParamsIntValue(memoryDevice, SPEC_PARAM_NODE).isPresent(); }
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) { START throw new RuntimeException(e); END } } Would be nice if you add here an exception text. Something like "unable to load the list of connector configurations"

Target:
public Boolean connectorExists(String id) { try { List<ConnectorConfiguration> list = configPersistence.load(ImmutableMap.of(Constants.CONNECTOR_PERSISTENT_ID, id)); return !list.isEmpty(); } catch (PersistenceException e) { throw new RuntimeException(e); } }
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"); START } END can we maybe have separate test cases for the returning clause?

Target:
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"); }
Source:
public void setSetPath(String path) { START setPath.set(requireNonNull(path, "path is null")); END } 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); ```

Target:
public void setSetPath(String path) { requireNonNull(path, "path is null"); setPath.set(path); }
Source:
public EnvVars getEnvironment() throws IOException, InterruptedException { if (cachedEnvironment != null) { START return cachedEnvironment; END } cachedEnvironment = EnvVars.getRemote(getChannel()); return cachedEnvironment; } 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; } ```

Target:
public EnvVars getEnvironment() throws IOException, InterruptedException { EnvVars cachedEnvironment = this.cachedEnvironment; if (cachedEnvironment != null) { return cachedEnvironment; } cachedEnvironment = EnvVars.getRemote(getChannel()); this.cachedEnvironment = cachedEnvironment; return cachedEnvironment; }
Source:
public int getMaxCapacity() { START readLock.lock(); END try { return maxCapacity; } finally { readLock.unlock(); } } why should add lock here?

Target:
public int getMaxCapacity() { return maxCapacity; }
Source:
public void testGetAllForVdsGroupWithPermissionsForUnpriviligedUser() { List<VDS> result = dao.getAllForVdsGroup(existingVds.getvds_group_id(), UNPRIVILEGED_USER_ID, true); assertNotNull(result); START assertTrue(result.size() == 0); END } Can you use isEmpty()?

Target:
public void testGetAllForVdsGroupWithPermissionsForUnpriviligedUser() { List<VDS> result = dao.getAllForVdsGroup(existingVds.getvds_group_id(), UNPRIVILEGED_USER_ID, true); assertNotNull(result); assertTrue(result.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) { START throw new RuntimeException("Failed check data source", e); END } return ds; } Я еще люблю в сообщение вставлять изначальный exception, nипа "Failed to check data source " + e.toString(), e).

Target:
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); checkDataSource(ds, name); return ds; }
Source:
protected Control createPageControls(Composite parent) { setTitle(Messages.RemoveReviewerDialog_Remove_Reviewer); START Label label = new Label(parent, SWT.CENTER); END label.setText( NLS.bind(Messages.RemoveReviewerDialog_Are_You_Sure_You_Want_To_Remove, userToRemove.getDisplayName())); return parent; } no need to center it, just give it SWT.NONE

Target:
protected Control createPageControls(Composite parent) { setTitle(Messages.RemoveReviewerDialog_Remove_Reviewer); Label label = new Label(parent, SWT.NONE); label.setText( NLS.bind(Messages.RemoveReviewerDialog_Are_You_Sure_You_Want_To_Remove, userToRemove.getDisplayName())); return parent; }
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; START } END I think you need to call super otherwise you loose the permissions that you need to check by default.

Target:
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())); list = QuotaHelper.addQuotaPermissionSubject(list, getStoragePool(), getQuotaId()); return list; }
Source:
public void onInit( String clientName, Map<String,Object> credentials ) throws IOException { START packer.packStructHeader( 1, INIT.signature() ); END packer.pack( clientName ); packer.pack( ValueUtils.asMapValue( credentials ) ); onMessageComplete.onMessageComplete(); } 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.

Target:
public void onInit( String clientName, Map<String,Object> credentials ) throws IOException { packer.packStructHeader( 2, INIT.signature() ); packer.pack( clientName ); packer.pack( ValueUtils.asMapValue( credentials ) ); onMessageComplete.onMessageComplete(); }
Source:
START public SecurityGroupExtensionProvider(NeutronSecurityGroupExtension neutronSecurityGroupExtension, END NovaSecurityGroupExtension novaSecurityGroupExtension) { this.neutronSecurityGroupExtension = neutronSecurityGroupExtension; this.novaSecurityGroupExtension = novaSecurityGroupExtension; } Remove the public modifier

Target:
SecurityGroupExtensionProvider(NeutronSecurityGroupExtension neutronSecurityGroupExtension, NovaSecurityGroupExtension novaSecurityGroupExtension) { this.neutronSecurityGroupExtension = neutronSecurityGroupExtension; this.novaSecurityGroupExtension = novaSecurityGroupExtension; }
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); START if (comparedExpression == null) { END return null; } } } return comparedExpression; } @vilchik-elena Do we need this block?

Target:
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); } } return comparedExpression; }
Source:
private void scheduleRefresh(Duration delay) { // already stopped? avoids rejection exception if (executor.isShutdown()) { return; } START executor.schedule((Runnable) this::refresh, delay.toMillis(), TimeUnit.MILLISECONDS); END } Is the `(Runnable)` needed?

Target:
private void scheduleRefresh(Duration delay) { // already stopped? avoids rejection exception if (executor.isShutdown()) { return; } executor.schedule(this::refresh, delay.toMillis(), TimeUnit.MILLISECONDS); }
Source:
public static void main(String[] args) { START LocalQueryRunner queryRunner = createLocalQueryRunner(ImmutableMap.of("reorder_joins", "false")); END new SqlConsecutiveJoinBenchmark(queryRunner).runBenchmark(new SimpleLineBenchmarkResultWriter(System.out)); } Technically, you should `queryRunner.close()` (or t-w-r). This would ensure proper cleanup of any temp files (or whatevers) it might have created

Target:
public static void main(String[] args) { LocalQueryRunner queryRunner = createLocalQueryRunner(ImmutableMap.of("reorder_joins", "false")); new SqlConsecutiveJoinBenchmark(queryRunner).runBenchmark(new SimpleLineBenchmarkResultWriter(System.out)); queryRunner.close(); }
Source:
START public void beforeStartingVertx(VertxOptions options) { END } Shouldn't they be protected not public?

Target:
protected void beforeStartingVertx(VertxOptions options) { }
Source:
public Builder body(String json) { checkNotNull(json, "body required"); checkArgument(json.getBytes().length <= getInteger(MESSAGE_BODY_MAX_IN_BYTES), START "json size must be <= %s bytes", getInteger(MESSAGE_BODY_MAX_IN_BYTES)); END this.body = new JsonBall(json).toString(); return self(); } 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?

Target:
public Builder body(String json) { checkNotNull(json, "body required"); this.body = new JsonBall(json).toString(); return self(); }
Source:
private String getTokenFromHeader(HttpServletRequest request) { String token = null; String headerValue = request.getHeader(SsoConstants.HEADER_AUTHORIZATION); if (headerValue != null && headerValue.startsWith(BEARER)) { token = START headerValue.substring("Bearer".length()).trim(); END } return token; } s/"Bearer"/BEARER

Target:
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; }
Source:
START public static CDIProvider getCDIProvider() { END 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; } } This method should not be public or what's the point?

Target:
private 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; } }
Source:
START public void testIsDrawable_Stage() throws Exception { END testIsDrawable(CaseManagementDiagram.class, AdHocSubprocess.class, true); } The Exception is never thrown.

Target:
public void testIsDrawable_Stage() { testIsDrawable(CaseManagementDiagram.class, AdHocSubprocess.class, true); }
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; START } END finally { Closeables2.closeQuietly(azureBlob); } } 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?

Target:
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"); } finally { Closeables2.closeQuietly(azureBlob); } }
Source:
public void enter() { mUseEap = (IkeSessionOptions.IKE_AUTH_METHOD_EAP == mIkeSessionOptions.getLocalAuthConfig().mAuthMethod); START super.enter(); END } 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)

Target:
public void enter() { super.enter(); mUseEap = (IkeSessionOptions.IKE_AUTH_METHOD_EAP == mIkeSessionOptions.getLocalAuthConfig().mAuthMethod); }
Source:
public static Predicate<Expression> isInferenceCandidate() { return expression -> { expression = normalizeInPredicateToEquality(expression); if (expression instanceof ComparisonExpression && DeterminismEvaluator.isDeterministic(expression) && START !NullabilityAnalyzer.mayReturnNullOnNonNullInput(expression) && END !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; }; } you can static import these functions.

Target:
public static Predicate<Expression> isInferenceCandidate() { return expression -> { expression = normalizeInPredicateToEquality(expression); if (expression instanceof ComparisonExpression && isDeterministic(expression) && !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; }; }
Source:
public void startMasters() throws Exception { mMaster = LocalAlluxioMaster.create(mWorkDirectory, true); mMaster.start(); START CommonUtils.PROCESS_TYPE.set(CommonUtils.ProcessType.CLIENT); END } why is this needed?

Target:
public void startMasters() throws Exception { mMaster = LocalAlluxioMaster.create(mWorkDirectory, true); mMaster.start(); }
Source:
public Proxy getProxy() { START if (mProxyHost == null) return null; END 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)); } mind the code style

Target:
public Proxy getProxy() { if (mProxyHost == null) { return null; } return new Proxy(mProxyType, new InetSocketAddress(mProxyHost, mProxyPort)); }
Source:
public HttpRequest setMethod(HttpMethod method) { ObjectUtil.checkNotNull(method, "method"); START this.method = method; END return this; } nit: you can merge both lines above as `checkNotNull` will return the given argument

Target:
public HttpRequest setMethod(HttpMethod method) { this.method = ObjectUtil.checkNotNull(method, "method"); return this; }
Source:
public Set<VmDeviceGeneralType> getDeviceTypesWithProperties(Version version) { if (!FeatureSupported.deviceCustomProperties(version)) { return Collections.emptySet(); } START Set<VmDeviceGeneralType> types; END 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; } a matter of taste - types can be avoided for the sake of return statements from the if-else block.

Target:
public Set<VmDeviceGeneralType> getDeviceTypesWithProperties(Version version) { if (!FeatureSupported.deviceCustomProperties(version)) { return Collections.emptySet(); } EnumMap<VmDeviceGeneralType, Map<String, Pattern>> map = deviceProperties.get(version); if (map.isEmpty()) { // no device type has any properties return Collections.emptySet(); } else { // prevent client to modify return Collections.unmodifiableSet(map.keySet()); } }
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); START return editor.getAdapter(GraphicalViewer.class); END } }); ReflectionHelper.setFieldValueWithoutException(this, "viewer", new SWTBotSiriusGefViewer(graphicalViewer), this.getClass().getSuperclass()); } generic has come with mars. Consequently that code won't compile against previous platform

Target:
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 (GraphicalViewer) editor.getAdapter(GraphicalViewer.class); } }); ReflectionHelper.setFieldValueWithoutException(this, "viewer", new SWTBotSiriusGefViewer(graphicalViewer), this.getClass().getSuperclass()); }
Source:
public CreateAllSnapshotsFromVmParameters() { needsLocking = true; START snapshotType = SnapshotType.REGULAR; END saveMemory = true; diskIdsToIgnoreInChecks = Collections.emptySet(); } I'd prefer that we handled it (the snapshot type) in a separate change.

Target:
public CreateAllSnapshotsFromVmParameters() { needsLocking = true; saveMemory = true; diskIdsToIgnoreInChecks = Collections.emptySet(); }
Source:
public SchedulerTask<?> createTaskInstance( String taskType ) throws IllegalArgumentException START { END 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 ); } } afacit vvv is all noise

Target:
public SchedulerTask<?> createTaskInstance( String taskType ) throws IllegalArgumentException { try { return lookupTask( taskType ); } catch ( ComponentLookupException e ) { throw new IllegalArgumentException( "Could not create task of type" + taskType, e ); } }
Source:
public PapyrusStereotypedElementItemProviderDecorator(ComposeableAdapterFactory adapterFactory) { super(adapterFactory); START labelProviderService = new LabelProviderServiceImpl(); END 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$ } } 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?

Target:
public PapyrusStereotypedElementItemProviderDecorator(ComposeableAdapterFactory adapterFactory) { super(adapterFactory); }
Source:
START default SourceMap sourceMap() { END return null; } Why not rely on `Optional`, rather than introducing another method which could lead to NPEs?

Target:
default Optional<SourceMap> sourceMap() { return Optional.empty(); }
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"); START emptyDirCreating(); END } 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.

Target:
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"); }
Source:
private static String parseAnnotationFieldTypeName(final Supplier<Class<?>> theTypeSupplier, final String errorMessage) { try { theTypeSupplier.get(); START throw new RuntimeException(errorMessage); END } catch (MirroredTypeException mte) { return mte.getTypeMirror().toString(); } } 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.

Target:
private static String parseAnnotationFieldTypeName(final Supplier<Class<?>> theTypeSupplier, final String errorMessage) { try { theTypeSupplier.get(); } catch (MirroredTypeException mte) { return mte.getTypeMirror().toString(); } // Failed to parse the field type name throw new RuntimeException(errorMessage); }
Source:
default StreamPriority getStreamPriority() { START return StreamPriority.DEFAULT; END } return `null` instead when there is no priority

Target:
default StreamPriority getStreamPriority() { return null; }
Source:
protected void configure() { bind(EventDao.class).to(EventDaoInMemory.class).asEagerSingleton(); START bind(Bootstrap.class); END } ?? Pourquoi cette ligne. Bootstrap est déjà une classe concrète...

Target:
protected void configure() { bind(EventDao.class).to(EventDaoInMemory.class).asEagerSingleton(); }
Source:
public static void onAdvancementEvent(AdvancementEvent event) { START if (ENABLED && event.getAdvancement().getDisplay() != null && event.getAdvancement().getDisplay().shouldAnnounceToChat()) END { logger.info("{} got the advancement", event.getEntityPlayer().getDisplayNameString(), event.getAdvancement().getDisplayText().getUnformattedText()); } } Second `ENABLED` check is not necessary if you have the first one.

Target:
public static void onAdvancementEvent(AdvancementEvent event) { if (event.getAdvancement().getDisplay() != null && event.getAdvancement().getDisplay().shouldAnnounceToChat()) { logger.info("{} got the advancement", event.getEntityPlayer().getDisplayNameString(), event.getAdvancement().getDisplayText().getUnformattedText()); } }
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")); START endpoints.add(httpEndpoint); END } catch (URISyntaxException e) { throw new IllegalStateException(e); } } let's use URI.create and avoid try/catch

Target:
public ExampleEndpointsProvider() { // Put custom code here to get endpoints // In our case they will be hardcoded JHttpEndpoint httpEndpoint = new JHttpEndpoint(URI.create("https://jagger.griddynamics.net:443")); endpoints.add(httpEndpoint); }
Source:
public SlackUserProperty() { START this.userId = null; END this.disableNotifications = false; } do we need any content in this constructor at all?

Target:
public SlackUserProperty() { }
Source:
public void onStreamCreate(IMediaStream stream) { START if (!stream.isTranscodeResult()) { END PacketListener listener = new PacketListener(); WMSProperties props = stream.getProperties(); synchronized (props) { props.setProperty(STREAM_ACTION_LISTENER_PROPERTY, listener); } stream.addLivePacketListener(listener); } } do return

Target:
public void onStreamCreate(IMediaStream stream) { if (stream.isTranscodeResult()) { return; } PacketListener listener = new PacketListener(); WMSProperties props = stream.getProperties(); synchronized (props) { props.setProperty(STREAM_ACTION_LISTENER_PROPERTY, listener); } stream.addLivePacketListener(listener); }
Source:
public long getEstimatedSizeInBytes() { START int result = INSTANCE_SIZE; END result += sizeOf(levelOffsets); result += tree.sizeOf(); for (T item : items) { result += item.getEstimatedSizeInBytes(); } return result; } result -> size

Target:
public long getEstimatedSizeInBytes() { long result = INSTANCE_SIZE + sizeOf(levelOffsets) + tree.sizeOf(); for (T item : items) { result += item.getEstimatedSizeInBytes(); } return result; }
Source:
public boolean respondsTo(RunEvent event) { Run r = event.getEventObject(); START if (event.getEventType().equals(MisoEventType.RUN_FAILED) && r.getHealth().equals(HealthType.Failed)) { END log.info("Run " + r.getAlias() + ": " + event.getEventMessage()); return true; } return false; } `==` instead of `.equals` (in both instances) would make this null-safe

Target:
public boolean respondsTo(RunEvent event) { Run r = event.getEventObject(); if (event.getEventType() == MisoEventType.RUN_FAILED && r.getHealth() == HealthType.Failed) { log.info("Run " + r.getAlias() + ": " + event.getEventMessage()); return true; } return false; }
Source:
public boolean isEnabled() { START final boolean res = super.isEnabled() || isDirty(); END return res; } en profiter pour enlever cette variable intermédiaire?

Target:
public boolean isEnabled() { return super.isEnabled() || isDirty(); }