auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>default UniConstraintStream<A> ifExistsOther(Class<A> otherClass) { <START> return ifExists(otherClass, Joiners.filtering((a, b) -> !a.equals(b))); <END> }</code><technical_language>Due Lambda identity, implement this slight different. explain: 2 statements lambda instance: - from(A.class).join(B.class).filter(Objects::equal) - from(A.class).join(B.class).filter(Objects::equal) 2 statements do lambda instance: - from(C.class).join(D.class).filter((c, d) -> c.equals(d)) - from(C.class).join(D.class).filter((c, d) -> c.equals(d)) try this out printing System.systemHashCode() BiPredicates. Now, do care that? of node sharing in Drools Bavet. If lambda instance, node sharing work guaranteed. If isn't, Bavet Drools some dirty ASM magic recognize code. Unfortunately, is Objects.notEquals in java.util.Objects. Apache commons-lang3 ObjectUtils.notEqual, presuming want that, I write: return ifExists(otherClass, Joiners.filtering(ObjectUtils::notEqual);</technical_language>

Target:
default UniConstraintStream<A> ifExistsOther(Class<A> otherClass) { return ifExists(otherClass, Joiners.filtering(ObjectUtils::notEqual)); }
Source:
<code>public void createNotificationChannel() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { <START> CharSequence name = appContext.getString(R.string.notification_text); <END> int importance = NotificationManager.IMPORTANCE_LOW; NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance); NotificationManager notificationManager = appContext.getSystemService(NotificationManager.class); notificationManager.createNotificationChannel(channel); } }</code><technical_language>I suggest putting a more name for channel name "Review reminder", name show in settings for people toggle</technical_language>

Target:
public void createNotificationChannel() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { CharSequence name = appContext.getString(R.string.review_reminder); int importance = NotificationManager.IMPORTANCE_LOW; NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance); NotificationManager notificationManager = appContext.getSystemService(NotificationManager.class); notificationManager.createNotificationChannel(channel); } }
Source:
<code>private void assertNicRemoved(Nic nic) { assertPredicate(new Predicate<String>() { @Override public boolean apply(String args) { String[] params = args.split(","); return nicApi().get(params[0], params[1], params[2]) == null; } <START> }, complexId(nic.dataCenterId(), testServer.id(), nic.id())); <END> }</code><technical_language>Nic for predicate too</technical_language>

Target:
private void assertNicRemoved(Nic nic) { assertPredicate(new Predicate<Nic>() { @Override public boolean apply(Nic testNic) { return nicApi().get(testNic.dataCenterId(), testNic.serverId(), testNic.id()) == null; } }, nic); }
Source:
<code>private boolean checkConnection() { boolean dbStatus = false; if (!connected) { logger.error("checkConnection: database is not connected"); dbStatus = false; } else { try { Pong pong = influxDB.ping(); String version = pong.getVersion(); if (version != null && !version.contains("unknown")) { dbStatus = true; logger.debug("database status is OK"); } else { logger.error("database connection failed, version is: \"{}\" response time was \"{}\"", version, pong.getResponseTime()); dbStatus = false; } } catch (RuntimeException e) { dbStatus = false; <START> logger.error("database connection failed throwing an exception"); <END> handleDatabaseException(e); } } return dbStatus; }</code><technical_language>add e.getMessage() log statement</technical_language>

Target:
private boolean checkConnection() { boolean dbStatus = false; if (!connected) { logger.error("checkConnection: database is not connected"); dbStatus = false; } else { try { Pong pong = influxDB.ping(); String version = pong.getVersion(); if (version != null && !version.contains("unknown")) { dbStatus = true; logger.debug("database status is OK, version is {}", version); } else { logger.error("database ping error, version is: \"{}\" response time was \"{}\"", version, pong.getResponseTime()); dbStatus = false; } } catch (RuntimeException e) { dbStatus = false; logger.error("database connection failed", e); handleDatabaseException(e); } } return dbStatus; }
Source:
<code>public void addStateTo(StateDumpCollector dump) { dump.addState("exclusiveHolder", String.valueOf(exclusiveHolder)); { StateDumpCollector releaseListenersDump = dump.subStateDumpCollector("releaseListeners"); int idx = 0; for (ClientDescriptor releaseListener : new HashSet<>(this.releaseListeners)) { releaseListenersDump.addState(String.valueOf(idx++), releaseListener.toString()); } } { <START> StateDumpCollector sharedHolders = dump.subStateDumpCollector("sharedHolders"); <END> int idx = 0; for (ClientDescriptor sharedHolder : new HashSet<>(this.sharedHolders)) { sharedHolders.addState(String.valueOf(idx++), sharedHolder.toString()); } } }</code><technical_language>Shared holders dumped level exclusive holder. is situation</technical_language>

Target:
public void addStateTo(StateDumpCollector dump) { ClientDescriptor exclusiveHolder = this.exclusiveHolder; Set<ClientDescriptor> sharedHolders = new HashSet<>(this.sharedHolders); Set<ClientDescriptor> releaseListeners = new HashSet<>(this.releaseListeners); { StateDumpCollector holdersDump = dump.subStateDumpCollector("holders"); if (exclusiveHolder != null) { holdersDump.addState("exclusive", String.valueOf(exclusiveHolder)); } if(!sharedHolders.isEmpty()) { StateDumpCollector sharedDump = holdersDump.subStateDumpCollector("shared"); int idx = 0; for (ClientDescriptor holder : sharedHolders) { sharedDump.addState(String.valueOf(idx++), String.valueOf(holder)); } } } { StateDumpCollector releaseListenersDump = dump.subStateDumpCollector("releaseListeners"); int idx = 0; for (ClientDescriptor releaseListener : new HashSet<>(releaseListeners)) { releaseListenersDump.addState(String.valueOf(idx++), String.valueOf(releaseListener)); } } }
Source:
<code>private BasicDBObject objectToBson(JsonNodeCursor cursor, EntityMetadata md) { BasicDBObject ret = new BasicDBObject(); do { Path path = cursor.getCurrentPath(); JsonNode node = cursor.getCurrentNode(); LOGGER.debug("field: {}", path); FieldTreeNode fieldMdNode = null; try { fieldMdNode = md.resolve(path); } catch (Exception e) { <START> return null; <END> } if (fieldMdNode instanceof SimpleField) { toBson(ret, (SimpleField) fieldMdNode, path, node, md); } else if (fieldMdNode instanceof ObjectField) { convertObjectFieldToBson(node, cursor, ret, path, md); } else if (fieldMdNode instanceof ArrayField) { convertArrayFieldToBson(node, cursor, ret, fieldMdNode, path, md); } else if (fieldMdNode instanceof ReferenceField) { convertReferenceFieldToBson(node,path); } } while (cursor.nextSibling()); return ret; }</code><technical_language>This hides exception. I removing try-catch best,</technical_language>

