auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static File getDiskCacheDir(Context context, String uniqueName) { // Check if media is mounted or storage is built-in, if so, try and use external cache dir // otherwise use internal cache dir. final String cachePath; START if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) END && context.getExternalCacheDir() != null) { cachePath = context.getExternalCacheDir().getPath(); } else { cachePath = context.getCacheDir().getPath(); } return new File(cachePath + File.separator + uniqueName); } I'd prefer the old order so when Environment.getExternalStorageState() return null we don't get an NPE.

Target:
public static File getDiskCacheDir(Context context, String uniqueName) { // Check if media is mounted or storage is built-in, if so, try and use external cache dir // otherwise use internal cache dir. final String cachePath; if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) && context.getExternalCacheDir() != null) { cachePath = context.getExternalCacheDir().getPath(); } else { cachePath = context.getCacheDir().getPath(); } return new File(cachePath + File.separator + uniqueName); }
Source:
START String getBucketName(URI uri) END { if (uri.getHost() != null) { return uri.getHost(); } else if (uri.getUserInfo() == null) { return uri.getAuthority(); } throw new IllegalArgumentException("Unable to determine S3 bucket from URI."); } mark this method private as this is only used in this class.

Target:
public static String getBucketName(URI uri) { if (uri.getHost() != null) { return uri.getHost(); } if (uri.getUserInfo() == null) { return uri.getAuthority(); } throw new IllegalArgumentException("Unable to determine S3 bucket from URI."); }
Source:
private MustacheFactory createNewMustacheFactory(Class<? extends View> key) { START return (fileRoot != null) ? new DefaultMustacheFactory(new FileSystemResolver(fileRoot)) END : new DefaultMustacheFactory(new PerClassMustacheResolver(key)); } I think we could make this initialization more terse if we initialize `MustacheResolver` with the ternary operator and pass it to `DefaultMustacheFactory`. ```java new DefaultMustacheFactory(fileRoot.isPresent() ? new FileSystemResolver(fileRoot.get()) : new PerClassMustacheResolver(key)) ```

Target:
private MustacheFactory createNewMustacheFactory(Class<? extends View> key) { return new DefaultMustacheFactory( fileRoot.isPresent() ? new FileSystemResolver(fileRoot.get()) : new PerClassMustacheResolver(key)); }
Source:
public boolean isValidValue(final Object element) { boolean result = super.isValidValue(element); if (result) { EObject eObject = EMFHelper.getEObject(element); result = (ProtocolUtils.isProtocol(eObject) && START !SystemElementsUtils.isSystemProtocol((Collaboration) eObject) && END !SystemElementsUtils.isBaseProtocol((Collaboration) eObject)); } return result; } If we're all agreed on letting users choose system protocols in the browser, then I suppose we should not have this condition.

Target:
public boolean isValidValue(final Object element) { boolean result = super.isValidValue(element); if (result) { EObject eObject = EMFHelper.getEObject(element); result = (ProtocolUtils.isProtocol(eObject) && !SystemElementsUtils.isBaseProtocol((Collaboration) eObject)); } return result; }
Source:
public void testLogin() throws Throwable { START InstrumentationRegistry.getInstrumentation().runOnMainSync(new Runnable() { END @Override public void run() { loginTestTask.execute(); } }); assertThat(completionLatch.await(), is(true)); } Very minor: consider another helper method for runOnMainSync() so we can focus on the interesting bit (loginTestTask.execute()). As a side note, executing from the main thread doesn't seem to be a requirement of "SaneAsyncTask" for whatever reason. However, it seems more proper to call execute on the main thread[0] since we think of it as a normal AsyncTask so I think we should keep it. [0] http://developer.android.com/reference/android/os/AsyncTask.html#execute(Params...)

Target:
public void testLogin() throws Throwable { runOnMainSync(new Runnable() { @Override public void run() { loginTestTask.execute(); } }); completionLatch.await(); }
Source:
public static void warnIfDeprecatedDnsLookupValue(AbstractConfig config) { String clientDnsLookupValue = config.getString(CLIENT_DNS_LOOKUP_CONFIG); if (clientDnsLookupValue.equals(ClientDnsLookup.DEFAULT.toString())) log.warn("Configuration '{}' with value '{}' is deprecated and will be removed in " + "future version. Please use '{}' or another non-deprecated value.", START CLIENT_DNS_LOOKUP_CONFIG, ClientDnsLookup.DEFAULT.toString(), END ClientDnsLookup.USE_ALL_DNS_IPS); } We don't need to call `toString()`

Target:
public static void warnIfDeprecatedDnsLookupValue(AbstractConfig config) { String clientDnsLookupValue = config.getString(CLIENT_DNS_LOOKUP_CONFIG); if (clientDnsLookupValue.equals(ClientDnsLookup.DEFAULT.toString())) log.warn("Configuration '{}' with value '{}' is deprecated and will be removed in " + "future version. Please use '{}' or another non-deprecated value.", CLIENT_DNS_LOOKUP_CONFIG, ClientDnsLookup.DEFAULT, ClientDnsLookup.USE_ALL_DNS_IPS); }
Source:
public HdfsCopyStats(String source, File destination, boolean enableStatsFile, int maxVersionsStatsFile, boolean isFileCopy, HdfsPathInfo pathInfo) { this.sourceFile = source; this.totalBytesTransferred = 0L; this.bytesTransferredSinceLastReport = 0L; this.pathInfo = pathInfo; this.lastReportNs = System.nanoTime(); this.startTimeMS = System.currentTimeMillis(); initializeStatsFile(destination, enableStatsFile, maxVersionsStatsFile, isFileCopy); START aggStats = HdfsFetcherAggStats.getStats(); END } I would like to remove the method getStats and would like to make the aggStats static.

Target:
public HdfsCopyStats(String source, File destination, boolean enableStatsFile, int maxVersionsStatsFile, boolean isFileCopy, HdfsPathInfo pathInfo) { this.sourceFile = source; this.totalBytesTransferred = 0L; this.bytesTransferredSinceLastReport = 0L; this.pathInfo = pathInfo; this.lastReportNs = System.nanoTime(); this.startTimeMS = System.currentTimeMillis(); initializeStatsFile(destination, enableStatsFile, maxVersionsStatsFile, isFileCopy); }
Source:
private void writeAlias(VmDevice device) { writer.writeStartElement("alias"); writer.writeAttributeString("name", String.format("ua-%s", START device.getId().getDeviceId().toString())); END writer.writeEndElement(); } toString() is not needed here, AFAIK.

Target:
private void writeAlias(VmDevice device) { writer.writeStartElement("alias"); writer.writeAttributeString("name", String.format("ua-%s", device.getId().getDeviceId())); writer.writeEndElement(); }
Source:
public ChartData(IDataChartProvider<?> provider, List<ChartSeries> series) { fProvider = provider; START fSeries = checkNotNull(ImmutableList.copyOf(series)); END } You shouldn't need the checkNotNull

Target:
public ChartData(IDataChartProvider<?> provider, List<ChartSeries> series) { fProvider = provider; fSeries = ImmutableList.copyOf(series); }
Source:
protected boolean isRegistered(final String uuid) { START return handlers.containsKey(uuid) && !handlers.get(uuid).isEmpty(); END } can this case be given? I mean having an entry for the given `uuid` but with no registrations?

Target:
protected boolean isRegistered(final String uuid) { return handlers.containsKey(uuid); }
Source:
START public synchronized Class<?> defineClass(String name, byte[] bytecode) { END return defineClass(name, convertClassToResourcePath(name), bytecode); } @manstis can this synchronized be removed? this method is only calling the defineClass overload which is already sync'ed.

Target:
public Class<?> defineClass(String name, byte[] bytecode) { return defineClass(name, convertClassToResourcePath(name), bytecode); }
Source:
public boolean onOptionsItemSelected(MenuItem item) { // home references the app icon if (item.getItemId() == android.R.id.home) { toggle(); // toggles the state of the sliding menu START if(getSlidingMenu().isMenuShowing() && menu.isAdded()) END setTitle(((ITitleable)menu).getTitle()); return true; } return false; } Could we get brackets around this if

Target:
public boolean onOptionsItemSelected(MenuItem item) { // home references the app icon if (item.getItemId() == android.R.id.home) { toggle(); // toggles the state of the sliding menu if(getSlidingMenu().isMenuShowing() && menu.isAdded()){ setTitle(((ITitleable)menu).getTitle()); } return true; } return false; }
Source:
public static ParcelFileDescriptor fromSocket(Socket socket) { FileDescriptor fd = socket.getFileDescriptor$(); try { return fd != null ? ParcelFileDescriptor.dup(fd) : null; } catch (IOException START ex) { END throw new UncheckedIOException(ex); } } super nit (okay to ignore): Here and below: For consistency, consider "e" rather than "ex". Typically we only use "ex" for nested catch blocks where the name "e" is already being used by the enclosing block.

Target:
public static ParcelFileDescriptor fromSocket(Socket socket) { FileDescriptor fd = socket.getFileDescriptor$(); try { return fd != null ? ParcelFileDescriptor.dup(fd) : null; } catch (IOException e) { throw new UncheckedIOException(e); } }
Source:
private String getThemePrefixedPath(String path) { String prefix = themeProperties != null ? themeProperties.get(IntroTheme.ATT_ID) : null; prefix = prefix == null ? "" : prefix.trim(); //$NON-NLS-1$ if (prefix.length() == 0) { return null; } START return prefix.charAt(prefix.length() - 1) == Path.SEPARATOR ? prefix + path : prefix + Path.SEPARATOR + path; END } Is the check for trailing Path.SEPARATOR necessary ? We just got the IntroTheme.ATT_ID property which is not supposed to have a trailing Path.SEPARATOR, no ?

Target:
private String getThemePrefixedPath(String path) { String prefix = themeProperties != null ? themeProperties.get(IntroTheme.ATT_ID) : null; prefix = prefix == null ? "" : prefix.trim(); //$NON-NLS-1$ if (prefix.length() == 0) { return null; } return prefix + Path.SEPARATOR + path; }
Source:
protected void writeString(int majorType, byte[] bytes) throws IOException { int len = (bytes == null) ? 0 : bytes.length; writeType(majorType, len); START m_os.write(bytes); END } what about the null case?

Target:
protected void writeString(int majorType, byte[] bytes) throws IOException { int len = (bytes == null) ? 0 : bytes.length; writeType(majorType, len); if (len > 0){ m_os.write(bytes); } }
Source:
private void checkLogData(long address, ILogData logData) { if (logData == null || logData.getType() == DataType.EMPTY) { throw new RuntimeException("Unexpected return of empty data at address " + address + " on read"); } else if (logData.isTrimmed()) { throw new TrimmedException(); } START } END extra `else` statement, please remove

Target:
private void checkLogData(long address, ILogData logData) { if (logData == null || logData.getType() == DataType.EMPTY) { throw new RuntimeException("Unexpected return of empty data at address " + address + " on read"); } if (logData.isTrimmed()) { throw new TrimmedException(); } }
Source:
private static void merge(AggregatedCalledFunction destination, AggregatedCalledFunction source) { long sourceDuration = source.getDuration(); long sourceSelfTime = source.getSelfTime(); destination.addToDuration(sourceDuration); destination.addToSelfTime(sourceSelfTime); START destination.fStatistics.update(source.fStatistics.getMaxSegment(),source.fStatistics.getMinSegment(), END sourceSelfTime); // merge the children callees. mergeChildren(destination, source); } - space after comma - you need to pass the source duration as well

Target:
private static void merge(AggregatedCalledFunction destination, AggregatedCalledFunction source) { long sourceDuration = source.getDuration(); long sourceSelfTime = source.getSelfTime(); destination.addToDuration(sourceDuration); destination.addToSelfTime(sourceSelfTime); destination.fStatistics.update(source.fStatistics.getMaxSegment(), source.fStatistics.getMinSegment(), sourceDuration, sourceSelfTime); // merge the children callees. mergeChildren(destination, source); }
Source:
@Override protected void doEnqueue(Callback<V> callback) { sendRequest().handle((response, t) -> { if (t != null) { callback.onError(t); } else { V value = null; try { value = parseResponse(response, bodyConverter); } catch (Throwable t1) { propagateIfFatal(t1); callback.onError(t1); } START if (value != null) callback.onSuccess(value); END } return null; }); } Think this needs to go right below line 91. `parseResponse` can return `null` (line 133), which will cause this future to never complete.

Target:
@Override protected void doEnqueue(Callback<V> callback) { sendRequest().handle((response, t) -> { if (t != null) { callback.onError(t); } else { try { V value = parseResponse(response, bodyConverter); callback.onSuccess(value); } catch (Throwable t1) { propagateIfFatal(t1); callback.onError(t1); } } return null; }); }
Source:
public SpiTransaction createServerTransaction(boolean isExplicit, int isolationLevel) { SpiTransaction t = transactionManager.createTransaction(isExplicit, isolationLevel); START try { END transactionScopeManager.set(t); } catch (PersistenceException existingTransactionError) { t.end(); throw existingTransactionError; } return t; } if (!isExplicit) { // ... around the try

Target:
public SpiTransaction createServerTransaction(boolean isExplicit, int isolationLevel) { SpiTransaction t = transactionManager.createTransaction(isExplicit, isolationLevel); if (isExplicit) { try { transactionScopeManager.set(t); } catch (PersistenceException existingTransactionError) { t.end(); throw existingTransactionError; } } return t; }
Source:
C baseApply() { final TreeMap<String, String> t = new TreeMap<String, String>(validate()); if(!children.contains(t)) { C child = newChild(); children.put(t, child); START return child; END } else return children.get(t); } What about thread safety here? I might be mistaken, but by just looking at this code snippet it looks like more than one thread could check the condition, receive `false` from the `contains()` method and execute the above code block. That might be the reason the blocking `putIfAbsent` method is used here?

Target:
C baseApply() { final TreeMap<String, String> t = new TreeMap<String, String>(validate()); C child = children.get(t); if(child == null) { child = newChild(); children.put(t, child); } return child; }
Source:
public void onConnect(String message) { debugView.showPermanently(getString(R.string.connected)); switchableView.setDisplayedChild(1); START presenter.startListeningForDirection(); END } i'd maybe just "forward" the `onConnect` to the presenter instead

Target:
public void onConnect(String message) { debugView.showPermanently(getString(R.string.connected)); switchableView.setDisplayedChild(1); }
Source:
public ByteBuffer[] nioBuffers(int index, int length) { if (b1.nioBufferCount() == 1 && b2.nioBufferCount() == 1) { return new ByteBuffer[] { b1.nioBuffer(), b2.nioBuffer() }; } START return ObjectArrays.concat(b1.nioBuffers(), b2.nioBuffers(), ByteBuffer.class); END } yup, this is incorrect, seems I failed somewhere, this logic has to be in `public ByteBuffer[] nioBuffers()`, gonna change it

Target:
public ByteBuffer[] nioBuffers(int index, int length) { return new ByteBuffer[] { nioBuffer(index, length) }; }
Source:
START public void setDisabledAdministrativeMonitors(Set<String> disabledAdministrativeMonitors) { END this.disabledAdministrativeMonitors = new CopyOnWriteArraySet<>(disabledAdministrativeMonitors); } why the instance-level lock suggestion, vs. what's been implemented here. seems like overkill

Target:
public void setDisabledAdministrativeMonitors(Set<String> disabledAdministrativeMonitors) { synchronized (this.disabledAdministrativeMonitors) { this.disabledAdministrativeMonitors.clear(); this.disabledAdministrativeMonitors.addAll(disabledAdministrativeMonitors); } }
Source:
START public boolean waitUntilReadyToProcess(Properties jobProps) { END return true; } Is this method going to be overridden in a subclass to provide a different behavior? This method can be protected if is not supposed to be overridden outside the package.

Target:
protected boolean waitUntilReadyToProcess(Properties jobProps) { return true; }
Source:
private ArrayList<Comment> fetchAllComments(ArticleTable article) { START return (ArrayList<Comment>) hibernateTemplate.find("FROM Comment WHERE articleId = ?", article.getArticleId()); END } Casting to `ArrayList` is brittle. Could we return `List<>` from here instead?

Target:
private List<Comment> fetchAllComments(ArticleTable article) { return (ArrayList<Comment>) hibernateTemplate.find("FROM Comment WHERE articleId = ?", article.getArticleId()); }
Source:
START public String getPreview() { END StringBuilder bld= new StringBuilder(); bld.append("\n"); if (isEnabled(CleanUpConstants.NUMBER_SUFFIX)) { bld.append("long number1 = 10L;\n"); bld.append("float number2 = 10F;\n"); bld.append("double number3 = 10D;\n"); } else { bld.append("long number1 = 10l;\n"); bld.append("float number2 = 10f;\n"); bld.append("double number3 = 10d;\n"); } return bld.toString(); } Missed this one in the previous review, needs updating as well!

Target:
public String getPreview() { StringBuilder bld= new StringBuilder(); bld.append("\n"); if (isEnabled(CleanUpConstants.NUMBER_SUFFIX)) { bld.append("long number1 = 10L;\n"); } else { bld.append("long number1 = 10l;\n"); } return bld.toString(); }
Source:
private static ByteBuf serializeProtobuf(MessageLite msg, ByteBufAllocator allocator) { int size = msg.getSerializedSize(); ByteBuf buf = allocator.heapBuffer(size, size); try { START msg.writeTo(new ByteBufOutputStream(buf)); END } catch (IOException e) { // This is in-memory serialization, should not fail throw new RuntimeException(e); } // Advance writer idx buf.writerIndex(buf.capacity()); return buf; } Is this a race or corruption happens all the time? Change looks fine, but I did not understand the actual issue with the current code on why corruption happening.

Target:
private static ByteBuf serializeProtobuf(MessageLite msg, ByteBufAllocator allocator) { int size = msg.getSerializedSize(); ByteBuf buf = allocator.heapBuffer(size, size); try { msg.writeTo(new ByteBufOutputStream(buf)); } catch (IOException e) { // This is in-memory serialization, should not fail throw new RuntimeException(e); } return buf; }
Source:
public void testEncodeOutputControl() { Tk103ProtocolEncoder encoder = new Tk103ProtocolEncoder(); Command command = new Command(); command.setDeviceId(1); command.setType(Command.TYPE_OUTPUT_CONTROL); command.set(Command.KEY_INDEX, 0); START command.set(Command.KEY_DATA, "1"); END assertEquals("(123456789012345AV001)", encoder.encodeCommand(command)); } Is this the value we use for all other protocols?

Target:
public void testEncodeOutputControl() { Tk103ProtocolEncoder encoder = new Tk103ProtocolEncoder(); Command command = new Command(); command.setDeviceId(1); command.setType(Command.TYPE_OUTPUT_CONTROL); command.set(Command.KEY_DATA, "1"); assertEquals("(123456789012345AV001)", encoder.encodeCommand(command)); }
Source:
void cancel() { super.cancel(); START if (callback != null) { END callback = null; } } No `if` check needed, just always set the reference to `null`.

Target:
@Override void cancel() { super.cancel(); callback = null; }
Source:
public void cancel() { try { Field field = FileWatchdog.class.getDeclaredField("interrupted"); field.setAccessible(true); field.set(this, true); } catch (ReflectiveOperationException cause) { START throw new Error("Cannot cancel log4j watchdog", cause); END } } `new Error` -> `new RuntimeException`

Target:
public void cancel() { try { Field field = FileWatchdog.class.getDeclaredField("interrupted"); field.setAccessible(true); field.set(this, true); } catch (ReflectiveOperationException cause) { throw new RuntimeException("Cannot cancel log4j watchdog", cause); } }
Source:
public static boolean isEditAllowed(@NonNull PageTitle title) { return START Arrays.asList(ENABLED_LANGUAGES).contains(title.getWikiSite().languageCode()); END } Very minor: it's probably cleaner just to initialized ENABLED_LANGUAGES using Arrays.asList

Target:
public static boolean isEditAllowed(@NonNull PageTitle title) { return ENABLED_LANGUAGES.contains(title.getWikiSite().languageCode()); }
Source:
private InputStream simulateSendAndReceive(ByteArrayOutputStream baos) throws IOException { byte[] bytes = baos.toByteArray(); baos.reset(); START int testMessageNo = 1; END PacketFormat format = new PacketFormat(testMessageNo, bytes); format.serialize(baos); return new ByteArrayInputStream(baos.toByteArray()); } Why is this hardcoded? and why is it 1 not 0?

Target:
private InputStream simulateSendAndReceive(ByteArrayOutputStream baos) throws IOException { return new ByteArrayInputStream(baos.toByteArray()); }
Source:
public ShovingMatch(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.INSTANT}, "{2}{U}"); // Until end of turn, all creatures gain "{tap}: Tap target creature." START Ability ability = new SimpleActivatedAbility(Zone.BATTLEFIELD, new TapTargetEffect(), new TapSourceCost()); END ability.addTarget(new TargetCreaturePermanent()); this.getSpellAbility().addEffect( new GainAbilityAllEffect(ability, Duration.EndOfTurn, new FilterCreaturePermanent()) .setText("Until end of turn, all creatures gain \"{T}: Tap target creature.\"") ); } This wasn't necessary, I was using the constructor I added that defaults to battlefield because most activated abilities are on the battlefield anyway. It doesn't really matter, I just figured I'd mention it.

Target:
public ShovingMatch(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.INSTANT}, "{2}{U}"); // Until end of turn, all creatures gain "{tap}: Tap target creature." Ability ability = new SimpleActivatedAbility(new TapTargetEffect(), new TapSourceCost()); ability.addTarget(new TargetCreaturePermanent()); this.getSpellAbility().addEffect( new GainAbilityAllEffect(ability, Duration.EndOfTurn, new FilterCreaturePermanent()) .setText("Until end of turn, all creatures gain \"{T}: Tap target creature.\"") ); }
Source:
public void testCompareRanges() { START assertTrue(compareRanges("abcdefghij".getBytes(), 0, 10, "abcdefghij".getBytes(), 0, 10) == 0); END assertTrue(compareRanges("123abcdefghij".getBytes(), 3, 10, "abcdefghij".getBytes(), 0, 10) == 0); } Use `assertEquals`

Target:
public void testCompareRanges() { assertEquals(compareRanges("abcdefghij".getBytes(), 0, 10, "abcdefghij".getBytes(), 0, 10), 0); assertEquals(compareRanges("123abcdefghij".getBytes(), 3, 10, "abcdefghij".getBytes(), 0, 10), 0); }
Source:
public void setRequiredParametersForCreation(DateTime paymentDate, Timeframe timeframe, Integer requestedAmount, Boolean build){ this.paymentDate = paymentDate; this.timeframe = timeframe; this.requestedAmount = requestedAmount; //??? if(build){ this.build = build; }else{ START this.building = build; END } } Verificar necessidade desse else

Target:
public void setRequiredParametersForCreation(DateTime paymentDate, Timeframe timeframe, Integer requestedAmount, Boolean build){ this.paymentDate = paymentDate; this.timeframe = timeframe; this.requestedAmount = requestedAmount; if(build){ this.build = build; } }
Source:
public TestElasticsearchIntegrationSmokeTest(EmbeddedElasticsearchNode embeddedElasticsearchNode) START throws Exception END { super(() -> createElasticsearchQueryRunner(embeddedElasticsearchNode, TpchTable.getTables())); this.embeddedElasticsearchNode = embeddedElasticsearchNode; } unnecessary `throws` (same for the constructor above).

Target:
public TestElasticsearchIntegrationSmokeTest(EmbeddedElasticsearchNode embeddedElasticsearchNode) { super(() -> createElasticsearchQueryRunner(embeddedElasticsearchNode, TpchTable.getTables())); this.embeddedElasticsearchNode = embeddedElasticsearchNode; }
Source:
public CommandResult exec(ContextAwareCommandInvocation commandInvocation) { START if (help) { END commandInvocation.println(commandInvocation.getHelpInfo()); } return CommandResult.SUCCESS; } print help all the time? the command `> server` alone isn't valid.

Target:
public CommandResult exec(ContextAwareCommandInvocation commandInvocation) { commandInvocation.println(commandInvocation.getHelpInfo()); return CommandResult.SUCCESS; }
Source:
for (OsType type : OsType.values()) { START osTypeValues.add(type.value().toLowerCase()); END } .value() returns .name().toLowerCase()

Target:
for (OsType type : OsType.values()) { osTypeValues.add(type.value()); }
Source:
private Menu fillMenu(Menu m) { for (IAction action : getActions()) { IContributionItem item; String actionText = action.getText(); if (actionText == null || actionText.isEmpty()) { item = new Separator(); } else { item = new ActionContributionItem(action); START } END item.fill(m, -1); } return m; } Why don't you change getAction() to return a Collection<ContributionItem>?

Target:
private Menu fillMenu(Menu m) { for (IContributionItem item : getActions()) { item.fill(m, -1); } return m; }
Source:
public void testThreadNameWithoutNumberNoDemon() { START Assert.assertEquals(ThreadUtils.createThreadFactory(THREAD_NAME, false). END newThread(EMPTY_RUNNABLE).getName(), THREAD_NAME); } In all `assert` method, the first argument is the "expected" value while the second one is the "actual" value. Can you swap them in this file to match that definition?

Target:
public void testThreadNameWithoutNumberNoDemon() { assertEquals(THREAD_NAME, ThreadUtils.createThreadFactory(THREAD_NAME, false). newThread(EMPTY_RUNNABLE).getName()); }
Source:
public <T> ModelAdaptor<? super T> getModelAdaptor(Class<T> attributeType) { //noinspection unchecked START return (ModelAdaptor<T>) adaptors.get(attributeType); END } ```suggestion return (ModelAdaptor<? super T>) adaptors.get(attributeType); ```

Target:
public <T> ModelAdaptor<? super T> getModelAdaptor(Class<T> attributeType) { //noinspection unchecked return (ModelAdaptor<? super T>) adaptors.get(attributeType); }
Source:
public com.google.gwtorm.client.Key<?>[] members() { START return new com.google.gwtorm.client.Key<?>[] {accountId, patchKey}; END } If you override accountId then the parentKey is automatically a member, and this needs to only include the patchKey.

Target:
public com.google.gwtorm.client.Key<?>[] members() { return new com.google.gwtorm.client.Key<?>[] {patchKey}; }
Source:
public void init(final RuleModellerPage page) { this.page = page; if (page.plugin() instanceof BRLActionColumnPlugin) { START END } } If it is then do what exactly? If we don't want to do anything do we need this ```if(..)``` block at all?

Target:
public void init(final RuleModellerPage page) { this.page = page; }
Source:
START @Override public TaskResult syncShards() { END return periodicShardSyncManager.start(); } nit: Could you have `Override` in its own line.

Target:
public TaskResult syncShards() { return periodicShardSyncManager.start(); }
Source:
static <T> List<T> without(List<T> list, Collection<Integer> indexes) { Set<Integer> indexesSet = ImmutableSet.copyOf(indexes); return IntStream.range(0, list.size()) .filter(index -> !indexesSet.contains(index)) START .mapToObj(ImmutableList.copyOf(list)::get) END .collect(toImmutableList()); } Drop this `ImmutableList.copyOf` wrapper. It reduces clarity and we do expect random-access lists here anyway.

Target:
static <T> List<T> without(List<T> list, Collection<Integer> indexes) { Set<Integer> indexesSet = ImmutableSet.copyOf(indexes); return IntStream.range(0, list.size()) .filter(index -> !indexesSet.contains(index)) .mapToObj(list::get) .collect(toImmutableList()); }
Source:
private Throwable getRealException(Throwable re) { if (re.getCause() == null) return re; Throwable cause = re.getCause(); START if (cause instanceof CacheException || cause instanceof RuntimeException || cause instanceof Error) END return getRealException(cause); else return re; } CacheException instanceOf RuntimeException, I guess you can simplify here.

Target:
private Throwable getRealException(Throwable re) { if (re.getCause() == null) return re; Throwable cause = re.getCause(); if (cause instanceof RuntimeException || cause instanceof Error) return getRealException(cause); else return re; }
Source:
public void layoutIfNecessary() { if (dirtySize != null && control != null && control instanceof Composite) { if (control.getSize().equals(dirtySize)) { START ((Composite) control).layout(); END flushChildren = false; } } dirtySize = null; } What does this change do?

Target:
public void layoutIfNecessary() { if (dirtySize != null && control != null && control instanceof Composite) { if (control.getSize().equals(dirtySize)) { ((Composite)control).layout(flushChildren); flushChildren = false; } } dirtySize = null; }
Source:
public Attribute setLabelAttribute(Boolean isLabelAttr) { set(IS_LABEL_ATTRIBUTE, isLabelAttr); START if (isLabelAttr != null && isLabelAttr) END { setNillable(false); } return this; } We ususally don't put the logic in the entity class. Will be confusing that this setter has side effects: `addAttribute("blah").setNillable(true).setLabelAttribute(true)`

Target:
public Attribute setLabelAttribute(Boolean isLabelAttr) { set(IS_LABEL_ATTRIBUTE, isLabelAttr); return this; }
Source:
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof IntegrationEvaluationContextAware) { StandardEvaluationContext evaluationContext = IntegrationContextUtils.getEvaluationContext(beanFactory); if (bean instanceof IntegrationObjectSupport) { ConversionService conversionService = ((IntegrationObjectSupport) bean).getConversionService(); START if (conversionService != null) { END evaluationContext.setTypeConverter(new StandardTypeConverter(conversionService)); } } ((IntegrationEvaluationContextAware) bean).setIntegrationEvaluationContext(evaluationContext); } return bean; } So, maybe just remove this code for now? And keep in mind it. However I remember this one: https://github.com/SpringSource/spring-integration/pull/827#issuecomment-20274110 I mean to rely just only on 'system-wide conversion service', not from endpoint.

Target:
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof IntegrationEvaluationContextAware) { StandardEvaluationContext evaluationContext = IntegrationContextUtils.getEvaluationContext(this.beanFactory); ((IntegrationEvaluationContextAware) bean).setIntegrationEvaluationContext(evaluationContext); } return bean; }
Source:
public <R, X extends Exception> R withHandle(HandleCallback<R, X> callback) throws X { Handle h = JdbiUtil.getHandle(jdbi); R result = callback.withHandle(h); // close if not in transaction START JdbiUtil.closeIfNeeded(h); END return result; } I believe we shouldn't close the handle here. It will be closed in the `afterCompletion` method. I think also it will probably be ignored because the handle is still binded to the active transaction.

Target:
public <R, X extends Exception> R withHandle(HandleCallback<R, X> callback) throws X { Handle h = JdbiUtil.getHandle(jdbi); try { return callback.withHandle(h); } finally { JdbiUtil.closeIfNeeded(h); } }
Source:
START public LanguageServerWrapper(@Nullable IProject project, @NonNull LanguageServerDefinition serverDefinition, END @Nullable IPath initialPath) { this.initialProject = project; this.initialPath = initialPath; this.allWatchedProjects = new HashSet<>(); this.serverDefinition = serverDefinition; this.connectedDocuments = new HashMap<>(); } In this case, shouldn't we getrid of the project parameter here (if we know the project, we shouldn't specify an extra initial path, or we should explicitly use the initial path.

Target:
private LanguageServerWrapper(@Nullable IProject project, @NonNull LanguageServerDefinition serverDefinition, @Nullable IPath initialPath) { this.initialProject = project; this.initialPath = initialPath; this.allWatchedProjects = new HashSet<>(); this.serverDefinition = serverDefinition; this.connectedDocuments = new HashMap<>(); }
Source:
public String getReplicaPath() { // GetRequest.Cloud_Replica_Keyword is added to avoid error on its peers. START return getMountPath() + File.separator + GetRequest.Cloud_Replica_Keyword + File.separator END + partitionId.toPathString(); } minor: would prefer that `Cloud_Replica_Keyword` comes before mount path since that would order the path from least to most granular

Target:
public String getReplicaPath() { // GetRequest.Cloud_Replica_Keyword is added to avoid error on its peers. return GetRequest.Cloud_Replica_Keyword + File.separator + getMountPath() + File.separator + partitionId.toPathString(); }
Source:
public void addChildren(AlluxioURI path, Collection<UfsStatus> children) { UfsStatus status = mStatuses.get(path); // If this path doesn't yet exist, we can't keep track of the parent-child relationship // We can still add statuses to the cache regardless START if (status != null) { END mChildren.computeIfAbsent(path, ufsStatus -> new ConcurrentHashSet<>()).addAll(children); } children.forEach(child -> { AlluxioURI childPath = path.joinUnsafe(child.getName()); addStatus(childPath, child); }); } Why can't we add this parent->children listing cache even if the parent status is not in the other map?

Target:
public Collection<UfsStatus> addChildren(AlluxioURI path, Collection<UfsStatus> children) { ConcurrentHashSet<UfsStatus> set = new ConcurrentHashSet<>(); children.forEach(child -> { AlluxioURI childPath = path.joinUnsafe(child.getName()); addStatus(childPath, child); set.add(child); }); return mChildren.put(path, set); }
Source:
private void actionCompleted(SegmentHolder segmentHolder) { switch (segmentHolder.getType()) { case LOAD: segmentsToLoad.remove(segmentHolder.getSegment()); queuedSize.addAndGet(-segmentHolder.getSegmentSize()); break; case DROP: segmentsToDrop.remove(segmentHolder.getSegment()); break; default: throw new UnsupportedOperationException(); } callBackExecutor.execute( START () -> executeCallbacks(segmentHolder) END ); } Pointless two level submission. `executeCallbacks()` submits each callback to itself another one time (this means that it's valuable to annotate each method in this class in which executor it's supposed to be run. Given that there are two different executors, plus "external", client code execution context (which we kind of shouldn't know where runs)

Target:
private void actionCompleted(SegmentHolder segmentHolder) { switch (segmentHolder.getType()) { case LOAD: segmentsToLoad.remove(segmentHolder.getSegment()); queuedSize.addAndGet(-segmentHolder.getSegmentSize()); break; case DROP: segmentsToDrop.remove(segmentHolder.getSegment()); break; default: throw new UnsupportedOperationException(); } executeCallbacks(segmentHolder); }
Source:
public ScheduledReporter build(MetricRegistry registry) { GraphiteReporter.Builder builder = builder(registry); START if ("udp".equalsIgnoreCase(this.transport)) { END return builder.build(new GraphiteUDP(host, port)); } else { return builder.build(new Graphite(host, port)); } } Is `this` needed here? If not, consider dropping it.

Target:
public ScheduledReporter build(MetricRegistry registry) { GraphiteReporter.Builder builder = builder(registry); if ("udp".equalsIgnoreCase(transport)) { return builder.build(new GraphiteUDP(host, port)); } else { return builder.build(new Graphite(host, port)); } }
Source:
public void onReceiveHangUpFromUser(QBRTCSession session, Integer userId) { setStatusForOpponent(userId, getString(R.string.text_status_hang_up)); Log.d(TAG, "onReceiveHangUpFromUser userId= " + userId); if (!isPeerToPeerCall) { if (userId == userIDFullScreen) { Log.d(TAG, "setAnotherUserToFullScreen call userId= " + userId); setAnotherUserToFullScreen(); } START if (videoTrackMap != null && videoTrackMap.containsKey(userId)) { END Log.d(TAG, "onReceiveHangUpFromUser videoTrackMap.remove(userId)= " + userId); videoTrackMap.remove(userId); } } } опять копипаст) у тебя ж сверху в onConnectionClosedForUser точно такой код, И вообще если мы удаляем в onConnectionClosedForUser , то зачем еще здесь? onConnectionClosedForUser в любом случае срабатывает когда с юзером связь остаточно закрылась,

Target:
public void onReceiveHangUpFromUser(QBRTCSession session, Integer userId) { setStatusForOpponent(userId, getString(R.string.text_status_hang_up)); Log.d(TAG, "onReceiveHangUpFromUser userId= " + userId); if (!isPeerToPeerCall) { if (userId == userIDFullScreen) { Log.d(TAG, "setAnotherUserToFullScreen call userId= " + userId); setAnotherUserToFullScreen(); } } }
Source:
private boolean isThis(ExpressionTree expression) { START ExpressionTree expressionNoParenthesis = (ExpressionUtils.skipParentheses(expression)); END if (expressionNoParenthesis.is(Tree.Kind.IDENTIFIER)) { String targetName = ((IdentifierTree) expressionNoParenthesis).name(); return "this".equals(targetName); } return false; } useless parentheses

Target:
private boolean isThis(ExpressionTree expression) { ExpressionTree expressionNoParenthesis = ExpressionUtils.skipParentheses(expression); if (expressionNoParenthesis.is(Tree.Kind.IDENTIFIER)) { String targetName = ((IdentifierTree) expressionNoParenthesis).name(); return "this".equals(targetName); } return false; }
Source:
protected Map<String, Queue> getQueueNamesToQueues() { return this.queues.stream() START .collect(Collectors.toMap(q -> q.getActualName(), q -> q)); END } `Queue::getActualName` ?

Target:
protected Map<String, Queue> getQueueNamesToQueues() { return this.queues.stream() .collect(Collectors.toMap(Queue::getActualName, q -> q)); }
Source:
public String toString() { Bundle myBundle = getBundle(); if (myBundle == null) return ""; //$NON-NLS-1$ String name = myBundle.getSymbolicName(); START return name == null ? Long.valueOf(myBundle.getBundleId()).toString() : name; END } Using String.valueOf(myBundle.getBundleId()) would make more sense than .valueOf.toString

Target:
public String toString() { Bundle myBundle = getBundle(); if (myBundle == null) return ""; //$NON-NLS-1$ String name = myBundle.getSymbolicName(); return name == null ? String.valueOf(myBundle.getBundleId()) : name; }
Source:
public void workbenchSelectionChanged(ISelection selection) { Object o = SelectionUtils.getSelectedObject(selection); if (o instanceof TextSelection) { String text = ((TextSelection) o).getText(); m_sourceGraphControl.setSourceText(text); START } else if (o == null) { END m_sourceGraphControl.setSourceText(""); //$NON-NLS-1$ } } The test on the "else" case isn't needed -- if it's anything but a TextSelection the text can be set to the emprty string.

Target:
public void workbenchSelectionChanged(ISelection selection) { Object o = SelectionUtils.getSelectedObject(selection); if (o instanceof TextSelection) { String text = ((TextSelection) o).getText(); m_sourceGraphControl.setSourceText(text); } else { m_sourceGraphControl.setSourceText(""); //$NON-NLS-1$ } }
Source:
START public JBlock getOnDestroyViewAfterSuperBlock() { END if (onDestroyViewAfterSuperBlock == null) { setContentViewRelatedMethods(); } return onDestroyViewAfterSuperBlock; } This could be private if you move the field creation to the holder as i suggested.

Target:
private JBlock getOnDestroyViewAfterSuperBlock() { if (onDestroyViewAfterSuperBlock == null) { setContentViewRelatedMethods(); } return onDestroyViewAfterSuperBlock; }
Source:
public boolean hasChildren(Object element) { START return ((MyModel) element).children.size() > 0; END } Use isEmpty() to check whether the collection is empty or not.

Target:
public boolean hasChildren(Object element) { return !((MyModel) element).children.isEmpty(); }
Source:
public GroupedPropertyList getPropertyList() { if (propertyList == null) { START try{ END boolean parallel = true; long t1 = System.currentTimeMillis(); propertyList = new GroupedPropertyList(individual, vreq, editing,parallel); log.debug(" getPropertyList parallel: "+parallel+" time :"+(System.currentTimeMillis()-t1)+" ms"); }catch(Exception e) { e.printStackTrace(); } } return propertyList; } I believe we can remove the `try`/`catch` wrappers. No checked Exceptions are thrown. Is there a particular Exception you are anticipating?

Target:
public GroupedPropertyList getPropertyList() throws Exception { propertyList = new GroupedPropertyList(individual, vreq, editing); return propertyList; }
Source:
private void doTheTest(UserGroup g0) { String s = MARSHALER.marshal(g0); UserGroup ug = MARSHALER.unmarshal(s); START System.out.println(g0); END System.out.println(ug); System.out.println(s); assertTrue(g0.equals(ug)); } Remove this ones

Target:
private void doTheTest(UserGroup g0) { String s = MARSHALER.marshal(g0); UserGroup ug = MARSHALER.unmarshal(s); assertTrue(g0.equals(ug)); }
Source:
String getConstraintType() { final ConstraintType constraintType = presenter.getConstraintType(); START if (constraintType == null) { END return presenter.inferComponentType(presenter.getConstraintValue()).value(); } else { return constraintType.toString(); } } This too would benefit from the (proposed) `ConstraintType.EMPTY` enumeration item.

Target:
private String getConstraintType() { if (presenter.getConstraintType() == null) { return presenter.inferComponentType(presenter.getConstraintValue()).value(); } else { return presenter.getConstraintType().toString(); } }
Source:
private WikipediaApp getApplication() { START return (WikipediaApp) getPageActivity().getApplication(); END } How about WikipediaApp.getInstance() instead?

Target:
private WikipediaApp getApplication() { return WikipediaApp.getInstance(); }
Source:
START public boolean isHostedEngineDirectLunDisk() { END return disk.getDiskStorageType() == DiskStorageType.LUN && StorageConstants.HOSTED_ENGINE_LUN_DISK_ALIAS.equals(disk.getDiskAlias()); } Should this be public or private? It is used only in the validator

Target:
private boolean isHostedEngineDirectLunDisk() { return disk.getDiskStorageType() == DiskStorageType.LUN && StorageConstants.HOSTED_ENGINE_LUN_DISK_ALIAS.equals(disk.getDiskAlias()); }
Source:
START public CommunityRest getParentCommunity(@Nullable HttpServletRequest httpServletRequest, END UUID collectionId, @Nullable Pageable optionalPageable, Projection projection) { try { Context context = obtainContext(); Collection collection = collectionService.find(context, collectionId); Community parentCommunity = (Community) collectionService.getParentObject(context, collection); if (collection == null) { throw new ResourceNotFoundException("No such collection: " + collectionId); } return converter.toRest(parentCommunity, projection); } catch (SQLException e) { throw new RuntimeException(e); } } Same here, JavaDocs for this method please

Target:
public CommunityRest getParentCommunity(@Nullable HttpServletRequest httpServletRequest, UUID collectionId, @Nullable Pageable optionalPageable, Projection projection) { try { Context context = obtainContext(); Collection collection = collectionService.find(context, collectionId); if (collection == null) { throw new ResourceNotFoundException("No such collection: " + collectionId); } Community parentCommunity = (Community) collectionService.getParentObject(context, collection); return converter.toRest(parentCommunity, projection); } catch (SQLException e) { throw new RuntimeException(e); } }
Source:
public List<WorkflowAction> findActions(List<WorkflowStep> steps, User user) throws DotDataException, DotSecurityException { START List<WorkflowAction> actions = new ArrayList<>(); END for(WorkflowStep step : steps) { actions.addAll(workFlowFactory.findActions(step)); } actions = APILocator.getPermissionAPI().filterCollection(actions, PermissionAPI.PERMISSION_USE, true, user); return actions; } Immutable

Target:
public List<WorkflowAction> findActions(List<WorkflowStep> steps, User user) throws DotDataException, DotSecurityException { final ImmutableList.Builder<WorkflowAction> actions = new ImmutableList.Builder<>(); for(WorkflowStep step : steps) { actions.addAll(workFlowFactory.findActions(step)); } return APILocator.getPermissionAPI().filterCollection(actions.build(), PermissionAPI.PERMISSION_USE, true, user); }
Source:
private String updateIconUri(MPart part) { MPartDescriptor desc = modelService.getPartDescriptor(part.getElementId()); START String iconURI = desc != null && desc.getIconURI() != null ? desc.getIconURI() : part.getIconURI(); END part.getTransientData().put(ICON_URI_FOR_PART, iconURI); return iconURI; } This code raises two more (previously existing) concerns: 1. Which iconURI has higher priority the descriptor or the part? 2. What happens if the iconURI of the descriptor is changed?

Target:
private String updateIconUri(MPart part) { MPartDescriptor desc = modelService.getPartDescriptor(part.getElementId()); String iconURI = part.getIconURI(); if (iconURI == null && desc != null) { iconURI = desc.getIconURI(); } part.getTransientData().put(ICON_URI_FOR_PART, iconURI); return iconURI; }
Source:
private Map<String, Pair<Class, Object>> getOverriddenReturnTypes(){ //Add attributes with 'smart' getters and setters that convert back and forth to correct values for MOLGENIS datatypes //Provide the attribute name as key, and a pair of returntype (Class) and a Object to be used as test value Map<String, Pair<Class, Object>> map = new HashMap<>(); START return map; END } This will throw redundancy warnings in IntelliJ

Target:
private Map<String, Pair<Class, Object>> getOverriddenReturnTypes(){ //Add attributes with 'smart' getters and setters that convert back and forth to correct values for MOLGENIS datatypes //Provide the attribute name as key, and a pair of return type (Class) and an Object to be used as test value return new HashMap<>(); }
Source:
START public String getParentId(String testId) { END return (String) getHibernateTemplate().find("select distinct w.parentId from WorkloadData w where w.taskId=? and w.sessionId=?", testId, sessionId).get(0); } why is it public?

Target:
private String getParentId(String testId) { return (String) getHibernateTemplate().find("select distinct w.parentId from WorkloadData w where w.taskId=? and w.sessionId=?", testId, sessionId).get(0); }
Source:
protected void executeQueryCommand() { List<Disk> diskList = DbFacade.getInstance() .getDiskDao() .getAllAttachableDisksByPoolId(getParameters().getStoragePoolId(), getParameters().getVmId(), getUserID(), getParameters().isFiltered()); if (CollectionUtils.isEmpty(diskList)) { START setReturnValue(new ArrayList<>()); END return; } setReturnValue(filterDisks(diskList)); } Why can't you just return diskList? If I'm not mistaken DbFacade does not return null lists, only empty

Target:
protected void executeQueryCommand() { List<Disk> diskList = DbFacade.getInstance() .getDiskDao() .getAllAttachableDisksByPoolId(getParameters().getStoragePoolId(), getParameters().getVmId(), getUserID(), getParameters().isFiltered()); if (CollectionUtils.isEmpty(diskList)) { setReturnValue(diskList); return; } setReturnValue(filterDisks(diskList)); }
Source:
public JoinFilterPreAnalysis computeJoinFilterPreAnalysisIfAbsent( Filter filter, List<JoinableClause> clauses, VirtualColumns virtualColumns ) { // Some filters have potentially expensive hash codes that are lazily computed and cached. // We call hashCode() here in a synchronized block before we attempt to use the Filter in the analyses map, // to ensure that the hashCode is only computed once per Filter since the Filter interface is not thread-safe. synchronized (analyses) { if (filter != null) { START filter.hashCode(); END } } JoinFilterPreAnalysisGroupKey key = new JoinFilterPreAnalysisGroupKey(filter, clauses, virtualColumns); return analyses.computeIfAbsent( key, (groupKey) -> { return JoinFilterAnalyzer.computeJoinFilterPreAnalysis( JoinableClauses.fromList(clauses), virtualColumns, filter, joinFilterRewriteConfig ); } ); } Oh, is this why we don't need thread-safety on filter hashcode methods i guess? This seems kind of a funny way to prime them with the cached values, I think maybe the supplier.memoize pattern would be a little cleaner and make this not necessary?

Target:
public JoinFilterPreAnalysis computeJoinFilterPreAnalysisIfAbsent( Filter filter, List<JoinableClause> clauses, VirtualColumns virtualColumns ) { JoinFilterPreAnalysisGroupKey key = new JoinFilterPreAnalysisGroupKey(filter, clauses, virtualColumns); return analyses.computeIfAbsent( key, (groupKey) -> { return JoinFilterAnalyzer.computeJoinFilterPreAnalysis( JoinableClauses.fromList(clauses), virtualColumns, filter, joinFilterRewriteConfig ); } ); }