auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
START public int processLocator(int rollCount, RollupExecutionContext executionContext, END RollupBatchWriter rollupBatchWriter, Locator locator) { if (log.isTraceEnabled()) log.trace("Rolling up (check,metric,dimension) for (gran,slot,shard) {}", locator, parentSlotKey); try { executeRollupForLocator(executionContext, rollupBatchWriter, locator); rollCount += 1; } catch (Throwable any) { // continue on, but log the problem so that we can fix things later. executionContext.markUnsuccessful(any); executionContext.decrementReadCounter(); log.error(any.getMessage(), any); log.error("BasicRollup failed for at {}", parentSlotKey, serverTime); } return rollCount; } Do we want to expose this out to caller? I.e: allowing them to skip Instrumentation? I'm thinking we may not want to. So make it protected (test classes can still call)?

Target:
protected int processLocator(int rollCount, RollupExecutionContext executionContext, RollupBatchWriter rollupBatchWriter, Locator locator) { if (log.isTraceEnabled()) log.trace("Rolling up (check,metric,dimension) for (gran,slot,shard) {}", locator, parentSlotKey); try { executeRollupForLocator(executionContext, rollupBatchWriter, locator); rollCount += 1; } catch (Throwable any) { // continue on, but log the problem so that we can fix things later. executionContext.markUnsuccessful(any); executionContext.decrementReadCounter(); log.error(any.getMessage(), any); log.error("BasicRollup failed for at {}", parentSlotKey, serverTime); } return rollCount; }
Source:
START public static AggregatedPayload createPayload(String json) throws JsonSyntaxException { END AggregatedPayload payload = new Gson().fromJson(json, AggregatedPayload.class); return payload; } We should use `JsonParseException` here if you want to declare the exception.

Target:
public static AggregatedPayload createPayload(String json) { AggregatedPayload payload = new Gson().fromJson(json, AggregatedPayload.class); return payload; }
Source:
START public static List<AggregatedPayload> createBundleList(String json) throws JsonSyntaxException { END Gson gson = new Gson(); JsonParser parser = new JsonParser(); JsonArray jArray = parser.parse(json).getAsJsonArray(); ArrayList<AggregatedPayload> bundleList = new ArrayList<AggregatedPayload>(); for(JsonElement obj : jArray ) { AggregatedPayload bundle = gson.fromJson( obj , AggregatedPayload.class); bundleList.add(bundle); } return bundleList; } JsonParseException

Target:
public static List<AggregatedPayload> createBundleList(String json) { Gson gson = new Gson(); JsonParser parser = new JsonParser(); JsonArray jArray = parser.parse(json).getAsJsonArray(); ArrayList<AggregatedPayload> bundleList = new ArrayList<AggregatedPayload>(); for(JsonElement obj : jArray ) { AggregatedPayload bundle = gson.fromJson( obj , AggregatedPayload.class); bundleList.add(bundle); } return bundleList; }
Source:
protected Points.Point createPoint( Long timestamp, Object value ) { START if( value instanceof Rollup || value instanceof String) END return new Points.Point( timestamp, value); else return new Points.Point( timestamp, new SimpleNumber( value ) ); } I missed bounded type parameters already :-) I don't know if it would be better to create separate versions of `createPoint` methods? Like this? ``` protected Points.Point createPoint(Long timestamp, Rollup value); protected Points.Point createPoint(Long timestamp, String value); protected Points.Point createPoint(Long timestamp, Object value); ```

Target:
protected Points.Point createPoint( Long timestamp, Object value ) { if( value instanceof Rollup ) return new Points.Point( timestamp, value); else return new Points.Point( timestamp, new SimpleNumber( value ) ); }
Source:
public ScheduleContext(long currentTimeMillis, Collection<Integer> managedShards) { this.scheduleTime = currentTimeMillis; this.shardStateManager = new ShardStateManager(managedShards, asMillisecondsSinceEpochTicker()); this.lockManager = new NoOpShardLockManager(); START this.clock = new DefaultClockImpl(); END registerMBean(); } why repeat this? calling this() should be the correct thing to do, just don't call registerMBean() in the subsequent constructor.

Target:
public ScheduleContext(long currentTimeMillis, Collection<Integer> managedShards) { this(currentTimeMillis, managedShards, new DefaultClockImpl()); }
Source:
public Map<Locator, MetricData> getEnumMetricDataForRangeForLocatorList(final List<Locator> locators, final Range range, final Granularity gran) { String columnFamily = CassandraModel.getColumnFamily(BluefloodEnumRollup.class, gran).getName(); START if ( columnFamily == null ) { END throw new IllegalArgumentException("invalid granularity: " + gran); } return getEnumMetricDataForRangeForLocatorList(locators, range, columnFamily); } Does this ever happen?

Target:
public Map<Locator, MetricData> getEnumMetricDataForRangeForLocatorList(final List<Locator> locators, final Range range, final Granularity gran) { String columnFamily = CassandraModel.getColumnFamily(BluefloodEnumRollup.class, gran).getName(); return getEnumMetricDataForRangeForLocatorList(locators, range, columnFamily); }
Source:
START public static Tracker getInstance() { END register(); return instance; } Do we need this method? It seems like people should just call Tracker.register() ?

Target:
public static Tracker getInstance() { return instance; }
Source:
public void waitForRollups() throws InterruptedException { Thread.currentThread().sleep(LOCATOR_WAIT_FOR_ALL_SECS * 1000); START } END Someone could totally mess with us by calling this repeatedly. We shouldnt expose these kinda methods. If you want control, have LOCATOR_WAIT_FOR_ALL_SECS to be set in a separate constructor. For tests you can set it to zero if you dont want it to wait. You can make it non-static that would let you set it in constructor. Its just an integer field.

Target:
protected void waitForRollups() throws InterruptedException { Thread.currentThread().sleep(LOCATOR_WAIT_FOR_ALL_SECS * 1000); }
Source:
protected int sizeOfSize() { START return 1; END } do we want to make these abstract?

Target:
protected final int sizeOfSize() { return 1; }
Source:
protected String[] getBodyArray( HttpResponse response ) throws IOException { StringWriter sw = new StringWriter(); IOUtils.copy( response.getEntity().getContent(), sw ); START IOUtils.closeQuietly( response.getEntity().getContent() ); END return sw.toString().split( System.lineSeparator() ); } Can you do closeQuietly in a finally block?

Target:
protected String[] getBodyArray( HttpResponse response ) throws IOException { try { StringWriter sw = new StringWriter(); IOUtils.copy( response.getEntity().getContent(), sw ); return sw.toString().split( System.lineSeparator() ); } finally { IOUtils.closeQuietly( response.getEntity().getContent() ); } }
Source:
private double meanOfPointCollectionRoll( Collection<Points.Point<BasicRollup>> fullPoints ) { long sum = 0; int count = 0; for( Points.Point<BasicRollup> p : fullPoints ) { sum += p.getData().getAverage().toLong(); START count++; END } return sum / count; } Why do you need count? Cant you use fullPoints.size?

Target:
private double meanOfPointCollectionRoll( Collection<Points.Point<BasicRollup>> fullPoints ) { long sum = 0; for( Points.Point<BasicRollup> p : fullPoints ) { sum += p.getData().getAverage().toLong(); } return sum / fullPoints.size(); }
Source:
private static void checkConfiguration() { if (!config.getBooleanProperty(CoreConfig.INGEST_MODE)) { log.error("Ingestion mode not enabled. Please check your configuration"); System.exit(StopReasons.INCORRECT_CONFIGURATION); } log.info("Configuration is good"); boolean useZookeeper = false; START log.info("Using zookeeper? " + useZookeeper); END } can we delete the boolean and this log statement? I think that's the only use of the variable.

Target:
private static void checkConfiguration() { if (!config.getBooleanProperty(CoreConfig.INGEST_MODE)) { log.error("Ingestion mode not enabled. Please check your configuration"); System.exit(StopReasons.INCORRECT_CONFIGURATION); } log.info("Configuration is good"); }
Source:
public void testNoCassandraHostsFailsValidation() { // given Configuration config = Configuration.getInstance(); config.setProperty(CoreConfig.CASSANDRA_HOSTS, ""); // when BluefloodServiceStarterException ex = null; try { BluefloodServiceStarter.validateCassandraHosts(); } catch (BluefloodServiceStarterException e) { START ex = e; END } // then assertNotNull(ex); assertEquals(-1, ex.getStatus()); } You could do the same thing by doing `@Test(expected = BluefloodServiceStarterException.class)` I would say checking for exit code equals -1 is not that important to do.

Target:
public void testNoCassandraHostsFailsValidation() { // given Configuration config = Configuration.getInstance(); config.setProperty(CoreConfig.CASSANDRA_HOSTS, ""); // when BluefloodServiceStarter.validateCassandraHosts(); // then // exception was thrown }
Source:
public void testCassandraHostWithoutPortFailsValidation() { // given Configuration config = Configuration.getInstance(); config.setProperty(CoreConfig.CASSANDRA_HOSTS, "127.0.0.1"); // when BluefloodServiceStarterException ex = null; try { BluefloodServiceStarter.validateCassandraHosts(); } catch (BluefloodServiceStarterException e) { ex = e; } // then START assertNotNull(ex); END assertEquals(-1, ex.getStatus()); } Can use `@Test(expected = ...)`, see above.

Target:
public void testCassandraHostWithoutPortFailsValidation() { // given Configuration config = Configuration.getInstance(); config.setProperty(CoreConfig.CASSANDRA_HOSTS, "127.0.0.1"); // when BluefloodServiceStarter.validateCassandraHosts(); // then // exception was thrown }
Source:
public void testRollupModeEnabled() { // given Configuration config = Configuration.getInstance(); config.setProperty(CoreConfig.ROLLUP_MODE, "true"); String[] args = new String[0]; // when BluefloodServiceStarterException ex = null; try { BluefloodServiceStarter.main(args); } catch (BluefloodServiceStarterException e) { ex = e; } // then START assertNull(ex); END } We can simplify this test method this way: ``` @Test public void testRollupModeEnabledShouldNotFail() throws Exception { Configuration config = Configuration.getInstance(); config.setProperty(CoreConfig.ROLLUP_MODE, "true"); String[] args = new String[0]; BluefloodServiceStarter.main(args); } ```

Target:
public void testRollupModeEnabled() { // given Configuration config = Configuration.getInstance(); config.setProperty(CoreConfig.ROLLUP_MODE, "true"); // when BluefloodServiceStarter.run(); // then // no exception thrown }
Source:
START public static boolean containsKey(String key) { END return props.containsKey(key); } Do these need to be static?

Target:
public boolean containsKey(String key) { return props.containsKey(key); }
Source:
START public static void clearProperty(Enum<? extends ConfigDefaults> name) { END clearProperty(name.toString()); } Do these need to be static?

Target:
public void clearProperty(Enum<? extends ConfigDefaults> name) { clearProperty(name.toString()); }
Source:
public int getNumPoints() { int enumCount = 0; Set keySet = hashedEnumValues2Count.keySet(); Iterator itr = keySet.iterator(); while(itr.hasNext()){ enumCount+= hashedEnumValues2Count.get(itr.next()); START } END return enumCount; } wouldn't it be clearer to iterate through the values with the foreach syntax, something like this: for (Long value: hashedEnumValues2Count.values()): enumCount += value;

Target:
public int getNumPoints() { int enumCount = 0; for (long count : hashedEnumValues2Count.values()) { enumCount += count; } return enumCount; }
Source:
START private Map<Long, String> getEnumValueFromHashes(ColumnList<Long> enumValues) { END HashMap<Long,String> hash2enumValues = new HashMap<Long, String>(); for (Column<Long> col: enumValues) { hash2enumValues.put(col.getName(), col.getStringValue()); } return hash2enumValues; } This method is useful and should be made public. I am going to need it in my PR. And what happened to the "getColumnsFromEnumCF" method? I am going to need that also. Or should I just add that on my own?

Target:
public Map<Long, String> getEnumValueFromHashes(ColumnList<Long> enumValues) { HashMap<Long,String> hash2enumValues = new HashMap<Long, String>(); for (Column<Long> col: enumValues) { hash2enumValues.put(col.getName(), col.getStringValue()); } return hash2enumValues; }
Source:
START private static <T> Points<T> asPoints(Class<T> type, long initialTime, long timeDelta, T... values) { END Points<T> points = new Points<T>(); long time = initialTime; for (T v : values) { points.add(new Points.Point<T>(time, v)); time += timeDelta; } return points; } You've added multiple copies of this method. Can it be put in a utility class somewhere?

Target:
public static <T> Points<T> asPoints(Class<T> type, long initialTime, long timeDelta, T... values) { Points<T> points = new Points<T>(); long time = initialTime; for (T v : values) { points.add(new Points.Point<T>(time, v)); time += timeDelta; } return points; }
Source:
START public void insertPreaggreatedMetrics(Collection<IMetric> metrics) throws Exception { END try { AstyanaxWriter.getInstance().insertMetrics(metrics, CassandraModel.CF_METRICS_PREAGGREGATED_FULL); } catch (ConnectionException e) { throw new IOException(e); } } What code changes in this class is throwing more exceptions other than IOException that cause you to change this throws definition?

Target:
public void insertPreaggreatedMetrics(Collection<IMetric> metrics) throws IOException { try { AstyanaxWriter.getInstance().insertMetrics(metrics, CassandraModel.CF_METRICS_PREAGGREGATED_FULL); } catch (ConnectionException e) { throw new IOException(e); } }
Source:
public ByteBuffer toByteBuffer(Object o) { try { byte type = typeOf(o); START byte[] buf = new byte[sizeOf(o, type, VERSION_2_TIMER)]; END serializeFullResMetric(o, buf); ByteBuffer out = ByteBuffer.wrap(buf); return out; } catch(IOException e) { throw new RuntimeException(e); } } It seems a bit strange to pass in the `timer` version while serializing non-timer rollups like gauges, counters etc. What do you think about having two overloaded methods named `sizeOf` with one accepting just two arguments i.e `(Object, Type)` which will be used by all non-timer rollup types and then the other one with `timerVersion` as the third argument, which gets called by the timer serializer?

Target:
public ByteBuffer toByteBuffer(Object o) { try { byte type = typeOf(o); byte[] buf = new byte[sizeOf(o, type)]; serializeFullResMetric(o, buf); ByteBuffer out = ByteBuffer.wrap(buf); return out; } catch(IOException e) { throw new RuntimeException(e); } }
Source:
public boolean shouldPersist(Metric metric) throws Exception { START boolean areStringMetricsDropped = Configuration.getInstance().getBooleanProperty(CoreConfig.STRING_METRICS_DROPPED); END if(areStringMetricsDropped) { return false; } else { String currentValue = String.valueOf(metric.getMetricValue()); final String lastValue = AstyanaxReader.getInstance().getLastStringValue(metric.getLocator()); return lastValue == null || !currentValue.equals(lastValue); } } perhaps this should be a static field on the class

Target:
public boolean shouldPersist(Metric metric) throws Exception { if (areStringMetricsDropped) { return false; } else { String currentValue = String.valueOf(metric.getMetricValue()); final String lastValue = AstyanaxReader.getInstance().getLastStringValue(metric.getLocator()); return lastValue == null || !currentValue.equals(lastValue); } }
Source:
START private String getUnit(Metric metric) { END return metric.getUnit(); } Should make static.

Target:
private static String getUnit(Metric metric) { return metric.getUnit(); }
Source:
START public <C> Builder<A, C> withFunction(AsyncFunction<B, C> function) { END Preconditions.checkNotNull(function); ArrayList<AsyncFunction<?, ?>> copy = new ArrayList<AsyncFunction<?, ?>>(this.functions); return new Builder<A, C>(copy); } does this add the function to the list of `functions`?

Target:
public <C> Builder<A, C> withFunction(AsyncFunction<B, C> function) { Preconditions.checkNotNull(function); ArrayList<AsyncFunction<?, ?>> copy = new ArrayList<AsyncFunction<?, ?>>(this.functions); copy.add(function); return new Builder<A, C>(copy); }
Source:
public boolean areTTLsForced() { START final Configuration config = Configuration.getInstance(); END return config.getBooleanProperty(TtlConfig.ARE_TTLS_FORCED); } this method could return a `public static final` that gets set during the static initialization. it would avoid map lookup and object creation for every call.

Target:
public boolean areTTLsForced() { return ARE_TTLS_FORCED; }
Source:
public static final boolean areTTLsForced() { START final Configuration config = Configuration.getInstance(); END return config.getBooleanProperty(TtlConfig.ARE_TTLS_FORCED); } `Configuration.getStringProperty()` (the base method in that class), does at least one map looking, more on overrides.

Target:
public boolean areTTLsForced() { return ARE_TTLS_FORCED; }
Source:
public static void main(String[] args) throws Exception { String[] preLoadClasses = { "javax.servlet.Filter", "javax.servlet.DispatcherType", }; for (String className : preLoadClasses) { START Class.forName(className); END } new IngestApplication().run(args); } Not sure why this code is over here.

Target:
public static void main(String[] args) throws Exception { new IngestApplication().run(args); }
Source:
public void update(long when, int shard) { Long current = updates.get(shard); if (current == null) { updates.put(shard, when); } else { START if (when > current) { END updates.put(shard, when); } } } Why are the shard updates taken only when the collection time is greater than the last update time? We allow uncontrolled update in the current setting right?

Target:
public void update(long when, int shard) { updates.put(shard, when); }
Source:
public void decrementReadCounter(long count) { START readCounter.addAndGet((-1) * count); END owner.interrupt(); } unary minus would make this prettier.

Target:
public void decrementReadCounter(long count) { readCounter.addAndGet(-count); owner.interrupt(); }
Source:
public long getAge() { START return (System.nanoTime() - timestamp) / 1000; END } I'm not sure this is correct. It looks like timestamp is in millis. so `(System.nanoTime()/1000) - timestamp)` may be more correct. Two things: 1) If I'm wrong, and we are using nano stamps to mark a file to indicate its age, we shouldn't do that. 2) if we're just concerned about getting the age of the file, `System.currentTimeMillis()` is good enough. Nanos would be needed if we were getting multiple files per millisecond. Even then, nanos wouldn't give a good indication of age--millis-since-epoch would still need to be part of the file name.

Target:
public long getAge() { return System.currentTimeMillis() - timestamp; }
Source:
START public synchronized void start() { END fileUploader = new DoneFileUploader(); if (uploaderThread != null) { throw new RuntimeException("StorageManager is already started"); } uploaderThread = new Thread(fileUploader, "StorageManager uploader"); uploaderThread.start(); log.info("Storage Manager fully started"); } disregardable nit: this method could do a better job to protect against stupid programmers. `fileManager` will get replaced if `start()` is called twice.

Target:
public synchronized void start() { if (uploaderThread != null) { throw new RuntimeException("StorageManager is already started"); } fileUploader = new DoneFileUploader(); uploaderThread = new Thread(fileUploader, "StorageManager uploader"); uploaderThread.start(); }
Source:
public boolean equals(Object obj) { START if (!(obj instanceof CounterRollup) || obj == null) END return false; CounterRollup other = (CounterRollup)obj; return this.getCount().equals(other.getCount()) && this.rate == other.rate; } I think this should be obj == null || !(obj instanceof CounterRollup)

Target:
public boolean equals(Object obj) { if (obj == null || !(obj instanceof CounterRollup)) return false; CounterRollup other = (CounterRollup)obj; return this.getCount().equals(other.getCount()) && this.rate == other.rate; }
Source:
public boolean equals(Object obj) { START return obj instanceof Locator && obj.hashCode() == this.hashCode(); END } null check?

Target:
public boolean equals(Object obj) { return obj != null && obj instanceof Locator && obj.hashCode() == this.hashCode(); }
Source:
public Emitter once(final String event, final Listener<T> fn) { Listener on = new Listener<T>() { @Override START public void call(T... arg) { END Emitter.this.off(event, this); fn.call(arg); } }; this.onceCallbacks.put(fn, on); this.on(event, on); return this; } args

Target:
public Emitter once(final String event, final Listener<T> fn) { Listener on = new Listener<T>() { @Override public void call(T... args) { Emitter.this.off(event, this); fn.call(args); } }; this.onceCallbacks.put(fn, on); this.on(event, on); return this; }
Source:
public String toString() { switch (type) { case INTEGER: return String.format("%d (int)", intValue); case LONG: return String.format("%d (long)", longValue); case DOUBLE: return String.format("%s (double)", doubleValue); default: START return "ERROR"; END } } throw new RuntimeException() maybe?

Target:
public String toString() { switch (type) { case INTEGER: return String.format("%d (int)", intValue); case LONG: return String.format("%d (long)", longValue); case DOUBLE: return String.format("%s (double)", doubleValue); default: return super.toString(); } }
Source:
START public void start() { END synchronized (running) { if (running.get()) return; else { running.set(true); run(); } } } I think we can just make the method synchronized. Might be easier to read.

Target:
public synchronized void start() { if (running.get()) return; else { run(); // running.get == true now. } }
Source:
public final boolean test(IPerson person) { Object[] atts = person.getAttributeValues(getAttributeName()); START if (atts != null && atts.length > 0) { END return false; } return true; } :art: `return atts == null || atts.length < 1`

Target:
public final boolean test(IPerson person) { Object[] atts = person.getAttributeValues(getAttributeName()); return atts == null || atts.length < 1; }
Source:
public String lookupEntityName(Entity entity) { START if (entity != null) { END EntityEnum entityEnum = EntityEnum.getEntityEnum(entity.getEntityType()); return lookupEntityName(entityEnum, entity.getId()); } return null; } :art: Personally I would lean toward using a guard statement. ```java if (entity == null) { return null } ... ```

Target:
public String lookupEntityName(Entity entity) { if (entity == null) { return null; } EntityEnum entityEnum = EntityEnum.getEntityEnum(entity.getEntityType()); return lookupEntityName(entityEnum, entity.getId()); }
Source:
public Collection<PhysicalAddress> fetchClusterMembers(String clusterName) { //If no DAO has been set just return an empty list if (pingDao == null) { log.info("No PingDao set, returning empty set for current cluster members"); return Collections.emptyList(); } //Add our address to the store getAndSavePhysicalAddress(clusterName); //Get the current cluster members final Map<Address, PhysicalAddress> existing_mbrs = pingDao.getAddresses(clusterName); START END //Return current members return existing_mbrs.values(); } I don't agree with the above change. I think you want your list of existing members to be everyone BUT yourself. You don't want to send messages to yourself.

Target:
public Collection<PhysicalAddress> fetchClusterMembers(String clusterName) { //If no DAO has been set just return an empty list if (pingDao == null) { log.info("No PingDao set, returning empty set for current cluster members"); return Collections.emptyList(); } //Get the current cluster members final Map<Address, PhysicalAddress> existing_mbrs = pingDao.getAddresses(clusterName); //Add our address to the store getAndSavePhysicalAddress(clusterName); //Return current members return existing_mbrs.values(); }
Source:
private Set<IGroupMember> primGetAllMembers(Set<IGroupMember> rslt) throws GroupsException { final Set<IGroupMember> members = getChildren(); START for (IGroupMember gm : members) { END rslt.add(gm); if (gm.isGroup()) { ((EntityGroupImpl) gm).primGetAllMembers(rslt); } } return rslt; } This assignment could be removed

Target:
private Set<IGroupMember> primGetAllMembers(Set<IGroupMember> rslt) throws GroupsException { for (IGroupMember gm : getChildren()) { rslt.add(gm); if (gm.isGroup()) { ((EntityGroupImpl) gm).primGetAllMembers(rslt); } } return rslt; }
Source:
public boolean isMemberOf(IEntityGroup group) throws GroupsException { final Set<IEntityGroup> parents = getParentGroups(); START return parents.contains(group); END } Refactor to 1 line?

Target:
public boolean isMemberOf(IEntityGroup group) throws GroupsException { return getParentGroups().contains(group); }
Source:
private String getUsernameForUserId(int id) { if (id > 0) { String username = userIdentityStore.getPortalUserName(id); if (username != null) { return username; } START logger.warn("Invalid userID found when exporting a portlet; return system username instead"); END } return systemUsername; } Placeholder `{}` without placeholder value?

Target:
private String getUsernameForUserId(int id) { if (id > 0) { String username = userIdentityStore.getPortalUserName(id); if (username != null) { return username; } logger.warn("Invalid userID found when exporting a portlet; return system username instead", id); } return systemUsername; }
Source:
private IPersonAttributesGroupDefinition getPagsGroupDefByName(String name) { Set<IPersonAttributesGroupDefinition> pagsGroups = personAttributesGroupDefinitionDao.getPersonAttributesGroupDefinitionByName(name); if (pagsGroups.size() > 1) { START logger.warn("More than one PAGS group with name found.", name); END } return pagsGroups.isEmpty() ? null : pagsGroups.iterator().next(); } `warn` seems insufficiently dire for a violation of a fundamental assumption of the groups system. `error` at the least? I'm not sure returning what is effectively a random selection among the illegally multiple groups with the same name is the right behavior. I think I'd rather it fail with an exception. Not an exception that results in the entire portal falling over dead, of course, but an exception that at least fails the specific group operation being computed. Multiple groups with the same name is, alas, not okay.

Target:
private IPersonAttributesGroupDefinition getPagsGroupDefByName(String name) { Set<IPersonAttributesGroupDefinition> pagsGroups = personAttributesGroupDefinitionDao.getPersonAttributesGroupDefinitionByName(name); if (pagsGroups.size() > 1) { logger.error("More than one PAGS group with name found.", name); } return pagsGroups.isEmpty() ? null : pagsGroups.iterator().next(); }
Source:
private void updateStickyProfile(IPerson person, UserProfile stickyProfile, String profileName) { if (person.getID() == -1) { try { throw new RuntimeException(); } catch (Exception e) { START e.printStackTrace(System.out); END } } stickyProfile.setProfileName(profileName); layoutStore.updateUserProfile(person, stickyProfile); } This seems... strange.

Target:
private void updateStickyProfile(IPerson person, UserProfile stickyProfile, String profileName) { stickyProfile.setProfileName(profileName); layoutStore.updateUserProfile(person, stickyProfile); }
Source:
protected void doHeaders(RenderRequest request, RenderResponse response) { try { doDispatch(request, response); } catch (IOException ex) { logger.error("Exception rendering headers for portlet " + getPortletName() + ". Aborting doHeaders", ex); START } catch (PortletException ex) { END logger.error("Exception rendering headers for portlet " + getPortletName() + ". Aborting doHeaders", ex); } } Opportunity to use JDK 7 multicatch `catch (IOException | PortletException ex)`.

Target:
protected void doHeaders(RenderRequest request, RenderResponse response) { try { doDispatch(request, response); } catch (IOException | PortletException ex) { logger.error("Exception rendering headers for portlet " + getPortletName() + ". Aborting doHeaders", ex); } }
Source:
public IEntityGroup find(String name) throws GroupsException { START List<IPersonAttributesGroupDefinition> groups = personAttributesGroupDefinitionDao.getPersonAttributesGroupDefinitionByName(name); END IPersonAttributesGroupDefinition pagsGroup = groups.get(0); GroupDefinition groupDef = initGroupDef(pagsGroup); IEntityGroup group = new EntityTestingGroupImpl(groupDef.getKey(), IPERSON_CLASS); group.setName(groupDef.getName()); group.setDescription(groupDef.getDescription()); return group; } Undetected error condition where multiple groups match the name?

Target:
public IEntityGroup find(String name) throws GroupsException { Set<IPersonAttributesGroupDefinition> groups = personAttributesGroupDefinitionDao.getPersonAttributesGroupDefinitionByName(name); IPersonAttributesGroupDefinition pagsGroup = groups.iterator().next(); GroupDefinition groupDef = initGroupDef(pagsGroup); IEntityGroup group = new EntityTestingGroupImpl(groupDef.getKey(), IPERSON_CLASS); group.setName(groupDef.getName()); group.setDescription(groupDef.getDescription()); return group; }
Source:
private IPersonAttributesGroupStoreDefinition getOrCreateStore() { List<IPersonAttributesGroupStoreDefinition> stores = personAttributesGroupStoreDefinitionDao.getPersonAttributesGroupStoreDefinitions(); if (stores.size() == 0) { return personAttributesGroupStoreDefinitionDao.createPersonAttributesGroupStoreDefinition("Default", "Default Person Attribute Group Store"); } else { START return stores.get(0); END } } Undetected error condition where there are multiple `IPersonAttributesGroupStoreDefinition`s? Perhaps not a failure-inducing error, but at least an odd state of affairs worth logging?

Target:
private IPersonAttributesGroupStoreDefinition getOrCreateStore() { Set<IPersonAttributesGroupStoreDefinition> stores = personAttributesGroupStoreDefinitionDao.getPersonAttributesGroupStoreDefinitions(); if (stores.size() == 0) { return personAttributesGroupStoreDefinitionDao.createPersonAttributesGroupStoreDefinition("Default", "Default Person Attribute Group Store"); } else { return stores.iterator().next(); } }
Source:
private IPersonAttributesGroupDefinition getOrCreateGroup(IPersonAttributesGroupStoreDefinition store, String name, String description) { List<IPersonAttributesGroupDefinition> groups = personAttributesGroupDefinitionDao.getPersonAttributesGroupDefinitionByName(name); if (groups.size() == 0) { return personAttributesGroupDefinitionDao.createPersonAttributesGroupDefinition(store, name, description); START } else { END groups.get(0).setDescription(description); personAttributesGroupDefinitionDao.updatePersonAttributesGroupDefinition(groups.get(0)); return groups.get(0); } } Undetected error condition where the `personAttributesGroupDefinitionDao` found multiple group definitions matching the `name`?

Target:
private IPersonAttributesGroupDefinition getOrCreateGroup(IPersonAttributesGroupStoreDefinition store, String name, String description) { Set<IPersonAttributesGroupDefinition> groups = personAttributesGroupDefinitionDao.getPersonAttributesGroupDefinitionByName(name); if (groups.size() == 0) { return personAttributesGroupDefinitionDao.createPersonAttributesGroupDefinition(store, name, description); } else { groups.iterator().next().setDescription(description); personAttributesGroupDefinitionDao.updatePersonAttributesGroupDefinition(groups.iterator().next()); return groups.iterator().next(); } }
Source:
START public Server(String clusterName, String mainDirectory, String languages, String transportAddresses) throws Exception { END try { if (SystemUtils.IS_OS_WINDOWS) { setupDirectories(new URL("file:///" + mainDirectory)); } else { setupDirectories(new URL("file://" + mainDirectory)); } } catch (Exception e) { throw new RuntimeException("Can't create directories: ", e); } this.clusterName = clusterName; this.languages = languages.split(","); this.transportAddresses = transportAddresses; } Delete 'throws Exception'? Also above.

Target:
public Server(String clusterName, String mainDirectory, String languages, String transportAddresses) { try { if (SystemUtils.IS_OS_WINDOWS) { setupDirectories(new URL("file:///" + mainDirectory)); } else { setupDirectories(new URL("file://" + mainDirectory)); } } catch (Exception e) { throw new RuntimeException("Can't create directories: ", e); } this.clusterName = clusterName; this.languages = languages.split(","); this.transportAddresses = transportAddresses; }
Source:
public String convert(QueryBuilder anItem) { try { BytesReference bytes = anItem.toXContent(JsonXContent.contentBuilder(), new ToXContent.MapParams(null)) .bytes(); return bytes.utf8ToString(); } catch (IOException e) { log.error("Unable to transform querybuilder to a json string due to an exception", e); START return null; END } } I know this was already there but I think we should throw an exception here instead of silently accepting it, e.g. `throw new RuntimeException("Unable to transform ....", e);`

Target:
public String convert(QueryBuilder anItem) { try { BytesReference bytes = anItem.toXContent(JsonXContent.contentBuilder(), new ToXContent.MapParams(null)) .bytes(); return bytes.utf8ToString(); } catch (IOException e) { log.error("Unable to transform querybuilder to a json string due to an exception", e); throw new RuntimeException("Unable to transform querybuilder to a json string due to an exception", e); } }
Source:
public boolean isUsefulForIndex() { if("place".equals(tagKey) && "houses".equals(tagValue)) return false; if(houseNumber != null) return true; if(name.isEmpty()) return false; START return linkedPlaceId <= 0; END } intellij is continuously recommending to simplify this code this way, but i think it is very hard to understand this way

Target:
public boolean isUsefulForIndex() { if("place".equals(tagKey) && "houses".equals(tagValue)) return false; if(houseNumber != null) return true; if(name.isEmpty()) return false; if(linkedPlaceId > 0) return false; return true; }
Source:
public IndexPreprocessor(final String prefix, final String theNamespace_url, final String draftParameter) { this.prefix = prefix; this.namespace_url = theNamespace_url; this.excludedDraftSection.clear(); this.excludedDraftSection.add(false); START includeDraft = draftParameter.equals(ARGS_DRAFT_YES) ? true : false; END indexDitaProcessor = new IndexDitaProcessor(); indexGroupProcessor = new IndexGroupProcessor(); } Simplify this to just ```java includeDraft = draftParameter.equals(ARGS_DRAFT_YES); ```

Target:
public IndexPreprocessor(final String prefix, final String theNamespace_url, final String draftParameter) { this.prefix = prefix; this.namespace_url = theNamespace_url; this.excludedDraftSection.clear(); this.excludedDraftSection.add(false); includeDraft = draftParameter.equals(ARGS_DRAFT_YES); indexDitaProcessor = new IndexDitaProcessor(); indexGroupProcessor = new IndexGroupProcessor(); }
Source:
private void printPlugins() { final List<String> installedPlugins = getInstalledPlugins(); if (installedPlugins != null) { System.out.println("The following DITA-OT plugins are installed:"); for (final String plugin : installedPlugins) { System.out.println(" " + plugin); } } else { System.out.println("No DITA-OT plugins are installed."); } START } END I'm not sure if I want to have this line output and each ID prefixed with spaces. My preference would be to just have one ID per line, without any prefixes. That way the output could be piped to other processes without parsing out the pretty printing. This is basically [plumbing vs porcelain](https://git-scm.com/book/en/v2/Git-Internals-Plumbing-and-Porcelain#_plumbing_porcelain) distinction.

Target:
private void printPlugins() { final List<String> installedPlugins = getInstalledPlugins(); for (final String plugin : installedPlugins) { System.out.println(plugin); } }
Source:
private void insertAction(final Action action, final FilterKey key) { if (filterMap.get(key) == null) { filterMap.put(key, action); } else { START logger.error(MessageUtils.getMessage("DOTJ007W", key.toString()).toString()); END } } This will still be logged as `error`. Shouldn't this be `logger.warn`?

Target:
private void insertAction(final Action action, final FilterKey key) { if (filterMap.get(key) == null) { filterMap.put(key, action); } else { logger.warn(MessageUtils.getMessage("DOTJ007W", key.toString()).toString()); } }
Source:
public void endElement(final String uri, final String localName, final String qName) throws SAXException { // @processing-role processRoleStack.pop(); final DitaClass cls = classes.pop(); if ((cls == null || !cls.isValid()) && !ELEMENT_NAME_DITA.equals(localName)) { START return; END } getContentHandler().endElement(uri, localName, qName); } This is a filter. If we return before passing the end element event to the next content handler, we'll end up with unbalanced tree. Is this really correct?

Target:
public void endElement(final String uri, final String localName, final String qName) throws SAXException { // @processing-role processRoleStack.pop(); classes.pop(); getContentHandler().endElement(uri, localName, qName); }
Source:
public ValidationLayer getValidationLayer() throws CatalogException { if(valLayer != null) { return valLayer; } else { START throw new CatalogException("validation layer is not initialized"); END } } Let's keep this method unchanged since it is better we modify the interface `Catalog`. Instead let's add null checks when this method is being used.

Target:
public ValidationLayer getValidationLayer() { return valLayer; }
Source:
public static OlapAnnotation getOlapAnnotationByName( final String name, List<OlapAnnotation> annotations) { OlapAnnotation foundAnnotation = null; for( OlapAnnotation annotation : annotations ) { if ( name.equals( annotation.getName() ) ) { START foundAnnotation = annotation; END } } return foundAnnotation; } break from for loop if annotation is found

Target:
public static OlapAnnotation getOlapAnnotationByName( final String name, List<OlapAnnotation> annotations) { OlapAnnotation foundAnnotation = null; for( OlapAnnotation annotation : annotations ) { if ( name.equals( annotation.getName() ) ) { foundAnnotation = annotation; break; } } return foundAnnotation; }
Source:
START public static <T> Flowable<T> fromCompletionStage(@NonNull CompletionStage<T> stage) { END ObjectHelper.requireNonNull(stage, "stage is null"); return RxJavaPlugins.onAssembly(new FlowableFromCompletionStage<>(stage)); } +NonNull for return type

Target:
public static <T> Flowable<@NonNull T> fromCompletionStage(@NonNull CompletionStage<T> stage) { ObjectHelper.requireNonNull(stage, "stage is null"); return RxJavaPlugins.onAssembly(new FlowableFromCompletionStage<>(stage)); }
Source:
START public static <T> Flowable<T> fromStream(@NonNull Stream<T> stream) { END ObjectHelper.requireNonNull(stream, "stream is null"); return RxJavaPlugins.onAssembly(new FlowableFromStream<>(stream)); } +NonNull for return type

Target:
public static <T> Flowable<@NonNull T> fromStream(@NonNull Stream<T> stream) { ObjectHelper.requireNonNull(stream, "stream is null"); return RxJavaPlugins.onAssembly(new FlowableFromStream<>(stream)); }
Source:
public void onComplete() { subscribers.dispose(); synchronized (this) { Map<Long, C> bufs = buffers; if (bufs == null) { return; } for (C b : bufs.values()) { queue.offer(b); } START bufs = null; END } done = true; drain(); } shouldn't this be `buffers = null`?

Target:
public void onComplete() { subscribers.dispose(); synchronized (this) { Map<Long, C> bufs = buffers; if (bufs == null) { return; } for (C b : bufs.values()) { queue.offer(b); } buffers = null; } done = true; drain(); }
Source:
void boundaryError(Disposable subscriber, Throwable ex) { SubscriptionHelper.cancel(upstream); START subscribers.delete(subscriber); END if (errors.addThrowable(ex)) { subscribers.dispose(); synchronized (this) { buffers = null; } done = true; drain(); } else { RxJavaPlugins.onError(ex); } } Can we just `dispose()` all subscribers here and remove `dispose()` call below?

Target:
void boundaryError(Disposable subscriber, Throwable ex) { SubscriptionHelper.cancel(upstream); subscribers.delete(subscriber); onError(ex); }
Source:
public final Disposable subscribe(final Action onComplete, final Consumer<? super Throwable> onError) { ObjectHelper.requireNonNull(onError, "onError is null"); ObjectHelper.requireNonNull(onComplete, "onComplete is null"); START return subscribe(onComplete, onError, Functions.emptyConsumer()); END } No need for null checks as you delegate to a common method.

Target:
public final Disposable subscribe(final Action onComplete, final Consumer<? super Throwable> onError) { return subscribe(onComplete, onError, Functions.emptyConsumer()); }
Source:
public final Disposable subscribe(final Action onComplete) { ObjectHelper.requireNonNull(onComplete, "onComplete is null"); START return subscribe(onComplete, Functions.ON_ERROR_MISSING); END } No need for null checks. Also since that subscribe delegates to a third method, one call indirection could be avoided by call the new method directly.

Target:
public final Disposable subscribe(final Action onComplete) { return subscribe(onComplete, Functions.ON_ERROR_MISSING); }
Source:
public final Maybe<T> defaultIfEmpty(T defaultItem) { ObjectHelper.requireNonNull(defaultItem, "item is null"); START return switchIfEmpty(Single.just(defaultItem)); END } Why was this changed, the original `just` should still work?!

Target:
public final Maybe<T> defaultIfEmpty(T defaultItem) { ObjectHelper.requireNonNull(defaultItem, "item is null"); return switchIfEmpty(just(defaultItem)); }
Source:
public void onError(Throwable e) { if (done) { START return; END } done = true; try { actual.onError(e); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); RxJavaHooks.onError(e); throw new OnErrorFailedException(new CompositeException(e, ex)); } } You should have moved it here.

Target:
public void onError(Throwable e) { if (done) { RxJavaHooks.onError(e); return; } done = true; try { actual.onError(e); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); throw new OnErrorFailedException(new CompositeException(e, ex)); } }
Source:
final void removeFirst() { Node head = get(); Node next = head.get(); size--; // can't just move the head because it would retain the very first value // can't null out the head's value because of late replayers would see null Node newHead = new Node(null); Node newNext = next.get(); START newHead.set(newNext); END setFirst(newHead); if (newNext == null) { tail = newHead; } } This can be `lazySet`.

Target:
final void removeFirst() { Node head = get(); Node next = head.get(); size--; // can't just move the head because it would retain the very first value // can't null out the head's value because of late replayers would see null setFirst(next); }
Source:
START UnicastProcessor(int capacityHint) { END this(capacityHint, true); } Is this one really necessary?

Target:
UnicastProcessor(int capacityHint) { this(capacityHint,null, true); }
Source:
public SingleScheduler(ThreadFactory threadFactory) { START this.threadFactory = ObjectHelper.requireNonNull(threadFactory, "threadFactory was null"); END executor.lazySet(createExecutor(threadFactory)); } Either this is unnecessary or you forgot to do this with the other new constructors.

Target:
public SingleScheduler(ThreadFactory threadFactory) { this.threadFactory = threadFactory; executor.lazySet(createExecutor(threadFactory)); }
Source:
public ReduceSeedObserver(SingleObserver<? super R> actual, BiFunction<R, ? super T, R> reducer, R value) { this.actual = actual; this.value = value; this.reducer = reducer; START this.value = value; END } 2x `this.value = value`? L64 & L66.

Target:
public ReduceSeedObserver(SingleObserver<? super R> actual, BiFunction<R, ? super T, R> reducer, R value) { this.actual = actual; this.value = value; this.reducer = reducer; }
Source:
public void onError(Throwable e) { if (done) { RxJavaPlugins.onError(e); return; } START value = null; END actual.onError(e); } needs `done=true`

Target:
public void onError(Throwable e) { if (done) { RxJavaPlugins.onError(e); return; } done = true; value = null; actual.onError(e); }
Source:
public void onNext(T value) { START R v = this.value; END try { this.value = ObjectHelper.requireNonNull(reducer.apply(v, value), "The reducer returned a null value"); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); d.dispose(); onError(ex); } } `done` checks in this class?

Target:
public void onNext(T value) { R v = this.value; if (v != null) { try { this.value = ObjectHelper.requireNonNull(reducer.apply(v, value), "The reducer returned a null value"); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); d.dispose(); onError(ex); } } }
Source:
START public AsyncProcessor() { END this.subscribers = new AtomicReference<AsyncSubscription<T>[]>(EMPTY); } Seems redundant to have both static factories and public constructors in the public API. Especially when there's multiple overloads such as in some of the other processors. Can we choose one and expose only it?

Target:
AsyncProcessor() { this.subscribers = new AtomicReference<AsyncSubscription<T>[]>(EMPTY); }
Source:
START @Override public Object call() { END return null; // null scalar is interpreted as being empty } nit: ~Square formatting

Target:
public Object call() { return null; // null scalar is interpreted as being empty }
Source:
public OnSubscribeToMap(Observable<T> source, Func1<? super T, ? extends K> keySelector, Func1<? super T, ? extends V> valueSelector) { START this(source, keySelector, valueSelector, DefaultMapFactory.<K, V>instance()); END } A small trick: make the OnSubscribeToMap also implement `Func0<Map<K, V>>` and assign `this` to the map factory function - of course you can't use `this()` constructor delegation but assign to the final fields explicitly. This way, there is no need for an extra class.

Target:
public OnSubscribeToMap(Observable<T> source, Func1<? super T, ? extends K> keySelector, Func1<? super T, ? extends V> valueSelector) { this(source, keySelector, valueSelector, null); }
Source:
public void call(final Subscriber<? super T> child) { final Worker worker = scheduler.createWorker(); child.add(worker); SkipTimedSubscriber<T> subscriber = new SkipTimedSubscriber<T>(child); START worker.schedule(subscriber, time, unit); END source.unsafeSubscribe(subscriber); } That's wrong because it calls `unsubscribe` in the `onError`/`onCompleted` path and unsubscribes the child. The `worker` should be added to `subscriber` instead and `subscriber` added to the `child`. No constructor forwarding.

Target:
public void call(final Subscriber<? super T> child) { final Worker worker = scheduler.createWorker(); SkipTimedSubscriber<T> subscriber = new SkipTimedSubscriber<T>(child); subscriber.add(worker); child.add(subscriber); worker.schedule(subscriber, time, unit); source.unsafeSubscribe(subscriber); }
Source:
public void unsubscribe() { if (once.compareAndSet(false, true)) { // unsubscribe should be idempotent, so only do this once // Release the worker _after_ the previous action (if any) has completed START threadWorker.schedule(new Action0() { END @Override public void call() { pool.release(threadWorker); } }); } innerSubscription.unsubscribe(); } EventLoopWorker can implement Action0 and schedule itself to release.

Target:
public void unsubscribe() { if (once.compareAndSet(false, true)) { // unsubscribe should be idempotent, so only do this once // Release the worker _after_ the previous action (if any) has completed threadWorker.schedule(this); } innerSubscription.unsubscribe(); }
Source:
public final Completable flatMapCompletable(final Func1<? super T, ? extends Completable> func) { START return Completable.create(new CompletableFlatMapSingleToCompletable(this, func)); END } You forgot to commit the class itself. Plus, use `new CompletableFlatMapSingleToCompletable<T>(this, func)` as it is a generic class.

Target:
public final Completable flatMapCompletable(final Func1<? super T, ? extends Completable> func) { return Completable.create(new CompletableFlatMapSingleToCompletable<T>(this, func)); }