Target:
private BasicDBObject objectToBson(JsonNodeCursor cursor, EntityMetadata md) { BasicDBObject ret = new BasicDBObject(); do { Path path = cursor.getCurrentPath(); JsonNode node = cursor.getCurrentNode(); LOGGER.debug("field: {}", path); FieldTreeNode fieldMdNode = md.resolve(path); if (fieldMdNode instanceof SimpleField) { toBson(ret, (SimpleField) fieldMdNode, path, node, md); } else if (fieldMdNode instanceof ObjectField) { convertObjectFieldToBson(node, cursor, ret, path, md); } else if (fieldMdNode instanceof ArrayField) { convertArrayFieldToBson(node, cursor, ret, fieldMdNode, path, md); } else if (fieldMdNode instanceof ReferenceField) { convertReferenceFieldToBson(node,path); } } while (cursor.nextSibling()); return ret; }
Source:
<code>public void setHandler(Object handler) { <START> Assert.state(handler instanceof MessageHandler || handler instanceof ReactiveMessageHandler, <END> "'handler' must be an instance of 'MessageHandler' or 'ReactiveMessageHandler'"); synchronized (this.handlerMonitor) { Assert.isNull(this.handler, "handler cannot be overridden"); if (handler instanceof ReactiveMessageHandler) { this.handler = new ReactiveMessageHandlerAdapter((ReactiveMessageHandler) handler); } else { this.handler = (MessageHandler) handler; } } }</code><technical_language>ISE instead of IAE? This is a setter. Assert.isTrue()</technical_language>

Target:
public void setHandler(Object handler) { Assert.isTrue(handler instanceof MessageHandler || handler instanceof ReactiveMessageHandler, "'handler' must be an instance of 'MessageHandler' or 'ReactiveMessageHandler'"); synchronized (this.handlerMonitor) { Assert.isNull(this.handler, "handler cannot be overridden"); if (handler instanceof ReactiveMessageHandler) { this.handler = new ReactiveMessageHandlerAdapter((ReactiveMessageHandler) handler); } else { this.handler = (MessageHandler) handler; } } }
Source:
<code>protected void put(Data dataKey, Data dataValue) { MultiMapContainer container = getOrCreateContainer(); Collection c = (Collection) toObject(dataValue); Collection<MultiMapRecord> coll = container.getOrCreateMultiMapValue(dataKey).getCollection(false); Consumer addObjToCollection = o -> { recordId = container.nextId(); <START> MultiMapRecord record = new MultiMapRecord(recordId, o); <END> coll.add(record); getOrCreateContainer().update(); publishEvent(EntryEventType.ADDED, dataKey, o, null); }; if (coll instanceof Set) { c.parallelStream().distinct().forEach(addObjToCollection); } else { c.parallelStream().forEach(addObjToCollection); } }</code><technical_language>Need respect configured in-memory format here. Do MultiMapRecord record = new MultiMapRecord(recordId, isBinary() ? o : toObject(o)); public final boolean isBinary() { return getOrCreateContainer().getConfig().isBinary(); }</technical_language>

Target:
protected void put(Data dataKey, Data dataValue) { MultiMapContainer container = getOrCreateContainer(); Collection<Data> c = ((DataCollection) toObject(dataValue)).getCollection(); Collection<MultiMapRecord> coll = container.getOrCreateMultiMapValue(dataKey).getCollection(false); Iterator<Data> it = c.iterator(); while (it.hasNext()) { Data o = it.next(); MultiMapRecord record = new MultiMapRecord(container.nextId(), isBinary() ? o : toObject(o)); if (coll.add(record)) { getOrCreateContainer().update(); publishEvent(EntryEventType.ADDED, dataKey, o, null); response = true; } } }
Source:
<code>public List<ParseResult<CompilationUnit>> tryToParse(String startPackage) throws IOException { assertNotNull(startPackage); Log.info("Parsing package \"%s\"", startPackage); final Path path = packageAbsolutePath(root, startPackage); class AsynchronousParse extends RecursiveAction { private static final long serialVersionUID = 1L; private final Path path; public AsynchronousParse(Path path) { this.path = path; } @Override protected void compute() { final List<AsynchronousParse> walks = new ArrayList<>(); try { Files.walkFileTree(path, new SimpleFileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { if (!dir.equals(AsynchronousParse.this.path)) { AsynchronousParse w = new AsynchronousParse(dir); w.fork(); walks.add(w); <START> return FileVisitResult.SKIP_SUBTREE; <END> } else { return FileVisitResult.CONTINUE; } } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (!attrs.isDirectory() && file.toString().endsWith(".java")) { Path relative = root.relativize(file.getParent()); tryToParse(relative.toString(), file.getFileName().toString()); } return FileVisitResult.CONTINUE; } }); } catch (IOException e) { Log.error(e); } for (AsynchronousParse w : walks) { w.join(); } } } AsynchronousParse w = new AsynchronousParse(path); ForkJoinPool p = new ForkJoinPool(); p.invoke(w); return getCache(); }</code><technical_language>This piece of code is duplicated below, chance of cleaning up? (only if improves of course)</technical_language>

