auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public int findWikiIndex(String wikiCode) { START int index = ArrayUtils.indexOf(getWikiCodes(), wikiCode); END if (index == ArrayUtils.INDEX_NOT_FOUND) { // FIXME: Instrument this with EL to find out what is happening on places where there is a lang we can't find // In the meantime, just fall back to en. See https://bugzilla.wikimedia.org/show_bug.cgi?id=66140 return findWikiIndex(FALLBACK_WIKI_LANG_CODE); } return index; } Couldn't we just use Arrays.asList(getWikiCodes).indexOf(wikiCode) instead of importing a whole new library?

Target:
public int findWikiIndex(String wikiCode) { int index = getWikiCodes().indexOf(wikiCode); if (index == -1) { // FIXME: Instrument this with EL to find out what is happening on places where there is a lang we can't find // In the meantime, just fall back to en. See https://bugzilla.wikimedia.org/show_bug.cgi?id=66140 return findWikiIndex(FALLBACK_WIKI_LANG_CODE); } return index; }
Source:
public void testRayCasting(){ final double[][] platform = {{ 59.8925348, 10.5242855}, { 59.8927012, 10.524743}, { 59.8926397, 10.5248089}, {59.8924888, 10.5243485}}; double[] testPointInside = { 59.8926474, 10.524729}; double[] testPointOutside = { 59.8925344, 10.5249007}; START assert(PlatformLinker.contains(platform, testPointInside)); END assert(!PlatformLinker.contains(platform, testPointOutside)); } nit: I would prefer to use the junit assertion functions.

Target:
public void testRayCasting(){ final double[][] platform = {{10.5242855, 59.8925348}, {10.524743, 59.8927012}, { 10.5248089, 59.8926397}, {10.5243485, 59.8924888}}; double[] testPointInside = { 10.524729, 59.8926474}; double[] testPointOutside = { 10.5249007, 59.8925344}; assert(PlatformLinker.contains(platform, testPointInside)); assert(!PlatformLinker.contains(platform, testPointOutside)); }
Source:
public void init() { try { eventBus.registerSubscriber(this); // Must set the initial status START currentStatus.compareAndSet(InstanceInfo.InstanceStatus.UNKNOWN, client.getInstanceRemoteStatus()); END } catch (InvalidSubscriberException e) { LOG.error("Error registring for discovery status change events.", e); } } @PostConstruct would not be called concurrently, rite? Do we need the current status as AtomicRef?

Target:
public void init() { try { eventBus.registerSubscriber(this); // Must set the initial status currentStatus = client.getInstanceRemoteStatus(); } catch (InvalidSubscriberException e) { LOG.error("Error registring for discovery status change events.", e); } }
Source:
public static void insertPageProlog(StringBuilder buffer, int position) { StringBuilder pageProlog= new StringBuilder(60); pageProlog.append("<html>"); //$NON-NLS-1$ buffer.append("<head>"); //$NON-NLS-1$ appendStyleSheetWithBodyColorRules(pageProlog, FG_COLOR_RGB, BG_COLOR_RGB); START buffer.append("</head>"); //$NON-NLS-1$ END buffer.insert(position, pageProlog.toString()); } Shouldn't this be appended to pageProlog?

Target:
public static void insertPageProlog(StringBuilder buffer, int position) { StringBuilder pageProlog= new StringBuilder(60); pageProlog.append("<html>"); //$NON-NLS-1$ pageProlog.append("<head>"); //$NON-NLS-1$ appendStyleSheetWithBodyColorRules(pageProlog, FG_COLOR_RGB, BG_COLOR_RGB); pageProlog.append("</head>"); //$NON-NLS-1$ buffer.insert(position, pageProlog.toString()); }
Source:
private void verifyCertificateChain(final List<X509Certificate> certificates) throws GeneralSecurityException, AuthenticationException { // create certificate chain, find the self signed cert first and chain all the way back // to the signer cert. Also perform certificate signing validation when chaining them back. X509Certificate issuerCert = getSelfSignedCert(certificates); final TrustAnchor trustAnchor = new TrustAnchor(issuerCert, null); START PKIXParameters pkixParameters = new PKIXParameters(Collections.singleton(trustAnchor)); END pkixParameters.setRevocationEnabled(false); final CertPath certPath = CertificateFactory.getInstance("X.509") .generateCertPath(certificates); final CertPathValidator certPathValidator = CertPathValidator.getInstance("PKIX"); certPathValidator.validate(certPath, pkixParameters); } final?

Target:
private void verifyCertificateChain(final List<X509Certificate> certificates) throws GeneralSecurityException, AuthenticationException { // create certificate chain, find the self signed cert first and chain all the way back // to the signer cert. Also perform certificate signing validation when chaining them back. final X509Certificate issuerCert = getSelfSignedCert(certificates); final TrustAnchor trustAnchor = new TrustAnchor(issuerCert, null); final PKIXParameters pkixParameters = new PKIXParameters(Collections.singleton(trustAnchor)); pkixParameters.setRevocationEnabled(false); final CertPath certPath = CertificateFactory.getInstance("X.509") .generateCertPath(certificates); final CertPathValidator certPathValidator = CertPathValidator.getInstance("PKIX"); certPathValidator.validate(certPath, pkixParameters); }
Source:
public Set<Class<?>> getClasses() { final Set<Class<?>> classes = new HashSet<>(); classes.add(HelloResource.class); classes.add(PureProxyEndPoint.class); START classes.add(HelloBadResource.class); END classes.add(HelloSometimesBadResource.class); return classes; } This change causes regression of JaxrsRuntimeNameTestCase. JaxrsRuntimeNameTestCase uses HelloApplication.java as well, but HelloBadResource is not added to the deployment from JaxrsRuntimeNameTestCase. So JaxrsRuntimeNameTestCase fails.

Target:
public Set<Class<?>> getClasses() { final Set<Class<?>> classes = new HashSet<>(); classes.add(HelloResource.class); classes.add(PureProxyEndPoint.class); return classes; }
Source:
START private void reconnectExceptionally(final String message) throws DatabaseEngineException { try { getConnection(); } catch (final Exception e) { throw new DatabaseEngineException(message, e); } } END Subclasses are also doing this. The method should be _protected_, and the same code should be replaced by a call to this method in the subclasses.

Target:
protected void reconnectExceptionally(final String message) throws DatabaseEngineException { try { getConnection(); } catch (final Exception e) { throw new DatabaseEngineException(message, e); } }
Source:
public Aggregator factorize(ColumnSelectorFactory metricFactory) { return new LongLastAggregator( name, metricFactory.makeLongColumnSelector(fieldName), START metricFactory.makeLongColumnSelector(Column.TIME_COLUMN_NAME) END ); } minor nit: can we pass time column selector before field selector to be consistent with buffered aggregator ?

Target:
public Aggregator factorize(ColumnSelectorFactory metricFactory) { return new LongLastAggregator( name, metricFactory.makeLongColumnSelector(Column.TIME_COLUMN_NAME), metricFactory.makeLongColumnSelector(fieldName) ); }
Source:
protected void logToAudit(){ START super.logToAudit(); END if (isPolicyResetMessage(getReturnStatus().message)) { return; } AuditLogableBase auditLogableBase = new AuditLogableBase(vds.getId()); auditLogableBase.setVds(vds); auditLogableBase.addCustomValue("message", getReturnStatus().message); auditLogDirector.log(auditLogableBase, AuditLogType.VDS_BROKER_COMMAND_FAILURE); } This won't do what you think. The base class should probably have a sholdLog() method, and the caller should implement protected final void logToAudit() { if (shouldLog()) { realLogToAudit()); } }

Target:
protected void logToAudit(){ if (isPolicyResetMessage(getReturnStatus().message)) { return; } AuditLogableBase auditLogableBase = new AuditLogableBase(vds.getId()); auditLogableBase.setVds(vds); auditLogableBase.addCustomValue("message", getReturnStatus().message); auditLogDirector.log(auditLogableBase, AuditLogType.VDS_BROKER_COMMAND_FAILURE); }
Source:
START protected String gtk_rgba_to_css_string (GdkRGBA rgba) { END String color = "rgba(" + (int)(rgba.red * 255) + "," + (int)(rgba.green * 255) + "," + (int)(rgba.blue * 255) + "," + (int)(rgba.alpha * 255) + ")"; return color; } This should not be protected but package.

Target:
String gtk_rgba_to_css_string (GdkRGBA rgba) { /* * In GdkRGBA, values are a double between 0-1.<br> * In CSS, values are typically integers between 0-255.<br> * I.e, note, there is a slight loss of precision. * Thus setting/getting color *might* return slight differences. */ String color = "rgba(" + (int)(rgba.red * 255) + "," + (int)(rgba.green * 255) + "," + (int)(rgba.blue * 255) + "," + (int)(rgba.alpha * 255) + ")"; return color; }
Source:
public FileMode getMode(File f, FS.Attributes attributes) { START if (attributes.isSymbolicLink()) END return FileMode.SYMLINK; else if (attributes.isDirectory()) { if (new File(f, Constants.DOT_GIT).exists()) return FileMode.GITLINK; else return FileMode.TREE; } else if (attributes.isExecutable()) return FileMode.EXECUTABLE_FILE; else return FileMode.REGULAR_FILE; } style nit: missing braces, the style guide was changed a while back since then we use braces around single line blocks

Target:
public FileMode getMode(File f, FS.Attributes attributes) { if (attributes.isSymbolicLink()) { return FileMode.SYMLINK; } else if (attributes.isDirectory()) { if (new File(f, Constants.DOT_GIT).exists()) { return FileMode.GITLINK; } else { return FileMode.TREE; } } else if (attributes.isExecutable()) { return FileMode.EXECUTABLE_FILE; } else { return FileMode.REGULAR_FILE; } }
Source:
public Map<String, Set<ExecutableElement>> setters() { START return Maps.transformValues(setters.asMap(), Sets::newHashSet); END } Move to constructor? We already do a defensive copy might as well front-load this work instead.

Target:
public Map<String, Set<ExecutableElement>> setters() { return setters; }
Source:
START public void sendBannerChange(Location location, CompoundTag nbt) throws NullPointerException { END sendBlockEntityChange(location, nbt, GlowBlockEntity.BANNER); } throws is not required

Target:
public void sendBannerChange(Location location, CompoundTag nbt) { sendBlockEntityChange(location, nbt, GlowBlockEntity.BANNER); }
Source:
public VfsFileChooserHelper( Shell shell, VfsFileChooserDialog fileChooserDialog, VariableSpace variableSpace, FileSystemOptions fileSystemOptions ) { this.fileChooserDialog = fileChooserDialog; this.shell = shell; this.variableSpace = variableSpace; this.fileSystemOptions = fileSystemOptions; START this.schemeRestrictions = new String[1]; END } @e-cuellar is the reason this is set to 1 because of line number 133? If so, I'd prefer this to be String[0], and add some safety on getSchemeRestriction() to check array length (because it could be 0, as set by setSchemeRestrictions). Looks like setSchemeRestriction needs to be a little smarter too. I'd suggest that if the API call setSchemeRestriction that we wipe the schemeRestriction and stuff it only with the incoming schemeRestriction.

Target:
public VfsFileChooserHelper( Shell shell, VfsFileChooserDialog fileChooserDialog, VariableSpace variableSpace, FileSystemOptions fileSystemOptions ) { this.fileChooserDialog = fileChooserDialog; this.shell = shell; this.variableSpace = variableSpace; this.fileSystemOptions = fileSystemOptions; this.schemeRestrictions = new String[0]; }
Source:
public static int getCurrentCounterValue() { return COUNTER.intValue(); START } END Default access (no modifier) suffices.

Target:
static int getCurrentCounterValue() { return COUNTER.intValue(); }
Source:
private void setCharset(String charsetName) { try { if (charsetName == null) { START this.charset = Charset.defaultCharset(); END } else { this.charset = Charset.forName(charsetName); } logger.debug("Serial port '{}' charset '{}' set.", this.port, charsetName); } catch (IllegalCharsetNameException e) { logger.error("Serial port '{}' charset '{}' not found.", this.port, charsetName); } } Should eliminate the extraneous use of `this.` throughout.

Target:
private void setCharset(String charsetName) { try { if (charsetName == null) { charset = Charset.defaultCharset(); } else { charset = Charset.forName(charsetName); } logger.debug("Serial port '{}' charset '{}' set.", port, charsetName); } catch (IllegalCharsetNameException e) { logger.warn("Serial port '{}' charset '{}' not found.", port, charsetName); charset = Charset.defaultCharset(); } }
Source:
void prepareView(final String type, final String constraintValue, final ConstraintType constraintType) { getView().setType(type); START if (!isEmpty(constraintValue)) { END getView().loadComponent(constraintType); } else { getView().setupEmptyContainer(); } } Now that we have the `constraintType `, we need change this to something like this: ```suggestion if (!isEmpty(constraintValue) || constraintType != null) { ``` Otherwise, when the user selects the "Expression" type and leaves the expression blank, the _Expression component_ wont be loaded.

Target:
void prepareView(final String type, final String constraintValue, final ConstraintType constraintType) { getView().setType(type); if (!isEmpty(constraintValue) || constraintType != null) { getView().loadComponent(constraintType); } else { getView().setupEmptyContainer(); } }
Source:
START public boolean shutdown() { END } I do not know much about databases but whether this method is properly constructed? My Eclipse returns "This method must return a result of type boolean" and I can add return for firstRun of false.

Target:
public boolean shutdown() { return true; }
Source:
public String getTitle() { START return Context.getMessageSourceService().getMessage("emrapi.title"); END } Why not just return "emrapi.title"?

Target:
public String getTitle() { return "emrapi.title"; }
Source:
public static String resolveName(Object context, String path) { Preconditions.checkNotNull(path, "path must not be null"); START if (path==null || path.startsWith("/") || Urls.isUrlWithProtocol(path)) return path; END Preconditions.checkNotNull(context, "context must not be null when path is relative"); return packagePath(context)+path; } Unnecessary null check for path; trivial; ignoring.

Target:
public static String resolveName(Object context, String path) { Preconditions.checkNotNull(path, "path must not be null"); if (path.startsWith("/") || Urls.isUrlWithProtocol(path)) return path; Preconditions.checkNotNull(context, "context must not be null when path is relative"); return packagePath(context)+path; }
Source:
private void sendCancelCommand(IntSet cancelledSegments) { START Address origin = rpcManager.getAddress(); END CacheRpcCommand cmd = commandsFactory.buildStateTransferCancelCommand(topologyId, cancelledSegments); try { rpcManager.sendTo(source, cmd, DeliverOrder.NONE); } catch (Exception e) { // Ignore exceptions here, the worst that can happen is that the provider will send some extra state log.debugf("Caught an exception while cancelling state transfer from node %s for segments %s", source, cancelledSegments); } } can be removed.

Target:
private void sendCancelCommand(IntSet cancelledSegments) { CacheRpcCommand cmd = commandsFactory.buildStateTransferCancelCommand(topologyId, cancelledSegments); try { rpcManager.sendTo(source, cmd, DeliverOrder.NONE); } catch (Exception e) { // Ignore exceptions here, the worst that can happen is that the provider will send some extra state log.debugf("Caught an exception while cancelling state transfer from node %s for segments %s", source, cancelledSegments); } }
Source:
public void heartbeat() { // Sync the pin list before attempting to reserve space START mBlockWorker.syncPinList(); END reserveSpace(); } This might be too expensive to call on every eviction attempt. We want to keep the eviction loop fast and without dependencies on external services.

Target:
public void heartbeat() { reserveSpace(); }
Source:
private final void decrementResponseOrExpired() { int decrementedValue = responsesAndExpirations.decrementAndGet(); if (decrementedValue == 0) { // The condition being signaled is a valid proxy for the CL being achieved // Only mark it as failed if the requested CL was achieved. START if (!condition.isSignaled() & requestedCLAchieved) END { replicaPlan.keyspace().metric.writeFailedIdealCL.inc(); } else { replicaPlan.keyspace().metric.idealCLWriteLatency.addNano(System.nanoTime() - queryStartNanoTime); } } } Is this intentionally a bitwise AND?

Target:
private final void decrementResponseOrExpired() { int decrementedValue = responsesAndExpirations.decrementAndGet(); if (decrementedValue == 0) { // The condition being signaled is a valid proxy for the CL being achieved // Only mark it as failed if the requested CL was achieved. if (!condition.isSignaled() && requestedCLAchieved) { replicaPlan.keyspace().metric.writeFailedIdealCL.inc(); } else { replicaPlan.keyspace().metric.idealCLWriteLatency.addNano(System.nanoTime() - queryStartNanoTime); } } }
Source:
public List<Attribute> getRequiredAttributes(PerunSession sess, List<Service> services, Resource resource, Group group, boolean withGroupAttributes) throws GroupResourceMismatchException { this.checkGroupIsFromTheSameVoLikeResource(sess, group, resource); List<Attribute> attributes = new ArrayList<>(); START attributes.addAll(getAttributesManagerImpl().getRequiredAttributes(sess, services, resource, group)); END if (withGroupAttributes) { attributes.addAll(getAttributesManagerImpl().getRequiredAttributes(sess, services, group)); } return attributes; } You can use parameterized constructor call instead of addAll()

Target:
public List<Attribute> getRequiredAttributes(PerunSession sess, List<Service> services, Resource resource, Group group, boolean withGroupAttributes) throws GroupResourceMismatchException { this.checkGroupIsFromTheSameVoLikeResource(sess, group, resource); List<Attribute> attributes = getAttributesManagerImpl().getRequiredAttributes(sess, services, resource, group); if (withGroupAttributes) { attributes.addAll(getAttributesManagerImpl().getRequiredAttributes(sess, services, group)); } return attributes; }
Source:
private boolean extractZsetIncrementHeader(Message<?> message) { START if (message.getHeaders().containsKey(RedisHeaders.ZSET_INCREMENT_SCORE)) { END return this.zsetIncrementScoreExpression.getValue(this.evaluationContext, message, Boolean.class); } return false; } If we open up the expression for user specification, this if test would have to go inside the default `FunctionExpression`.

Target:
private boolean extractZsetIncrementHeader(Message<?> message) { Boolean value = this.zsetIncrementScoreExpression.getValue(this.evaluationContext, message, Boolean.class); return value != null ? value : false; }
Source:
public void shouldGetDiagnosisById() { START int diagnosisId = 1; END Diagnosis diagnosis = diagnosisDAO.getDiagnosisById(diagnosisId); assertEquals("4e663d66-6b78-11e0-93c3-18a905e044dc", diagnosis.getUuid()); } We can get rid of the above variable

Target:
public void shouldGetDiagnosisById() { Diagnosis diagnosis = diagnosisDAO.getDiagnosisById(1); assertEquals("4e663d66-6b78-11e0-93c3-18a905e044dc", diagnosis.getUuid()); }
Source:
public Operator createOperator(DriverContext driverContext) { checkState(!closed, "Factory is already closed"); OperatorContext operatorContext = driverContext.addOperatorContext(operatorId, planNodeId, HashBuilderOperator.class.getSimpleName()); START return new SpatialJoinOperator(operatorContext, getTypes(), probeTypes, probeOutputChannels, probeGeometryChannel, pagesSpatialIndexFactory.createPagesSpatialIndex(), spatialRelationshipTest); END } split lines

Target:
public Operator createOperator(DriverContext driverContext) { checkState(!closed, "Factory is already closed"); OperatorContext operatorContext = driverContext.addOperatorContext( operatorId, planNodeId, SpatialJoinOperator.class.getSimpleName()); return new SpatialJoinOperator( operatorContext, getTypes(), probeTypes, probeOutputChannels, probeGeometryChannel, pagesSpatialIndexFactory); }
Source:
private IssuesRecorder enableWarningsForNewFixedOutstandingTest(final FreeStyleProject job, IssuesRecorder oldPublisher, String pattern) { START if(oldPublisher != null) { END job.getPublishersList().remove(oldPublisher); } IssuesRecorder publisher = new IssuesRecorder(); publisher.setTools(Collections.singletonList(new ToolConfiguration(pattern, new Eclipse()))); job.getPublishersList().add(publisher); return publisher; } Evtl. geht auch `clear()` dann braucht man gar keinen Parameter...

Target:
private IssuesRecorder enableWarningsForNewFixedOutstandingTest(final FreeStyleProject job, IssuesRecorder oldPublisher, String pattern) { if(oldPublisher != null) { job.getPublishersList().remove(oldPublisher); } return enableWarningsForNewFixedOutstandingTest(job, pattern); }
Source:
public boolean isMember(User user) { if (user == null || user.getPerson() == null) { return false; } START return new ActivePhdProcessesGroup().isMember(user) || (user.getPerson().getStudent() != null && user.getPerson() END .getStudent().hasActiveRegistrations()); } There are more non PHD students than there are PHD students, thus switching the order of the || will probably improve performance.

Target:
public boolean isMember(User user) { if (user == null || user.getPerson() == null) { return false; } return (user.getPerson().getStudent() != null && user.getPerson().getStudent().hasActiveRegistrations()) || new ActivePhdProcessesGroup().isMember(user); }
Source:
public ListenableFuture<?> waitForWriting() { if (isFinished()) { return NOT_BLOCKED; } START return exchanger.getNotFullFuture(); END } maybe you could rename this `getNotFullFuture` to `waitForWriting`?

Target:
public ListenableFuture<?> waitForWriting() { if (isFinished()) { return NOT_BLOCKED; } return exchanger.waitForWriting(); }
Source:
public Map<String, TransportConfiguration> getConnectors() { START return Collections.unmodifiableMap(connectors); END } What's the relation between this change and WFLY-19339?

Target:
public Map<String, TransportConfiguration> getConnectors() { return connectors; }
Source:
public void setEntries(IRuntimeClasspathEntry[] entries) { model.removeAll(); IRuntimeClasspathEntry entry; for (IRuntimeClasspathEntry START entrie : END entries) { entry = entrie; switch (entry.getClasspathProperty()) { case IRuntimeClasspathEntry.USER_CLASSES: model.addEntry(ClasspathModel.USER, entry); break; default: model.addEntry(ClasspathModel.BOOTSTRAP, entry); break; } } refresh(); } rename to entry

Target:
public void setEntries(IRuntimeClasspathEntry[] entries) { model.removeAll(); for (IRuntimeClasspathEntry entry : entries) { switch (entry.getClasspathProperty()) { case IRuntimeClasspathEntry.USER_CLASSES: model.addEntry(ClasspathModel.USER, entry); break; default: model.addEntry(ClasspathModel.BOOTSTRAP, entry); break; } } refresh(); }
Source:
public static String getGerritJarPluginName(File srcFile) throws IOException { START JarFile jarFile = new JarFile(srcFile); try { return jarFile.getManifest().getMainAttributes() .getValue("Gerrit-PluginName"); } finally { jarFile.close(); } END } This is not a new code, you just mved it, but consider to use Java7 try-with-resources statement: try (JarFile jarFile = new JarFile(srcFile)) { return jarFile.getManifest().getMainAttributes() .getValue("Gerrit-PluginName"); }

Target:
public static String getGerritJarPluginName(File srcFile) throws IOException { try (JarFile jarFile = new JarFile(srcFile)) { return jarFile.getManifest().getMainAttributes() .getValue("Gerrit-PluginName"); } }
Source:
protected String getContextId(String name) { boolean includeHostName = camelContext != null && camelContext.getManagementStrategy().getManagementAgent().getIncludeHostName(); START if (includeHostName != null && includeHostName) { END return hostName + "/" + (name != null ? name : VALUE_UNKNOWN); } else { return name != null ? name : VALUE_UNKNOWN; } } primitive boolean cannot be compared with null.

Target:
protected String getContextId(String name) { boolean includeHostName = camelContext != null && camelContext.getManagementStrategy().getManagementAgent().getIncludeHostName(); if (includeHostName) { return hostName + "/" + (name != null ? name : VALUE_UNKNOWN); } else { return name != null ? name : VALUE_UNKNOWN; } }
Source:
public boolean getChecked(Object element) { if (fObjects.containsKey(element)) { return fObjects.get(element); } START return fCheckboxTreeViewer.getChecked(element); END } If it's possible for an element to be checked in the viewer but not in the map, then other code is wrong, e.g. getCheckedElements(). If it's not possible, then you can just return false here.

Target:
public boolean getChecked(Object element) { return fObjects.contains(element); }
Source:
START private void putPreferred(String email) throws RestApiException, OrmException { List<EmailInfo> emails = getEmails.apply(rsrc); for (EmailInfo e : emails) { if (e.email.equals(email)) { putPreferred.apply(new AccountResource.Email(user, email), null); } } } END Should we swallow typo-case without even issue a warning? Delete email method above doesn't really matter, because if a mail doesn't exist, all is fine. Here someone rellies on this command to change something, yet when she spelled email wrong, it should fail, i think.

Target:
private void putPreferred(String email) throws RestApiException, OrmException { putPreferred.apply(new AccountResource.Email(user, email), null); }
Source:
private void cancel(Job[] jobs) { START for (Job job : jobs) { END job.cancel(); } } The "brackets for single statements" cleanup in this file should be done in a separate commit, as we should not mix unrelated changes.

Target:
private void cancel(Job[] jobs) { for (Job job : jobs) job.cancel(); }
Source:
START static private long toMillis(String seconds) { END if (seconds.contains(".")) { float value = Float.parseFloat(seconds); float millis = value % 1; return SECONDS.toMillis((long) value) + (long) (millis * 1000); } else { return SECONDS.toMillis(Long.parseLong(seconds)); } } Please swap the order to `private static` like in the [google code style guide](https://google.github.io/styleguide/javaguide.html#s4.8.7-modifiers)

Target:
private static long toMillis(String seconds) { if (seconds.contains(".")) { float value = Float.parseFloat(seconds); float millis = value % 1; return SECONDS.toMillis((long) value) + (long) (millis * 1000); } else { return SECONDS.toMillis(Long.parseLong(seconds)); } }
Source:
public synchronized void addSegmentChangeRequests(List<DataSegmentChangeRequest> requests) { for (DataSegmentChangeRequest request : requests) { if (changes.size() >= maxSize) { START changes.remove(0); END } changes.add(new Holder(request, getLastCounter().inc())); } singleThreadedExecutor.execute(resolveWaitingFuturesRunnable); } This might be pre-mature optimization, but I worry about how this data structure is being used. One option would be to view the list as a revolving buffer and essentially maintain an index of the oldest "valid" item. You can replace and increment that on `add` and start your search from there wrapping back around.

Target:
public synchronized void addSegmentChangeRequests(List<DataSegmentChangeRequest> requests) { for (DataSegmentChangeRequest request : requests) { changes.add(new Holder(request, getLastCounter().inc())); } singleThreadedExecutor.execute(resolveWaitingFuturesRunnable); }
Source:
static boolean checkStartObject(JsonParser parser, boolean shouldThrow) throws IOException { try { JsonToken currentToken = parser.currentToken(); // The parser may not be at a token, yet. If that's the case advance. if (currentToken == null) currentToken = parser.nextToken(); // If we are still not at the expected token, we could be an another or an empty body. if (currentToken == JsonToken.START_OBJECT) return true; if (shouldThrow) { throw new IllegalArgumentException("Expected start object, was " + currentToken); } return false; START } catch (JsonParseException e) { // likely not json END if (shouldThrow) throw e; return false; } } catch `Throwable`? When methods shouldn't throw, like where `shouldThrow` is `false` here, it's easy to end up with a hang because an exception type changed.

Target:
static boolean checkStartObject(JsonParser parser, boolean shouldThrow) throws IOException { try { JsonToken currentToken = parser.currentToken(); // The parser may not be at a token, yet. If that's the case advance. if (currentToken == null) currentToken = parser.nextToken(); // If we are still not at the expected token, we could be an another or an empty body. if (currentToken == JsonToken.START_OBJECT) return true; if (shouldThrow) { throw new IllegalArgumentException("Expected start object, was " + currentToken); } return false; } catch (Throwable e) { // likely not json if (shouldThrow) throw e; return false; } }
Source:
public VdsIdVDSCommandBase(P parameters, boolean newHost) { super(parameters); if (!newHost) { START _vdsManager = Injector.get(ResourceManager.class).getVdsManager(parameters.getVdsId()); END } } It seems that we can get rid from this injection by moving the initialization of the _vdsManager from the c'tor to the executeVDSCommand() method. we actually can just keep the newHost as a member and use it from the executeVDSCommand() by referring to the already initialized ResourceManager to obtain the vdsManager associated with the host.

Target:
public VdsIdVDSCommandBase(P parameters, boolean newHost) { super(parameters); this.newHost = newHost; }
Source:
public DRCatalogDiffEngine(Catalog localCatalog, Catalog remoteCatalog) { super(localCatalog, remoteCatalog); START localCatalog.getClusters().get("cluster").getDrclusterid(); END } This seems not needed.

Target:
public DRCatalogDiffEngine(Catalog localCatalog, Catalog remoteCatalog) { super(localCatalog, remoteCatalog); }
Source:
START public List<@NonNull Integer> getSubAttributes(int quark, boolean recursive) END throws AttributeNotFoundException { return getAttributeTree().getSubAttributes(quark, recursive); } If you annotate the interface methods you don't need to repeat them here (we have to setting to inherit annotations).

Target:
public List<Integer> getSubAttributes(int quark, boolean recursive) throws AttributeNotFoundException { return getAttributeTree().getSubAttributes(quark, recursive); }
Source:
private String getLsRegisterOutput() throws Exception { if START (lsRegisterOutput != END null) { return lsRegisterOutput; } long beforeCallLsRegister = System.currentTimeMillis(); lsRegisterOutput = processExecutor.execute(LSREGISTER, DUMP); long afterCallLsRegister = System.currentTimeMillis(); System.out.println("Call to lsregister took :" + (afterCallLsRegister - beforeCallLsRegister)); //$NON-NLS-1$ return lsRegisterOutput; } this.lsRegisterOutput

Target:
private String getLsRegisterOutput() throws Exception { if (this.lsRegisterOutput != null) { return this.lsRegisterOutput; } this.lsRegisterOutput = processExecutor.execute(LSREGISTER, DUMP); return this.lsRegisterOutput; }
Source:
public static String masterInbox(Map conf) throws IOException { String ret = masterLocalDir(conf) + FILE_SEPARATOR + "inbox"; try { FileUtils.forceMkdir(new File(ret)); } catch (IOException e) { LOG.error("Failed to create dir " + ret, e); START throw e; END } return ret; } Again lets remove the try/catch/log/rethrow

Target:
public static String masterInbox(Map conf) throws IOException { String ret = masterLocalDir(conf) + FILE_SEPARATOR + "inbox"; FileUtils.forceMkdir(new File(ret)); return ret; }
Source:
START public MockReplicaId(String storeId, long capacity, String filePath) { END this.storeId = storeId; this.capacity = capacity; this.filePath = filePath; partitionId = mock(PartitionId.class); when(partitionId.toString()).thenReturn(storeId); } not public

Target:
MockReplicaId(String storeId, long capacity, String filePath) { this.storeId = storeId; this.capacity = capacity; this.filePath = filePath; partitionId = mock(PartitionId.class); when(partitionId.toString()).thenReturn(storeId); }
Source:
public static void main(String[] args) { LOG.info("Validating configuration."); try { Configuration.validate(); LOG.info("Configuration is valid."); } catch (IllegalStateException e) { START LOG.warn("Configuration is invalid: {}", e.getMessage()); END System.exit(-1); } System.exit(0); } Log this at error level? I don't think we should put the stack trace, but the end result is crashing the system which seems to be more of an issue than warn.

Target:
public static void main(String[] args) { LOG.info("Validating configuration."); try { Configuration.validate(); LOG.info("Configuration is valid."); } catch (IllegalStateException e) { LOG.error("Configuration is invalid: {}", e.getMessage()); System.exit(-1); } System.exit(0); }
Source:
START private boolean isConstantFilterFunction(FilterFunction filter, Block[] constantBlocks) END { return Arrays.stream(filter.getInputChannels()).allMatch(channel -> constantBlocks[channel] != null); } static

Target:
private static boolean isConstantFilterFunction(FilterFunction filter, Block[] constantBlocks) { return Arrays.stream(filter.getInputChannels()).allMatch(channel -> constantBlocks[channel] != null); }
Source:
public void testDefaults() { START assertRecordedDefaults(ConfigAssertions.recordDefaults(FileSessionPropertyManagerConfig.class) END .setConfigFile(null)); } Nit: static import `recordDefaults`

Target:
public void testDefaults() { assertRecordedDefaults(recordDefaults(FileSessionPropertyManagerConfig.class) .setConfigFile(null)); }
Source:
public int hashCode() { START return Objects.hash(storageDomainId, imageGroupId, baseImageId, topImageId, baseImageGeneration, baseImage, topImage); END } Let's break up this line please

Target:
public int hashCode() { return Objects.hash(storageDomainId, imageGroupId, baseImageGeneration, baseImage, topImage); }
Source:
public boolean isApplicable(Class<? extends Item> itemClass) { START if (itemClass.isAssignableFrom(MavenModule.class) || itemClass.isAssignableFrom(MavenModuleSet.class)) { END return true; } else { return false; } } `return itemClass.isAssignableFrom(MavenModule.class) || itemClass.isAssignableFrom(MavenModuleSet.class)`.

Target:
public boolean isApplicable(Class<? extends Item> itemClass) { return itemClass.isAssignableFrom(MavenModule.class) || itemClass.isAssignableFrom(MavenModuleSet.class); }
Source:
public void TestWikiaLogoInGlobalNav_001_centralWikiExists(String wikiName, String expectedCentralUrl) { HomePageObject homePage = new HomePageObject(driver); homePage.getUrl(urlBuilder.getUrlForWiki(wikiName)); VenusGlobalNavPageObject globalNav = homePage.getVenusGlobalNav(); globalNav.waitForCorrectUrl(config.getEnv()); START globalNav.clickWikiaLogo(); END Assertion.assertStringContains(urlBuilder.getUrlForWiki(expectedCentralUrl), driver.getCurrentUrl()); } Use fluent interface in here

Target:
public void TestWikiaLogoInGlobalNav_001_centralWikiExists(String wikiName, String expectedCentralUrl) { HomePageObject homePage = new HomePageObject(driver); homePage.getUrl(urlBuilder.getUrlForWiki(wikiName)); homePage.getVenusGlobalNav() .clickWikiaLogo(); Assertion.assertStringContains(urlBuilder.getUrlForWiki(expectedCentralUrl), driver.getCurrentUrl()); }
Source:
public void execute(WorkflowExecutor workflowExecutor) throws IOException { START if (!isComplete()) throw new IllegalArgumentException("Workflow is not complete"); END Pool pool = step1.getInput(); pool.setConcentration((double) step0.getInput()); workflowExecutor.save(pool); } There's no issue with the argument (`workflowExecutor`), so an `IllegalStateException` makes more sense here

Target:
public void execute(WorkflowExecutor workflowExecutor) throws IOException { if (!isComplete()) throw new IllegalStateException("Workflow is not complete"); Pool pool = step1.getInput(); pool.setConcentration((double) step0.getInput()); workflowExecutor.save(pool); }
Source:
public void should_return_null_when_encountering_parsing_issue() { logTester.setLevel(LoggerLevel.DEBUG); assertThat(XmlParser.parseXML(new File("src/test/files/xml/parsing-issue.xml"))).isNull(); assertThat(logTester.logs(LoggerLevel.ERROR)).contains("Unable to parse xml file: src/test/files/xml/parsing-issue.xml"); START System.out.println(logTester.logs(LoggerLevel.DEBUG)); END assertThat(logTester.logs(LoggerLevel.DEBUG)).hasSize(1).allSatisfy(s -> s.startsWith("XML file parsing failed because of : org.xml.sax.SAXParseException; systemId: file: ")); } Please remove this `System.out.println`

Target:
public void should_return_null_when_encountering_parsing_issue() { logTester.setLevel(LoggerLevel.DEBUG); assertThat(XmlParser.parseXML(new File("src/test/files/xml/parsing-issue.xml"))).isNull(); assertThat(logTester.logs(LoggerLevel.ERROR)).contains("Unable to parse xml file: src/test/files/xml/parsing-issue.xml"); assertThat(logTester.logs(LoggerLevel.DEBUG)).hasSize(1).allSatisfy(s -> s.startsWith("XML file parsing failed because of : org.xml.sax.SAXParseException; systemId: file: ")); }
Source:
boolean getHl7PrefixProperty() { try { return PropertyAccessor.getInstance().getPropertyBoolean(NhincConstants.GATEWAY_PROPERTY_FILE, NhincConstants.HL7_PREFIX_FOR_ATTR_PROPERTY); } catch (final PropertyAccessException ex) { START LOG.warn(ex.getLocalizedMessage()); END LOG.trace("Get HL7 Prefix Property exception: {}", ex.getLocalizedMessage(), ex); } return false; } Remove log.warn since we already cover in log.trace

Target:
boolean getHl7PrefixProperty() { try { return PropertyAccessor.getInstance().getPropertyBoolean(NhincConstants.GATEWAY_PROPERTY_FILE, NhincConstants.HL7_PREFIX_FOR_ATTR_PROPERTY); } catch (final PropertyAccessException ex) { LOG.trace("Get HL7 Prefix Property exception: {}", ex.getLocalizedMessage(), ex); } return false; }
Source:
public void followPeergos() throws Exception { UserContext u1 = PeergosNetworkUtils.ensureSignedUp("peergos", "testpassword", network, crypto); UserContext u2 = PeergosNetworkUtils.ensureSignedUp("w", "w", network, crypto); START u2.sendFollowRequest(u1.username, SymmetricKey.random()).get(); END List<FollowRequestWithCipherText> u1Requests = u1.processFollowRequests().get(); assertTrue("Receive a follow request", u1Requests.size() > 0); } this shouldn't be here. Users automatically friend "peergos" during signup

Target:
public void followPeergos() throws Exception { UserContext u1 = PeergosNetworkUtils.ensureSignedUp("peergos", "testpassword", network, crypto); UserContext u2 = PeergosNetworkUtils.ensureSignedUp("w", "w", network, crypto); List<FollowRequestWithCipherText> u1Requests = u1.processFollowRequests().get(); assertTrue("Receive a follow request", u1Requests.size() > 0); }
Source:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { requireNonNull(contextThreadLocalSupplier, "httpClientContextSupplier should not be null"); try { contextThreadLocalSupplier.addContext(getRequestHeadersMap(request), getQueryParamsMap(request)); chain.doFilter(request, response); START } catch (IllegalArgumentException e) { END ((HttpServletResponse) response).sendError(HttpServletResponse.SC_BAD_REQUEST); } finally { contextThreadLocalSupplier.clear(); } } тут ты ловишь и то, что вылетит из `chain.doFilter()`. надо более узкий `try` - только на `getRequestHeadersMap()` и `getQueryParamsMap()`

Target:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { requireNonNull(contextThreadLocalSupplier, "httpClientContextSupplier should not be null"); try { try { contextThreadLocalSupplier.addContext(getRequestHeadersMap(request), getQueryParamsMap(request)); } catch (IllegalArgumentException e) { ((HttpServletResponse) response).sendError(HttpServletResponse.SC_BAD_REQUEST); return; } chain.doFilter(request, response); } finally { contextThreadLocalSupplier.clear(); } }
Source:
public CtPath getPath() { try { return new CtElementPathBuilder().fromElement(this, getParent(CtModelImpl.CtRootPackage.class)); } catch (CtPathException e) { START throw new SpoonException(); END } } `throw new SpoonException(e);` ... the orgin exception should be used as cause of the SpoonException

Target:
public CtPath getPath() { try { return new CtElementPathBuilder().fromElement(this, getParent(CtModelImpl.CtRootPackage.class)); } catch (CtPathException e) { throw new SpoonException(e); } }
Source:
public void instrument(final InputStream input, final OutputStream output, final String name) throws IOException { START final byte[] bytes; END try { bytes = Java9Support.readFully(input); } catch (final IOException e) { throw instrumentError(name, e); } output.write(instrument(bytes, name)); } I think we can delegate to the overloaded method here: public void instrument(final InputStream input, final OutputStream output, final String name) throws IOException { output.write(instrument(input, name)); }

Target:
public void instrument(final InputStream input, final OutputStream output, final String name) throws IOException { output.write(instrument(input, name)); }
Source:
public WorkQueue.Executor getBatchQueue() { START System.out.println("Job scheduled in batch Queue"); END return batchExecutor; } Drop the println. :-)

Target:
public WorkQueue.Executor getBatchQueue() { return batchExecutor; }
Source:
protected void tearDown() { boolean removed = api().deleteRole(roleName); START assertTrue(removed); END } This will fail if the `testCreateRole` test fails. Better leave the assertions for the tests, not the tearDown methods.

Target:
protected void tearDown() { api().deleteRole(roleName); }
Source:
public void itDoesntWritePassword() throws Exception { // When I call JSON for user1 JsonNode node = getResponseAsJson(RequestType.GET, "/user/user1"); // Then it doesn't contain the password at all START assertNull("", node.get("properties").get("password")); END } No need for an empty message here `assertNull(node.get("properties").get("password"));`

Target:
public void itDoesntWritePassword() throws Exception { // When I call JSON for user1 JsonNode node = getResponseAsJson(RequestType.GET, "/user/user1"); // Then it doesn't contain the password at all assertNull(node.get("properties").get("password")); }
Source:
protected void demandUnload(SynchronizedResourceSet resourceSet, Resource resource, IProgressMonitor monitor) { START lock.lock(); END try { unloadingPool.execute(new ResourceUnloader(resourceSet, resource, monitor)); } finally { lock.unlock(); } } why do you need to lock this code? ExecutorService.execute is thread safe, isn't it ?

Target:
protected void demandUnload(SynchronizedResourceSet resourceSet, Resource resource, IProgressMonitor monitor) { unloadingPool.execute(new ResourceUnloader(resourceSet, resource, monitor)); }
Source:
private void checkSigOps() throws VerificationException { // Check there aren't too many signature verifications in the block. This is an anti-DoS measure, see the // comments for MAX_BLOCK_SIGOPS. int sigOps = 0; for (Transaction tx : transactions) { sigOps += tx.getSigOpCount(); } START if (sigOps > MAX_BLOCK_SIGOPS) { END throw new VerificationException("Block had too many Signature Operations"); } } This is an unrelated change snuck in. Sorry for bitching, but it makes reviewing harder for big refactorings like this one.

Target:
private void checkSigOps() throws VerificationException { // Check there aren't too many signature verifications in the block. This is an anti-DoS measure, see the // comments for MAX_BLOCK_SIGOPS. int sigOps = 0; for (Transaction tx : transactions) { sigOps += tx.getSigOpCount(); } if (sigOps > MAX_BLOCK_SIGOPS) throw new VerificationException("Block had too many Signature Operations"); }
Source:
START public static Expression filterConjuncts(Expression expression, Predicate<Expression> predicate) END { List<Expression> conjuncts = extractConjuncts(expression).stream() .filter(predicate) .collect(toList()); return combineConjuncts(conjuncts); } There are no conjuncts in the API (no `List`, just an `expression`). Make it `private`.

Target:
private static Expression filterConjuncts(Expression expression, Predicate<Expression> predicate) { List<Expression> conjuncts = extractConjuncts(expression).stream() .filter(predicate) .collect(toList()); return combineConjuncts(conjuncts); }
Source:
public void createPartControl(Composite parent) { String name = getViewSite().getSecondaryId(); if (name != null) { name = TmfViewFactory.getBaseSecId(name); } if (name != null) { /* must initialize view info before calling super */ fViewInfo.setName(name); } fPresentationProvider = new XmlPresentationProvider(name); START TimeGraphViewer timeGraphViewer = getTimeGraphViewer(); END timeGraphViewer.getTimeGraphControl().colorSettingsChanged(timeGraphViewer.getTimeGraphProvider().getStateTable()); super.createPartControl(parent); } NPE: timeGraphViewer is null before super is called. But I don't think the next line is necessary.

Target:
public void createPartControl(Composite parent) { String name = getViewSite().getSecondaryId(); if (name != null) { name = TmfViewFactory.getBaseSecId(name); } if (name != null) { /* must initialize view info before calling super */ fViewInfo.setName(name); } fPresentationProvider = new XmlPresentationProvider(name); super.createPartControl(parent); TimeGraphViewer timeGraphViewer = getTimeGraphViewer(); timeGraphViewer.getTimeGraphControl().colorSettingsChanged(timeGraphViewer.getTimeGraphProvider().getStateTable()); }
Source:
START public ProtocolVersion protocolVersion() { END return protocolVersion; } Let's not change this signature. Maybe add a separate method

Target:
public String protocolVersion() { return protocolVersion.toString(); }
Source:
public Matrix removeRow(int i) { START return removeRow(i, this.factory); END } Please, do not use `this` when it's unnecessary. You can write just `factory`.

Target:
public Matrix removeRow(int i) { return removeRow(i, factory); }
Source:
public void testBracketsInGroup() throws Exception { createFiles("[", "]", "[]", "][", "[[]", "[]]", "[[]]"); writeTrashFile(".gitattributes", "[[]] bar1\n"); writeTrashFile(".gitattributes", "[\\[]] bar2\n"); writeTrashFile(".gitattributes", "[[\\]] bar3\n"); START writeTrashFile(".gitattributes", "[\\[\\]] bar4\n"); END assertSameAsCGit(); } I presume you want to have all those line in .gitattributes? I think you need to do a single writeTrashFile with the four lines: writeTrashFile(".gitattributes", "[[]] bar\n" + "[\\[]] bar2\n" + ... );

Target:
public void testBracketsInGroup() throws Exception { createFiles("[", "]", "[]", "][", "[[]", "[]]", "[[]]"); writeTrashFile(".gitattributes", "[[]] bar1\n" + "[\\[]] bar2\n" + "[[\\]] bar3\n" + "[\\[\\]] bar4\n"); assertSameAsCGit(); }
Source:
public void notIgnoredAfterOnCreateView() { assertFalse(myListFragment.didExecute); LayoutInflater inflater = mock(LayoutInflater.class); ViewGroup viewGroup = mock(ViewGroup.class); Bundle bundle = mock(Bundle.class); START myListFragment.onCreateView(inflater, viewGroup, bundle); END assertFalse(myListFragment.didExecute); myListFragment.ignoreWhenViewDestroyed(); assertTrue(myListFragment.didExecute); } We could just pass `null` to every parameter here, there is no need for mocking in this case.

Target:
public void notIgnoredAfterOnCreateView() { assertFalse(myListFragment.didExecute); myListFragment.onCreateView(null, null, null); assertFalse(myListFragment.didExecute); myListFragment.ignoreWhenViewDestroyed(); assertTrue(myListFragment.didExecute); }
Source:
private static String checkSitePathToken(Site site, String pattern) { if (site.getRequestScheme().hasPathToken()) { START StringBuilder modified = new StringBuilder(pattern.length() + 8); END modified.append("/*"); if (!pattern.isEmpty() && !pattern.startsWith("/")) { modified.append('/'); } modified.append(pattern); return modified.toString(); } else { return pattern; } } why `8`?

Target:
private static String checkSitePathToken(Site site, String pattern) { if (site.getRequestScheme().hasPathToken()) { StringBuilder modified = new StringBuilder(pattern.length() + 3); modified.append("/*"); if (!pattern.isEmpty() && !pattern.startsWith("/")) { modified.append('/'); } modified.append(pattern); return modified.toString(); } else { return pattern; } }