Target:
public List<ParseResult<CompilationUnit>> tryToParse(String startPackage) throws IOException { assertNotNull(startPackage); Log.info("Parsing package \"%s\"", startPackage); final Path path = packageAbsolutePath(root, startPackage); Files.walkFileTree(path, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (!attrs.isDirectory() && file.toString().endsWith(".java")) { Path relative = root.relativize(file.getParent()); tryToParse(relative.toString(), file.getFileName().toString()); } return FileVisitResult.CONTINUE; } }); return getCache(); }
Source:
<code>public ActualProperties visitAssignUniqueId(AssignUniqueId node, List<ActualProperties> inputProperties) { ActualProperties properties = Iterables.getOnlyElement(inputProperties); ImmutableList.Builder<LocalProperty<Symbol>> localPropertiesBuilder = ImmutableList.builder(); localPropertiesBuilder.addAll(properties.getLocalProperties()); <START> localPropertiesBuilder.add(new GroupingProperty<>(ImmutableSet.of(node.getIdColumn()))); <END> if (properties.getNodePartitioning().isPresent()) { return ActualProperties.builderFrom(properties) .local(localPropertiesBuilder.build()) .build(); } return ActualProperties.builderFrom(properties) .global(partitionedOn(ARBITRARY_DISTRIBUTION, ImmutableList.of(node.getIdColumn()), Optional.empty())) .local(localPropertiesBuilder.build()) .build(); }</code><technical_language>I stronger statement grouped columns, no</technical_language>

Target:
public ActualProperties visitAssignUniqueId(AssignUniqueId node, List<ActualProperties> inputProperties) { ActualProperties properties = Iterables.getOnlyElement(inputProperties); ImmutableList.Builder<LocalProperty<Symbol>> newLocalProperties = ImmutableList.builder(); newLocalProperties.addAll(properties.getLocalProperties()); newLocalProperties.add(new GroupingProperty<>(ImmutableList.of(node.getIdColumn()))); node.getSource().getOutputSymbols().stream() .forEach(column -> newLocalProperties.add(new ConstantProperty<>(column))); if (properties.getNodePartitioning().isPresent()) { return ActualProperties.builderFrom(properties) .local(newLocalProperties.build()) .build(); } return ActualProperties.builderFrom(properties) .global(partitionedOn(ARBITRARY_DISTRIBUTION, ImmutableList.of(node.getIdColumn()), Optional.empty())) .local(newLocalProperties.build()) .build(); }
Source:
<code>private void populateColumns(JsonNode propertiesNode, List<String> arrays, List<ElasticsearchColumn> columns) <START> throws IOException <END> { Comparator<String> stringComparator = (key1, key2) -> { int length1 = key1.split("\\.").length; int length2 = key2.split("\\.").length; if (length1 == length2) { return key1.compareTo(key2); } return length2 - length1; }; TreeMap<String, Type> fieldsMap = new TreeMap<>(stringComparator); for (String columnMetadata : getColumnsMetadata(null, propertiesNode)) { int delimiterIndex = columnMetadata.lastIndexOf(":"); if (delimiterIndex == -1 || delimiterIndex == columnMetadata.length() - 1) { LOG.debug("Invalid column path format: " + columnMetadata); continue; } String fieldName = columnMetadata.substring(0, delimiterIndex); String typeName = columnMetadata.substring(delimiterIndex + 1); if (!fieldName.endsWith(".type")) { LOG.debug("Ignoring column with no type info: " + columnMetadata); continue; } String propertyName = fieldName.substring(0, fieldName.lastIndexOf('.')); String nestedName = propertyName.replaceAll("properties\\.", ""); if (nestedName.contains(".")) { fieldsMap.put(nestedName, getPrestoType(typeName)); } else { boolean newNestedColumn = columns.stream().noneMatch(column -> column.getName().equalsIgnoreCase(nestedName)); if (newNestedColumn) { columns.add(new ElasticsearchColumn(nestedName, getPrestoType(typeName), nestedName, typeName, arrays.contains(nestedName), -1)); } } } processNestedFields(fieldsMap, columns, arrays); }</code><technical_language>IOException is thrown in this method</technical_language>

Target:
private void populateColumns(JsonNode propertiesNode, List<String> arrays, List<ElasticsearchColumn> columns) { Comparator<String> stringComparator = (key1, key2) -> { int length1 = key1.split("\\.").length; int length2 = key2.split("\\.").length; if (length1 == length2) { return key1.compareTo(key2); } return length2 - length1; }; TreeMap<String, Type> fieldsMap = new TreeMap<>(stringComparator); for (String columnMetadata : getColumnMetadata(null, propertiesNode)) { int delimiterIndex = columnMetadata.lastIndexOf(":"); if (delimiterIndex == -1 || delimiterIndex == columnMetadata.length() - 1) { LOG.debug("Invalid column path format: %s", columnMetadata); continue; } String fieldName = columnMetadata.substring(0, delimiterIndex); String typeName = columnMetadata.substring(delimiterIndex + 1); if (!fieldName.endsWith(".type")) { LOG.debug("Ignoring column with no type info: %s", columnMetadata); continue; } String propertyName = fieldName.substring(0, fieldName.lastIndexOf('.')); String nestedName = propertyName.replaceAll("properties\\.", ""); if (nestedName.contains(".")) { fieldsMap.put(nestedName, getPrestoType(typeName)); } else { boolean newNestedColumn = columns.stream() .noneMatch(column -> column.getName().equalsIgnoreCase(nestedName)); if (newNestedColumn) { columns.add(new ElasticsearchColumn(nestedName, getPrestoType(typeName), nestedName, typeName, arrays.contains(nestedName), -1)); } } } processNestedFields(fieldsMap, columns, arrays); }
Source:
<code>private Set<Resource> getSessionResources(boolean includeMainResource) { List<Resource> result = Lists.newArrayList(); for (DAnalysis analysis : allAnalyses()) { Resource res = analysis.eResource(); if (res != null && <START> (analysis != sessionResource || includeMainResource)) <END> { result.add(res); } } return ImmutableSet.copyOf(result); }</code><technical_language>I put includeMainResource || analysis != sessionResource</technical_language>

Target:
private Set<Resource> getSessionResources(boolean includeMainResource) { List<Resource> result = Lists.newArrayList(); for (DAnalysis analysis : allAnalyses()) { Resource res = analysis.eResource(); if (res != null && (includeMainResource || analysis != sessionResource)) { result.add(res); } } return ImmutableSet.copyOf(result); }
Source:
<code>public void activate(final BundleContext bundleContext, final Map<String, Object> configuration) { this.bundleContext = bundleContext; String refreshIntervalString = (String) configuration.get("refresh"); if (StringUtils.isNotBlank(refreshIntervalString)) { refreshInterval = Long.parseLong(refreshIntervalString); } String pollingIntervalString = (String) configuration.get("polling"); if (StringUtils.isNotBlank(pollingIntervalString)) { pollingInterval = Integer.parseInt(pollingIntervalString); } <START> logger.debug("mcp23017 activated " + this.hashCode()); <END> setProperlyConfigured(true); logger.debug("mcp23017 activated and ProperlyConfigured " + this.hashCode()); }</code><technical_language>parameterized logging instead of string concatenation</technical_language>

Target:
public void activate(final BundleContext bundleContext, final Map<String, Object> configuration) { this.bundleContext = bundleContext; String refreshIntervalString = (String) configuration.get("refresh"); if (StringUtils.isNotBlank(refreshIntervalString)) { refreshInterval = Long.parseLong(refreshIntervalString); } String pollingIntervalString = (String) configuration.get("polling"); if (StringUtils.isNotBlank(pollingIntervalString)) { pollingInterval = Integer.parseInt(pollingIntervalString); } setProperlyConfigured(true); logger.debug("mcp23017 activated and properly configured {}", this.hashCode()); }
Source:
<code>public Object apply(RevisionResource rsrc) throws <START> AuthException, BadRequestException, ResourceConflictException, Exception { <END> return Response.withMustRevalidate(delegate.get().format(rsrc)); }</code><technical_language>exceptions unsed. "Exception" is in real code, in unit tests</technical_language>

Target:
public Object apply(RevisionResource rsrc) { return Response.withMustRevalidate(delegate.format(rsrc)); }
Source:
<code>private String saveTempFile(InputStream input) { if (input == null) { return null; } byte[] buffer = new byte[8192]; int bytesRead = 0; File labelsFile = null; FileOutputStream output = null; try { labelsFile = File.createTempFile("tempIngestLabels.", ".txt"); output = new FileOutputStream(labelsFile); while ((bytesRead = input.read(buffer)) > -1) { output.write(buffer, 0, bytesRead); } } catch (IOException ioex) { if (input != null) { try { input.close(); } catch (IOException e) { } } if (output != null) { try { output.close(); } catch (IOException e) { } } return null; <START> } finally <END> { if(null!=output) { try{ output.close(); }catch(IOException ic){} } } if (labelsFile != null) { return labelsFile.getAbsolutePath(); } return null; }</code><technical_language>this finally block partially duplicates in catch... close in finally</technical_language>

Target:
private String saveTempFile(InputStream input) { if (input == null) { return null; } byte[] buffer = new byte[8192]; int bytesRead = 0; File labelsFile = null; FileOutputStream output = null; try { labelsFile = File.createTempFile("tempIngestLabels.", ".txt"); output = new FileOutputStream(labelsFile); while ((bytesRead = input.read(buffer)) > -1) { output.write(buffer, 0, bytesRead); } } catch (IOException ioex) { return null; } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } if (labelsFile != null) { return labelsFile.getAbsolutePath(); } return null; }
Source:
<code>public void sendPinResetConfirmationCode(UUID userId) { <START> User user = userService.lockUserForUpdate(userId); <END> logger.info("Generating pin reset confirmation code for user with mobile number '{}' and ID '{}'", user.getMobileNumber(), user.getId()); ConfirmationCode pinResetConfirmationCode = user.getPinResetConfirmationCode(); pinResetConfirmationCode.setCode(userService.generateConfirmationCode()); sendConfirmationCodeTextMessage(user, pinResetConfirmationCode); }</code><technical_language>I get it. this silently proceed user is removed</technical_language>

Target:
public void sendPinResetConfirmationCode(UUID userId) { userService.updateUserIfExisting(userId, this::sendPinResetConfirmationCode); }
Source:
<code>private void reset() { <START> LogManager.resetConfiguration(); PropertyConfigurator.configure(getClass().getClassLoader().getResource( LOG_CONFIGURATION)); <END> }</code><technical_language>I is a bit of a race condition here. If config is reset a log configuration is loaded, unexpected behavior occur</technical_language>

Target:
private static void reset() throws MalformedURLException { for (Enumeration<Logger> logger = LogManager.getCurrentLoggers(); logger.hasMoreElements();) { Logger log = logger.nextElement(); log.setLevel(null); } if (Strings.isNullOrEmpty(System.getProperty(JAVA_OPTIONS_LOG_CONFIG))) { PropertyConfigurator.configure(Loader.getResource(LOG_CONFIGURATION)); } else { PropertyConfigurator.configure( new URL(System.getProperty(JAVA_OPTIONS_LOG_CONFIG))); } }
Source:
<code>Part(Method method, int p, Headers headers, Converter<T, RequestBody> converter) { this.headers = headers; this.converter = converter; this.method = method; <START> this.p = p; <END> }</code><technical_language>field order statement order match constructor argument order</technical_language>

Target:
Part(Method method, int p, Headers headers, Converter<T, RequestBody> converter) { this.method = method; this.p = p; this.headers = headers; this.converter = converter; }
Source:
<code>protected Configuration readConfiguration(ServletContext context) throws ConfigurationException { Charset utf8 = Charset.forName("UTF-8"); PropertiesFileConfiguration systemConfig = new PropertiesFileConfiguration(); systemConfig.setEncoding(utf8); File configFile = new File(ConfigProperties.DEFAULT_CONFIG_FILE); if (configFile.canRead()) { log.debug("Loading system configuration"); systemConfig.load(configFile); log.debug("System configuration: " + systemConfig); } MapConfiguration defaults = new MapConfiguration( ConfigProperties.DEFAULT_PROPERTIES); log.debug("Loading default configuration values"); <START> return systemConfig.merge(defaults); <END> }</code><technical_language>merge a static method implementation classes? java public static Configuration merge(Configuration ... configs) { MapConfiguration mergedConfig = new MapConfiguration(); for (Configuration c : configs) { for (String key : c.getKeys()) { if (!mergedConfig.containsKey(key)) { mergedConfig.setProperty(key, c.getProperty(key)); } } } return mergedConfig; } configuration trumped it</technical_language>

Target:
protected Configuration readConfiguration(ServletContext context) throws ConfigurationException { Charset utf8 = Charset.forName("UTF-8"); PropertiesFileConfiguration systemConfig = new PropertiesFileConfiguration(); systemConfig.setEncoding(utf8); File configFile = new File(ConfigProperties.DEFAULT_CONFIG_FILE); if (configFile.canRead()) { log.debug("Loading system configuration"); systemConfig.load(configFile); log.debug("System configuration: " + systemConfig); } MapConfiguration defaults = new MapConfiguration( ConfigProperties.DEFAULT_PROPERTIES); log.debug("Loading default configuration values"); return PropertiesFileConfiguration.merge(systemConfig, defaults); }
Source:
<code>protected void addListeners() { this.addListener(new InputListener() { @Override public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) { if (doTouchDown(x, y, pointer)) { return true; } setTouchable(Touchable.disabled); Actor target = getParent().hit(event.getStageX(), event.getStageY(), true); if (target != null) { target.fire(event); } setTouchable(Touchable.enabled); return false; } }); this.addListener(new BroadcastListener() { @Override public void handleBroadcastEvent(BroadcastEvent event, String broadcastMessage) { <START> doHandleBroadcastEvent(event, broadcastMessage); <END> } @Override public void handleBroadcastFromWaiterEvent(BroadcastEvent event, String broadcastMessage) { doHandleBroadcastFromWaiterEvent(event, broadcastMessage); } }); }</code><technical_language>event is handed a functions for map (event.getSenderSprite().getBroadcastWaitSequenceMap()) pass map through</technical_language>

Target:
protected void addListeners() { this.addListener(new InputListener() { @Override public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) { if (doTouchDown(x, y, pointer)) { return true; } setTouchable(Touchable.disabled); Actor target = getParent().hit(event.getStageX(), event.getStageY(), true); if (target != null) { target.fire(event); } setTouchable(Touchable.enabled); return false; } }); this.addListener(new BroadcastListener() { @Override public void handleBroadcastEvent(BroadcastEvent event, String broadcastMessage) { doHandleBroadcastEvent(event.getSenderSprite(), broadcastMessage); } @Override public void handleBroadcastFromWaiterEvent(BroadcastEvent event, String broadcastMessage) { doHandleBroadcastFromWaiterEvent(event, broadcastMessage); } }); }
Source:
<code>public boolean equals(Object otherCohortMembershipObject) { <START> if(!(otherCohortMembershipObject instanceof CohortMembership)){ <END> return false; } CohortMembership otherCohortMembership = (CohortMembership)otherCohortMembershipObject; if(this == otherCohortMembership) return true; return otherCohortMembership != null && ((endDate != null ) ? endDate.equals(otherCohortMembership.getEndDate()) : otherCohortMembership.getEndDate() == null) && ((startDate !=null) ? startDate.equals(otherCohortMembership.getStartDate()) : otherCohortMembership.getStartDate() == null) && ((patientId != null) ? patientId.equals(otherCohortMembership.getPatientId()) : otherCohortMembership.getPatientId() == null); }</code><technical_language>cheaper for otherCohortMembership != null check checked early return statement</technical_language>

Target:
public boolean equals(Object otherCohortMembershipObject) { if(otherCohortMembershipObject == null || !(otherCohortMembershipObject instanceof CohortMembership)){ return false; } CohortMembership otherCohortMembership = (CohortMembership)otherCohortMembershipObject; if(this == otherCohortMembership) return true; return ((endDate != null ) ? endDate.equals(otherCohortMembership.getEndDate()) : otherCohortMembership.getEndDate() == null) && ((startDate !=null) ? startDate.equals(otherCohortMembership.getStartDate()) : otherCohortMembership.getStartDate() == null) && ((patientId != null) ? patientId.equals(otherCohortMembership.getPatientId()) : otherCohortMembership.getPatientId() == null); }
Source:
<code>public List<String> remoteStyles() { try { <START> List<String> remoteStyles = new ArrayList<String>(); <END> remoteStyles.add(""); remoteStyles.addAll( getWMSLayer(null) .getStyles() .stream() .map(s -> s.getName()) .collect(Collectors.toList())); return remoteStyles; } catch (Exception e) { LOGGER.log( Level.SEVERE, "Unable to fetch styles for cascaded wms layer " + getNativeName()); LOGGER.log(Level.SEVERE, e.getMessage(), e); throw new RuntimeException(e); } }</code><technical_language>This change unrelated, mixup other work? This explain current conflicts, please clean :)</technical_language>

Target:
public List<String> remoteStyles() { try { return allAvailableRemoteStyles .stream() .map(s -> s.getName()) .collect(Collectors.toList()); } catch (Exception e) { LOGGER.log( Level.SEVERE, "Unable to fetch styles for cascaded wms layer " + getNativeName()); LOGGER.log(Level.SEVERE, e.getMessage(), e); throw new RuntimeException(e); } }
Source:
<code>public void emitTuples() { int fileCt = 0; while ((!fileQueue.isEmpty()) && (fileCt < MAX_FILE_PER_WINDOW)) { Path newPath = fileQueue.peek(); String newPathString = newPath.toString(); <START> pendingFiles.add(newPathString); <END> synchronized (processedFiles.getClass()) { processedFiles.add(newPathString); } localProcessedFileCount.increment(); fileQueue.remove(); fileCt++; } super.emitTuples(); }</code><technical_language>I pending file is required fileQueue list of pending files</technical_language>

Target:
public void emitTuples() { while ((!fileQueue.isEmpty()) && (fileCount < getMaxFilesPerWindow())) { Path newPath = fileQueue.peek(); String newPathString = newPath.toString(); pendingFiles.add(newPathString); synchronized (processedFiles.getClass()) { processedFiles.add(newPathString); } localProcessedFileCount.increment(); fileQueue.remove(); fileCount++; } super.emitTuples(); }
Source:
<code>public Saga execute(Saga saga) { Saga nextSaga = saga; Object nextVal; String chapterName = saga.getCurrent().getName(); if (chapterName.equals(getName())) { if (saga.isForward()) { nextSaga = process(saga); nextVal = nextSaga.getCurrentValue(); if (nextSaga.isCurrentSuccess()) { nextSaga.forward(); } else { nextSaga.back(); } } else { nextSaga = rollback(saga); nextVal = nextSaga.getCurrentValue(); nextSaga.back(); } if (isSagaFinished(nextSaga)) { return nextSaga; } nextSaga.setCurrentValue(nextVal); } Saga finalNextSaga = nextSaga; return sd.find(chapterName).map(ch -> ch.execute(finalNextSaga)) <START> .orElseThrow(RuntimeException::new); <END> }</code><technical_language>nice some sort of description in RuntimeException i.e. "could execute saga"</technical_language>

Target:
public Saga execute(Saga saga) { Saga nextSaga = saga; Object nextVal; String chapterName = saga.getCurrent().getName(); if (chapterName.equals(getName())) { if (saga.isForward()) { nextSaga = process(saga); nextVal = nextSaga.getCurrentValue(); if (nextSaga.isCurrentSuccess()) { nextSaga.forward(); } else { nextSaga.back(); } } else { nextSaga = rollback(saga); nextVal = nextSaga.getCurrentValue(); nextSaga.back(); } if (isSagaFinished(nextSaga)) { return nextSaga; } nextSaga.setCurrentValue(nextVal); } Saga finalNextSaga = nextSaga; return sd.find(chapterName).map(ch -> ch.execute(finalNextSaga)) .orElseThrow(serviceNotFoundException(chapterName)); }
Source:
<code>private IAction createFlatAction() { IAction action = new Action(Messages.ControlFlowView_flatViewLabel, IAction.AS_RADIO_BUTTON) { @Override public void run() { if (fIsFlatList) { swapBetweenFlatViewOrHierarchicalView(); fIsFlatList = false; } } }; action.setToolTipText(Messages.ControlFlowView_flatViewToolTip); <START> action.setImageDescriptor(Activator.getDefault().getImageDescripterFromPath(IControlflowImageConstants.IMG_UI_FLAT_VIEW)); <END> return action; }</code><technical_language>windows</technical_language>

Target:
private IAction createFlatAction() { IAction action = new Action(Messages.ControlFlowView_flatViewLabel, IAction.AS_RADIO_BUTTON) { @Override public void run() { if (!fIsFlatViewClicked) { switchView(fFlatList); fIsFlatViewClicked = true; } } }; return action; }
Source:
<code><START> public void onRTPSessionCreate(RTPSession rtpSession) <END> { String queryStr = rtpSession.getQueryStr(); String uriStr = rtpSession.getUri(); try { HashMap<String, String> queryParameters = Utils.getRtmpUrlParameters(uriStr, queryStr); onClientConnect(rtpSession.getProperties(), queryParameters); } catch (Exception e) { logger.error("Entry authentication failed with url [" + uriStr + "]: " + e.getMessage()); rtpSession.rejectSession(); DiagnosticsProvider.addRejectedStreamFromRTSP(e.getMessage(), rtpSession); } }</code><technical_language>Please add spacing functions. improves reading of file</technical_language>

Target:
public void onRTPSessionCreate(RTPSession rtpSession) { String queryStr = rtpSession.getQueryStr(); String uriStr = rtpSession.getUri(); try { WMSProperties properties = rtpSession.getProperties(); HashMap<String, String> queryParameters = Utils.getRtmpUrlParameters(uriStr, queryStr); if (queryParameters.containsKey(Constants.REQUEST_PROPERTY_ENTRY_ID)) { logger.debug("onRTPSessionCreate - [" + queryParameters.get(Constants.REQUEST_PROPERTY_ENTRY_ID) + "]"); } onClientConnect(properties, queryParameters); } catch (Exception e) { logger.error("Entry authentication failed with url [" + uriStr + "]: " + e.getMessage()); appInstance.getVHost().getRTPContext().shutdownRTPSession(rtpSession); DiagnosticsProvider.addRejectedRTSPStream(rtpSession, e.getMessage()); } }
Source:
<code>public void addEvent(IEventDeclaration event) throws ParseException { if (fEventUnsetId) { throw new ParseException("Event without id with multiple events in a stream"); } int id = ((EventDeclaration) event).id(); if (id == EventDeclaration.UNSET_EVENT_ID) { if (!fEvents.isEmpty()) { throw new ParseException("Event without id with multiple events in a stream"); } fEventUnsetId = true; <START> fEvents = ImmutableList.<IEventDeclaration> of(event); <END> } else { List<IEventDeclaration> eventsList = new ArrayList<>(); eventsList.addAll(fEvents); if (eventsList.size() > id && eventsList.get(id) != UNASSIGNED) { throw new ParseException("Event id already exists"); } while (eventsList.size() <= id) { eventsList.add(UNASSIGNED); } if (eventsList.get(id) == UNASSIGNED) { eventsList.set(id, event); } else { eventsList.add(event); } fEvents = ImmutableList.copyOf(eventsList); } }</code><technical_language>care, SingletonList sounds here</technical_language>

Target:
public void addEvent(IEventDeclaration event) throws ParseException { if (fEventUnsetId) { throw new ParseException("Event without id with multiple events in a stream"); } int id = ((EventDeclaration) event).id(); if (id == EventDeclaration.UNSET_EVENT_ID) { if (!fEvents.isEmpty()) { throw new ParseException("Event without id with multiple events in a stream"); } fEventUnsetId = true; fEvents = Collections.singletonList(event); } else { if (fEvents.equals(Collections.EMPTY_LIST)) { fEvents = new ArrayList<>(); } if (fEvents.size() > id && fEvents.get(id) != null) { throw new ParseException("Event id already exists"); } while (fEvents.size() <= id) { fEvents.add(null); } fEvents.set(id, event); } }
Source:
<code>public Response refreshLuns(Action action) { QueryIdResolver<Guid> storageDomainResolver = new QueryIdResolver<Guid>(VdcQueryType.GetStorageDomainById, IdQueryParameters.class); org.ovirt.engine.core.common.businessentities.StorageDomain entity = getEntity(storageDomainResolver, true); <START> StorageDomain model = map(entity, new StorageDomain()); <END> StorageType storageType = entity.getStorageType(); if (storageType != null) { switch (storageType) { case ISCSI: case FCP: refreshLunSize(action); break; default: break; } } return Response.ok().entity(model).build(); }</code><technical_language>I suggest get() instead of lines</technical_language>

Target:
public Response refreshLuns(Action action) { StorageDomain model = get(); org.ovirt.engine.api.model.StorageType storageType = org.ovirt.engine.api.model.StorageType.fromValue(model.getStorage().getType()); if (storageType != null) { switch (storageType) { case ISCSI: case FCP: refreshLunSize(action); break; default: break; } } return Response.ok().entity(model).build(); }
Source:
<code>private VmPropertiesUtils mockVmPropertiesUtils() throws InitializationException { VmPropertiesUtils utils = spy(new VmPropertiesUtils()); doReturn("sap_agent=^(true|false)$;sndbuf=^[0-9]+$;" + "vhost=^(([a-zA-Z0-9_]*):(true|false))(,(([a-zA-Z0-9_]*):(true|false)))*$;" + <START> "viodiskcache=^(none|writeback|writethrough)$" + <END> "mdev_type=^.*$"). when(utils) .getPredefinedVMProperties(any(Version.class)); doReturn(""). when(utils) .getUserdefinedVMProperties(any(Version.class)); doReturn(new HashSet<>(Arrays.asList(Version.v3_6, Version.v4_0))). when(utils) .getSupportedClusterLevels(); doReturn(utils).when(runVmValidator).getVmPropertiesUtils(); utils.init(); return utils; }</code><technical_language>missing semicolon</technical_language>

Target:
private VmPropertiesUtils mockVmPropertiesUtils() throws InitializationException { VmPropertiesUtils utils = spy(new VmPropertiesUtils()); doReturn("sap_agent=^(true|false)$;sndbuf=^[0-9]+$;" + "vhost=^(([a-zA-Z0-9_]*):(true|false))(,(([a-zA-Z0-9_]*):(true|false)))*$;" + "viodiskcache=^(none|writeback|writethrough)$;" + "mdev_type=^.*$"). when(utils) .getPredefinedVMProperties(any(Version.class)); doReturn(""). when(utils) .getUserdefinedVMProperties(any(Version.class)); doReturn(new HashSet<>(Arrays.asList(Version.v3_6, Version.v4_0))). when(utils) .getSupportedClusterLevels(); doReturn(utils).when(runVmValidator).getVmPropertiesUtils(); utils.init(); return utils; }
Source:
<code>public final byte[] getUncompressedContent() { final byte[] uncompressedContent = ExternalCompression.uncompress(method, compressedContent); if (uncompressedContent.length != uncompressedLength) { throw new CRAMException(String.format("Block uncompressed length did not match expected length: %04x vs %04x", uncompressedLength, uncompressedContent.length)); } <START> return ExternalCompression.uncompress(method, compressedContent); <END> }</code><technical_language>uncompress calls (its called above)</technical_language>

Target:
public final byte[] getUncompressedContent() { final byte[] uncompressedContent = ExternalCompression.uncompress(compressionMethod, compressedContent); if (uncompressedContent.length != uncompressedLength) { throw new CRAMException(String.format("Block uncompressed length did not match expected length: %04x vs %04x", uncompressedLength, uncompressedContent.length)); } return uncompressedContent; }
Source:
<code>public PentahoWebPackageResource resolve( String moduleId ) { int index = 0; <START> boolean moduleIdStartsWithSlash = moduleId.indexOf( '/' ) == 0; <END> if ( moduleIdStartsWithSlash ) { ++index; } boolean moduleIdIncludesOrganization = moduleId.indexOf( '@', index ) - index == 0; if ( moduleIdIncludesOrganization ) { index = moduleId.indexOf( '/', index ) + 1; } index = moduleId.indexOf( '/', index ); String baseModuleId = moduleId.substring( moduleIdStartsWithSlash ? 1 : 0, index ); int versionSeparatorIndex = baseModuleId.lastIndexOf( '_' ); if ( versionSeparatorIndex == -1 ) { return null; } String packageName = baseModuleId.substring( 0, versionSeparatorIndex ); String packageVersion = baseModuleId.substring( versionSeparatorIndex + 1 ); PentahoWebPackage webPackage = findWebPackage( packageName, packageVersion ); if ( webPackage == null ) { return null; } String resourcePath = webPackage.getResourceRootPath() + "/" + moduleId.substring( index + 1 ); ClassLoader classLoader = webPackage.getBundle().adapt( BundleWiring.class ).getClassLoader(); return new PentahoWebPackageResourceImpl( resourcePath, classLoader ); }</code><technical_language>Module ids start a /. Idem for test cases below</technical_language>

Target:
public PentahoWebPackageResource resolve( String moduleId ) { int index = 0; boolean moduleIdIncludesOrganization = moduleId.indexOf( '@' ) == 0; if ( moduleIdIncludesOrganization ) { index = moduleId.indexOf( '/', 1 ) + 1; } index = moduleId.indexOf( '/', index ); String baseModuleId = moduleId.substring( 0, index ); int versionSeparatorIndex = baseModuleId.lastIndexOf( '_' ); if ( versionSeparatorIndex == -1 ) { return null; } String packageName = baseModuleId.substring( 0, versionSeparatorIndex ); String packageVersion = baseModuleId.substring( versionSeparatorIndex + 1 ); PentahoWebPackage webPackage = findWebPackage( packageName, packageVersion ); if ( webPackage == null ) { return null; } String resourcePath = webPackage.getResourceRootPath() + "/" + moduleId.substring( index + 1 ); ClassLoader classLoader = webPackage.getBundle().adapt( BundleWiring.class ).getClassLoader(); return new PentahoWebPackageResourceImpl( resourcePath, classLoader ); }
Source:
<code>private boolean addConnection() { if (totalConnections.incrementAndGet() > config.getMaximumPoolSize()) { totalConnections.decrementAndGet(); <START> LOGGER.debug("{} - Cannot exceed maximum connections capacity: {}", poolName, config.getMaximumPoolSize()); <END> return true; } try { final PoolEntry poolEntry = newPoolEntry(); connectionBag.add(poolEntry); final long maxLifetime = config.getMaxLifetime(); if (maxLifetime > 0) { final long variance = maxLifetime > 60_000 ? ThreadLocalRandom.current().nextLong(10_000) : 0; final long lifetime = maxLifetime - variance; poolEntry.setFutureEol(houseKeepingExecutorService.schedule(new Runnable() { @Override public void run() { softEvictConnection(poolEntry, "(connection reached maxLifetime)", false ); } }, lifetime, TimeUnit.MILLISECONDS)); } LOGGER.debug("{} - Added connection {}", poolName, poolEntry.connection); return true; } catch (Exception e) { totalConnections.decrementAndGet(); if (poolState == POOL_NORMAL) { LOGGER.debug("{} - Cannot acquire connection from data source", poolName, e); } return false; } }</code><technical_language>This is a fire hose of logs, tested it</technical_language>

Target:
private boolean addConnection() { if (totalConnections.incrementAndGet() > config.getMaximumPoolSize()) { totalConnections.decrementAndGet(); return true; } try { final PoolEntry poolEntry = newPoolEntry(); connectionBag.add(poolEntry); final long maxLifetime = config.getMaxLifetime(); if (maxLifetime > 0) { final long variance = maxLifetime > 60_000 ? ThreadLocalRandom.current().nextLong(10_000) : 0; final long lifetime = maxLifetime - variance; poolEntry.setFutureEol(houseKeepingExecutorService.schedule(new Runnable() { @Override public void run() { softEvictConnection(poolEntry, "(connection reached maxLifetime)", false ); } }, lifetime, TimeUnit.MILLISECONDS)); } LOGGER.debug("{} - Added connection {}", poolName, poolEntry.connection); return true; } catch (Exception e) { totalConnections.decrementAndGet(); if (poolState == POOL_NORMAL) { LOGGER.debug("{} - Cannot acquire connection from data source", poolName, e); } return false; } }
Source:
<code>public ArrayList<Person> getTechs(boolean noZeroMinute, UUID firstTechId, boolean sorted, boolean eliteFirst) { ArrayList<Person> techs = new ArrayList<>(); Person firstTech = getPerson(firstTechId); if ((firstTech != null) && firstTech.isTech() && firstTech.isActive() && (!noZeroMinute || firstTech.getMinutesLeft() > 0)) { techs.add(firstTech); } for (Person p : getPersonnel()) { if (p.isTech() && p.isActive() && (!p.equals(firstTech)) && (!noZeroMinute || (p.getMinutesLeft() > 0))) { techs.add(p); } } for(Unit u : getUnits()) { if(u.isSelfCrewed() && !(u.getEntity() instanceof Infantry) && null != u.getEngineer()) { techs.add(u.getEngineer()); } } if (sorted) { Collections.sort(techs, new Comparator<Person>() { @Override public int compare(Person person1, Person person2) { <START> int retVal = person1.getExperienceLevel(!person1.isTechPrimary() && person1.isTechSecondary()) <END> > person2.getExperienceLevel(!person2.isTechPrimary() && person2.isTechSecondary()) ? -1 : (person1.getExperienceLevel(!person1.isTechPrimary() && person1.isTechSecondary()) < person2.getExperienceLevel(!person2.isTechPrimary() && person2.isTechSecondary())) ? 1 : 0; return eliteFirst ? retVal *= -1 : retVal; } }); } return techs; }</code><technical_language>I complex ternary expressions next guy, this is pretty unreadable. untangle it</technical_language>

Target:
public ArrayList<Person> getTechs(boolean noZeroMinute, UUID firstTechId, boolean sorted, boolean eliteFirst) { ArrayList<Person> techs = new ArrayList<>(); Person firstTech = getPerson(firstTechId); if ((firstTech != null) && firstTech.isTech() && firstTech.isActive() && (!noZeroMinute || firstTech.getMinutesLeft() > 0)) { techs.add(firstTech); } for (Person p : getPersonnel()) { if (p.isTech() && p.isActive() && (!p.equals(firstTech)) && (!noZeroMinute || (p.getMinutesLeft() > 0))) { techs.add(p); } } for(Unit u : getUnits()) { if(u.isSelfCrewed() && !(u.getEntity() instanceof Infantry) && null != u.getEngineer()) { techs.add(u.getEngineer()); } } if (sorted) { Collections.sort(techs, new Comparator<Person>() { @Override public int compare(Person person1, Person person2) { int retVal = 0; boolean p1Secondary = !person1.isTechPrimary() && person1.isTechSecondary(); boolean p2Secondary = !person2.isTechPrimary() && person2.isTechSecondary(); if (person1.getExperienceLevel(p1Secondary) > person2.getExperienceLevel(p2Secondary)) { retVal = -1; } else if (person1.getExperienceLevel(p1Secondary) < person2.getExperienceLevel(p2Secondary)) { retVal = 1; } return eliteFirst ? retVal *= -1 : retVal; } }); } return techs; }
Source:
<code>protected boolean validateFieldValue(FormField field, Object value) { if (field.isRequired()) { return validateFieldValueRequired(field, value); } for(CustomFieldValidator validator : field.getCustomValidators()) { ValidationResult result = validator.validate(value); <START> if(result.getStatus().hasMessage()) { <END> if(!result.getStatus().isValid()) { field.showError(result.getMessage()); return false; } else { field.showWarning(result.getMessage()); } } } return true; }</code><technical_language>suggestion if (result.getStatus().hasMessage()) {</technical_language>

Target:
protected boolean validateFieldValue(FormField field, Object value) { if (field.isRequired()) { if (!validateFieldValueRequired(field, value)) { return false; } } for (CustomFieldValidator validator : field.getCustomValidators()) { ValidationResult result = validator.validate(value); if (result.getStatus().hasMessage()) { if (!result.getStatus().isValid()) { field.showError(result.getMessage()); return false; } else { field.showWarning(result.getMessage()); } } } return true; }
Source:
<code>private boolean matchesAnIgnoredFieldType(DualValue dualKey) { <START> return ignoredFieldsForTypes.contains(dualKey.actual.getClass()); <END> }</code><technical_language>dualKey.actual null, in case a bit tricky, dualKey.expected compare objects of types (ex: Person PersonDto) this relevant. Options dualKey.actual is null: * return false (don't ignore evaluate type) * evaluate dualKey.expected instead assuming actual expected (not true) * ? thoughts</technical_language>

Target:
private boolean matchesAnIgnoredFieldType(DualValue dualKey) { if (dualKey.actual == null) { return false; } return ignoredTypes.contains(dualKey.actual.getClass()); }