auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public boolean verifyEventIdentifier(AbstractPlaceEvent event) { boolean equals = Objects.equals(getEditorIdentifier(), event.getPlace().getIdentifier()); boolean equals1 = Objects.equals(editorPlaceRequest, event.getPlace()); return (equals && <START> equals1); <END> }</code><technical_language>Toni, please choose variable names here? equals equals1 do for newcomer codebase. avoid storing partial results by: java if(!Objects.equals(editorPlaceRequest, event.getPlace())) { return false; } if (!Objects.equals(getEditorIdentifier(), event.getPlace().getIdentifier())) { return false; } return true; Please do think</technical_language>

Target:
public boolean verifyEventIdentifier(AbstractPlaceEvent event) { return (Objects.equals(getEditorIdentifier(), event.getPlace().getIdentifier()) && Objects.equals(editorPlaceRequest, event.getPlace())); }
Source:
<code>public int hashCode() { <START> return fFieldName.hashCode(); <END> }</code><technical_language>consider label well</technical_language>

Target:
public int hashCode() { return Objects.hash(fFieldName, fLabel); }
Source:
<code>public void createOrUpdateObjectFromJson_primaryKey_isNull_updateFromJsonObject() throws JSONException { if (clazz.equals(PrimaryKeyAsString.class)) { realm.beginTransaction(); realm.createObject(clazz, null); realm.createOrUpdateObjectFromJson(clazz, new JSONObject(jsonString)); realm.commitTransaction(); <START> <END> RealmResults<PrimaryKeyAsString> results = realm.where(PrimaryKeyAsString.class).findAll(); assertEquals(1, results.size()); assertEquals(Long.valueOf(secondaryFieldValue).longValue(), results.first().getId()); assertEquals(null, results.first().getName()); } else { realm.beginTransaction(); realm.createObject(clazz, null); realm.createOrUpdateObjectFromJson(clazz, new JSONObject(jsonString)); realm.commitTransaction(); RealmResults results = realm.where(clazz).findAll(); assertEquals(1, results.size()); assertEquals(null, ((NullPrimaryKey)results.first()).getId()); assertEquals(secondaryFieldValue, ((NullPrimaryKey)results.first()).getName()); } }</code><technical_language>do lines in if else</technical_language>

Target:
public void createOrUpdateObjectFromJson_primaryKey_isNull_updateFromJsonObject() throws JSONException { realm.beginTransaction(); realm.createObject(clazz, null); realm.createOrUpdateObjectFromJson(clazz, new JSONObject(jsonString)); realm.commitTransaction(); if (clazz.equals(PrimaryKeyAsString.class)) { RealmResults<PrimaryKeyAsString> results = realm.where(PrimaryKeyAsString.class).findAll(); assertEquals(1, results.size()); assertEquals(Long.valueOf(secondaryFieldValue).longValue(), results.first().getId()); assertEquals(null, results.first().getName()); } else { RealmResults results = realm.where(clazz).findAll(); assertEquals(1, results.size()); assertEquals(null, ((NullPrimaryKey)results.first()).getId()); assertEquals(secondaryFieldValue, ((NullPrimaryKey)results.first()).getName()); } }
Source:
<code>private List<String> getVdsIps(VDS vds) { List<String> vdsIps = new ArrayList<String>(); for (VdsNetworkInterface iface : getInterfaceDao().getAllInterfacesForVds(vds.getId())) { <START> vdsIps.add(iface.getAddress()); <END> } return vdsIps; }</code><technical_language>iface.getAddress() null, list include null element. result a false positive in comparison (in fetchServers) list filtered out null elements</technical_language>

Target:
private List<String> getVdsIps(VDS vds) { List<String> vdsIps = new ArrayList<String>(); for (VdsNetworkInterface iface : getInterfaceDao().getAllInterfacesForVds(vds.getId())) { if (iface.getAddress() != null) { vdsIps.add(iface.getAddress()); } } return vdsIps; }
Source:
<code>public static Optional<Formatter> getFormatterForModifier(String modifier) { Objects.requireNonNull(modifier); switch (modifier) { case "lower": return Optional.of(new LowerCaseFormatter()); case "upper": return Optional.of(new UpperCaseFormatter()); case "capitalize": return Optional.of(new CapitalizeFormatter()); case "titlecase": return Optional.of(new TitleCaseFormatter()); case "sentencecase": return Optional.of(new SentenceCaseFormatter()); } if (modifier.startsWith(RegexFormatter.KEY)) { String regex = modifier.substring(RegexFormatter.KEY.length()); return Optional.of(new RegexFormatter(regex)); <START> } else if (modifier.matches(TruncateFormatter.KEY + "\\d+")) { <END> int truncateAfter = Integer.parseInt(modifier.substring(TruncateFormatter.KEY.length())); return Optional.of(new TruncateFormatter(truncateAfter)); } else { return getAll().stream().filter(f -> f.getKey().equals(modifier)).findAny(); } }</code><technical_language>I sense extract this a Pattern call compile <LINK_0></technical_language>

Target:
public static Optional<Formatter> getFormatterForModifier(String modifier) { Objects.requireNonNull(modifier); switch (modifier) { case "lower": return Optional.of(new LowerCaseFormatter()); case "upper": return Optional.of(new UpperCaseFormatter()); case "capitalize": return Optional.of(new CapitalizeFormatter()); case "titlecase": return Optional.of(new TitleCaseFormatter()); case "sentencecase": return Optional.of(new SentenceCaseFormatter()); } if (modifier.startsWith(RegexFormatter.KEY)) { String regex = modifier.substring(RegexFormatter.KEY.length()); return Optional.of(new RegexFormatter(regex)); } else if (TRUNCATE_PATTERN.matcher(modifier).matches()) { int truncateAfter = Integer.parseInt(modifier.substring(8)); return Optional.of(new TruncateFormatter(truncateAfter)); } else { return getAll().stream().filter(f -> f.getKey().equals(modifier)).findAny(); } }
Source:
<code>@Test public void testCorrelateQuery() { final FrameworkConfig config = RelBuilderTest.config().build(); final RelBuilder builder = RelBuilder.create(config); final Holder<RexCorrelVariable> v = Holder.of(null); RelNode relNode = builder.scan("EMP") .variable(v) .scan("DEPT") .filter( builder.equals(builder.field(0), builder.field(v.get(), "DEPTNO"))) .correlate( JoinRelType.INNER, v.get().id, builder.field(2, 0, "DEPTNO")) .build(); RelJsonWriter jsonWriter = new RelJsonWriter(); relNode.explain(jsonWriter); final String relJson = jsonWriter.asString(); <START> String s = deserializeAndDumpToTextFormat(getSchema(relNode), relJson, SqlExplainFormat.TEXT); <END> final String expected = "" + "LogicalCorrelate(correlation=[$cor0], joinType=[inner], requiredColumns=[{7}])\n" + " LogicalTableScan(table=[[scott, EMP]])\n" + " LogicalFilter(condition=[=($0, $cor0.DEPTNO)])\n" + " LogicalTableScan(table=[[scott, DEPT]])\n"; assertThat(s, isLinux(expected)); }</code><technical_language>method name tells is dumping TEXT format..</technical_language>

Target:
@Test public void testCorrelateQuery() { final FrameworkConfig config = RelBuilderTest.config().build(); final RelBuilder builder = RelBuilder.create(config); final Holder<RexCorrelVariable> v = Holder.of(null); RelNode relNode = builder.scan("EMP") .variable(v) .scan("DEPT") .filter( builder.equals(builder.field(0), builder.field(v.get(), "DEPTNO"))) .correlate( JoinRelType.INNER, v.get().id, builder.field(2, 0, "DEPTNO")) .build(); RelJsonWriter jsonWriter = new RelJsonWriter(); relNode.explain(jsonWriter); final String relJson = jsonWriter.asString(); String s = deserializeAndDump(getSchema(relNode), relJson, SqlExplainFormat.TEXT); final String expected = "" + "LogicalCorrelate(correlation=[$cor0], joinType=[inner], requiredColumns=[{7}])\n" + " LogicalTableScan(table=[[scott, EMP]])\n" + " LogicalFilter(condition=[=($0, $cor0.DEPTNO)])\n" + " LogicalTableScan(table=[[scott, DEPT]])\n"; assertThat(s, isLinux(expected)); }
Source:
<code>IndexTuningConfig computeTuningConfig(List<Pair<QueryableIndex, DataSegment>> queryableIndexAndSegments) { if (!hasPartitionConfig(tuningConfig)) { final double avgRowsPerByte = queryableIndexAndSegments .stream() .mapToDouble(queryableIndexAndDataSegment -> { <START> final long numRows = queryableIndexAndDataSegment.lhs.getNumRows(); <END> final long size = queryableIndexAndDataSegment.rhs.getSize(); return numRows / (double) size; }) .average() .orElseThrow(() -> new ISE("Cannot find targetPartitionSize because the input segment is empty")); final int targetPartitionSize = (int) Math.round(avgRowsPerByte * targetCompactionSizeBytes); Preconditions.checkState(targetPartitionSize > 0, "Negative targetPartitionSize[%s]", targetPartitionSize); log.info( "Estimated targetPartitionSize[%d] = avgRowsPerByte[%f] * targetCompactionSizeBytes[%d]", targetPartitionSize, avgRowsPerByte, targetCompactionSizeBytes ); return (tuningConfig == null ? IndexTuningConfig.createDefault() : tuningConfig) .withTargetPartitionSize(targetPartitionSize); } else { return tuningConfig; } }</code><technical_language>this is average of averages, do average for (total num rows / total size)</technical_language>

Target:
IndexTuningConfig computeTuningConfig(List<Pair<QueryableIndex, DataSegment>> queryableIndexAndSegments) { if (!hasPartitionConfig(tuningConfig)) { final long nonNullTargetCompactionSizeBytes = Preconditions.checkNotNull( targetCompactionSizeBytes, "targetCompactionSizeBytes" ); final long totalNumRows = queryableIndexAndSegments .stream() .mapToLong(queryableIndexAndDataSegment -> queryableIndexAndDataSegment.lhs.getNumRows()) .sum(); final long totalSizeBytes = queryableIndexAndSegments .stream() .mapToLong(queryableIndexAndDataSegment -> queryableIndexAndDataSegment.rhs.getSize()) .sum(); if (totalSizeBytes == 0L) { throw new ISE("Total input segment size is 0 byte"); } final double avgRowsPerByte = totalNumRows / (double) totalSizeBytes; final int targetPartitionSize = Math.toIntExact(Math.round(avgRowsPerByte * nonNullTargetCompactionSizeBytes)); Preconditions.checkState(targetPartitionSize > 0, "Negative targetPartitionSize[%s]", targetPartitionSize); log.info( "Estimated targetPartitionSize[%d] = avgRowsPerByte[%f] * targetCompactionSizeBytes[%d]", targetPartitionSize, avgRowsPerByte, nonNullTargetCompactionSizeBytes ); return (tuningConfig == null ? IndexTuningConfig.createDefault() : tuningConfig) .withTargetPartitionSize(targetPartitionSize); } else { return tuningConfig; } }
Source:
<code><START> protected GarbageFreeScheduledReporter(MetricRegistry registry, <END> String name, MetricFilter filter, TimeUnit rateUnit, TimeUnit durationUnit, ScheduledExecutorService executor, boolean shutdownExecutorOnStop, Set<MetricAttribute> disabledMetricAttributes) { super(registry, name, filter, rateUnit, durationUnit, executor, shutdownExecutorOnStop, disabledMetricAttributes); init(registry, filter); }</code><technical_language>I enough this constructor implemented in GarbageFreeScheduledReporter. other constructors derived it. case, reporters built builders invoke detailed constructor. Another declare registry mirror final</technical_language>

Target:
protected GarbageFreeScheduledReporter(MetricRegistry registry, String name, MetricFilter filter, TimeUnit rateUnit, TimeUnit durationUnit, ScheduledExecutorService executor, boolean shutdownExecutorOnStop, Set<MetricAttribute> disabledMetricAttributes) { super(registry, name, filter, rateUnit, durationUnit, executor, shutdownExecutorOnStop, disabledMetricAttributes); this.registry = registry; this.mirror = new RegistryMirror(filter); registry.addListener(mirror); }
Source:
<code><START> protected static URI buildCriteriaURI(ResourceContextImpl resourceContext, RecordTemplate criteria, String batchParameterName, URI uri) <END> throws CloneNotSupportedException { DataList criteriaList = new DataList(1); criteriaList.add(criteria.data()); DataMap queryParams = extractQueryParamsFromResourceContext(resourceContext); return URIParamUtils.replaceQueryParam(uri, batchParameterName, criteriaList, queryParams, resourceContext.getRestliProtocolVersion()); }</code><technical_language>suggest making private methods package-private if need accessed a unit test. Making protected opens access implies intended inheritance relationship</technical_language>

Target:
static URI buildCriteriaURI(ResourceContextImpl resourceContext, RecordTemplate criteria, String batchParameterName, URI uri) { DataList criteriaList = new DataList(1); criteriaList.add(criteria.data()); return URIParamUtils.replaceQueryParam(uri, batchParameterName, criteriaList, resourceContext.getParameters(), resourceContext.getRestliProtocolVersion()); }
Source:
<code>private ArrayList<Chunk> findChunksToMove(long startBlock, long moveSize) { ArrayList<Chunk> move = new ArrayList<>(); for (Chunk c : chunks.values()) { if (c.block > startBlock) { move.add(c); } } Collections.sort(move, new Comparator<Chunk>() { @Override public int compare(Chunk o1, Chunk o2) { int res = Long.signum(o1.block - o2.block); <START> assert res == Long.compare(o1.block, o2.block); <END> return res; } }); int count = 0; long size = 0; for (Chunk c : move) { long chunkSize = c.len * (long) BLOCK_SIZE; size += chunkSize; if (size > moveSize) { break; } count++; } while (move.size() > count && move.size() > 1) { move.remove(1); } return move; }</code><technical_language>This assertion strange for me. Chunk.block negative due some error? I other reason for it</technical_language>

Target:
private ArrayList<Chunk> findChunksToMove(long startBlock, long moveSize) { ArrayList<Chunk> move = new ArrayList<>(); for (Chunk c : chunks.values()) { if (c.block > startBlock) { move.add(c); } } Collections.sort(move, new Comparator<Chunk>() { @Override public int compare(Chunk o1, Chunk o2) { return Long.signum(o1.block - o2.block); } }); int count = 0; long size = 0; for (Chunk c : move) { long chunkSize = c.len * (long) BLOCK_SIZE; size += chunkSize; if (size > moveSize) { break; } count++; } while (move.size() > count && move.size() > 1) { move.remove(1); } return move; }
Source:
<code>private String extractJsonStringFromRequest(HttpServletRequest request) throws FileUploadException { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(4096); factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(1000000); <START> List<?> fileItems = upload.parseRequest(request); <END> Iterator<?> iterator = fileItems.iterator(); String jsonContent = ""; while (iterator.hasNext()) { FileItem fi = (FileItem) iterator.next(); if (fi.isFormField()) { String name = fi.getFieldName(); String value = fi.getString(); if (name.equalsIgnoreCase(MAIN_FORM_ITEM_NAME)) { jsonContent = value; } } fi.delete(); } return jsonContent; }</code><technical_language>is reason wildcard 'extends'</technical_language>

Target:
private String extractJsonStringFromRequest(HttpServletRequest request) throws FileUploadException { String jsonContent = ""; for (FileItem requestItem : new ServletRequestTransformer().getFormItems(request)) { if (requestItem.isFormField()) { String name = requestItem.getFieldName(); String value = requestItem.getString(); if (name.equalsIgnoreCase(MAIN_FORM_ITEM_NAME)) { jsonContent = value; } } requestItem.delete(); } return jsonContent; }
Source:
<code>public Collection<T> getPropertiesList() { <START> return subProperties; <END> }</code><technical_language>want return collection is ? if is expect client api modify list of properties manually. This fine. If want alter list please return a Collections.unmodifiableCollection</technical_language>

Target:
public Collection<T> getPropertiesList() { return Collections.unmodifiableCollection(subProperties); }
Source:
<code>private String nodeSensorPrefix(final String threadId, final String taskId, final String processorNodeName) { return taskSensorPrefix(threadId, taskId) <START> + SENSOR_PREFIX_DELIMITER + "node" + SENSOR_PREFIX_DELIMITER + processorNodeName; <END> }</code><technical_language>for node</technical_language>

Target:
private String nodeSensorPrefix(final String threadId, final String taskId, final String processorNodeName) { return taskSensorPrefix(threadId, taskId) + SENSOR_PREFIX_DELIMITER + SENSOR_NODE_LABEL + SENSOR_PREFIX_DELIMITER + processorNodeName; }
Source:
<code>public List<Route> routes() { return Collections.singletonList( <START> new Route(DELETE, MachineLearning.BASE_PATH + "_delete_expired_data/{" + Fields.JOB_ID.getPreferredName() + "}")); <END> }</code><technical_language>need empty route in replacedRoutes put is removed</technical_language>

Target:
public List<Route> routes() { return Collections.singletonList( new Route(DELETE, MachineLearning.BASE_PATH + "_delete_expired_data/{" + Job.ID.getPreferredName() + "}")); }
Source:
<code>public Object call(ApiCaller ac, Deserializer parms) throws PerunException { ac.stateChangingCheck(); List<Integer> memberInts = parms.readList("members", Integer.class); Group group = ac.getGroupById(parms.readInt("group")); List<Member> members = new ArrayList<>(); for (Integer memberInt : memberInts) { members.add(ac.getGroupsManager().getGroupMemberById(ac.getSession(), group, memberInt)); } <START> ac.getGroupsManager().removeMembers(ac.getSession(), <END> group, members); return null; }</code><technical_language>exceptions? describing exceptions InternalErrorException, PrivilageException RpcException. check in AttributesManagerMethod (It is missing in this manager)</technical_language>

Target:
public Group call(ApiCaller ac, Deserializer parms) throws PerunException { ac.stateChangingCheck(); if (parms.contains("group")) { if (parms.contains("parentGroup")) { return ac.getGroupsManager().createGroup(ac.getSession(), ac.getGroupById(parms.readInt("parentGroup")), parms.read("group", Group.class)); } else if (parms.contains("vo")) { Group group = parms.read("group", Group.class); if (group.getParentGroupId() == null) { return ac.getGroupsManager().createGroup(ac.getSession(), ac.getVoById(parms.readInt("vo")), group); } else { throw new RpcException(RpcException.Type.WRONG_PARAMETER, "Top-level groups can't have parentGroupId set!"); } } else { throw new RpcException(RpcException.Type.MISSING_VALUE, "vo or parentGroup"); } } else if (parms.contains("name") && parms.contains("description")) { if (parms.contains("parentGroup")) { String name = parms.readString("name"); String description = parms.readString("description"); Group group = new Group(name, description); return ac.getGroupsManager().createGroup(ac.getSession(), ac.getGroupById(parms.readInt("parentGroup")), group); } else if (parms.contains("vo")) { String name = parms.readString("name"); String description = parms.readString("description"); Group group = new Group(name, description); return ac.getGroupsManager().createGroup(ac.getSession(), ac.getVoById(parms.readInt("vo")), group); } else { throw new RpcException(RpcException.Type.MISSING_VALUE, "vo or parentGroup"); } } else { throw new RpcException(RpcException.Type.MISSING_VALUE, "group or (name and description)"); } }
Source:
<code>public void onClick(View view) { if (adapter == null) { return; } if (adapter.getActionMode() != BrickAdapter.ActionModeEnum.NO_ACTION) { return; } <START> if (((BrickAdapter) adapter).isDragging) { <END> return; } showFormulaEditorToEditFormula(view); }</code><technical_language>of ClassCastException, instanceof check required casting</technical_language>

Target:
public void onClick(View view) { if (adapter == null) { return; } if (adapter.getActionMode() != BrickAdapter.ActionModeEnum.NO_ACTION) { return; } if (adapter instanceof BrickAdapter && ((BrickAdapter) adapter).isDragging) { return; } showFormulaEditorToEditFormula(view); }
Source:
<code>private String getSpatialPartitioning(Rectangle extent, List<OGCGeometry> geometries, int partitionCount) { ImmutableList.Builder<Rectangle> rectangles = ImmutableList.builder(); for (OGCGeometry geometry : geometries) { Envelope envelope = new Envelope(); geometry.getEsriGeometry().queryEnvelope(envelope); rectangles.add(new Rectangle(envelope.getXMin(), envelope.getYMin(), envelope.getXMax(), envelope.getYMax())); } return KDB_TREE_CODEC.toJson(buildKDBTree((int) (Math.ceil(geometries.size() * 1.0 / partitionCount)), partitionCount, extent, rectangles.build())); <START> } <END></code><technical_language>toIntExact</technical_language>

Target:
private String getSpatialPartitioning(Rectangle extent, List<OGCGeometry> geometries, int partitionCount) { ImmutableList.Builder<Rectangle> rectangles = ImmutableList.builder(); for (OGCGeometry geometry : geometries) { Envelope envelope = new Envelope(); geometry.getEsriGeometry().queryEnvelope(envelope); rectangles.add(new Rectangle(envelope.getXMin(), envelope.getYMin(), envelope.getXMax(), envelope.getYMax())); } return KdbTreeUtils.toJson(buildKdbTree(roundToInt(geometries.size() * 1.0 / partitionCount, CEILING), extent, rectangles.build())); }
Source:
<code>private VdsNetworkInterface getVlanDevice(final VdsNetworkInterface baseNic, final Integer vlanId) { if (vlanId == null) { return null; } return LinqUtils.firstOrNull(getNics(), new Predicate<VdsNetworkInterface>() { @Override public boolean eval(VdsNetworkInterface t) { return (baseNic.getName().equals(t.getBaseInterface()) && <START> ObjectUtils.objectsEqual(t.getVlanId(), <END> vlanId)); } }); }</code><technical_language>pls Objects.equal() instead</technical_language>

Target:
private VdsNetworkInterface getVlanDevice(final VdsNetworkInterface baseNic, final Integer vlanId) { if (vlanId == null) { return null; } return LinqUtils.firstOrNull(getNics(), new Predicate<VdsNetworkInterface>() { @Override public boolean eval(VdsNetworkInterface t) { return (baseNic.getName().equals(t.getBaseInterface()) && Objects.equals(t.getVlanId(), vlanId)); } }); }
Source:
<code>public static X509TrustManager createX509TrustManager(SslConfiguration config) { TrustManager trustManager = createTrustManagers(config)[0]; if (trustManager instanceof X509TrustManager) { return (X509TrustManager) trustManager; } else { throw new RuntimeException( "First TrustManager associated with SslConfiguration was not a X509TrustManager: " <START> + config.trustStorePath()); <END> } }</code><technical_language>useful kind of trust manager was</technical_language>

Target:
public static X509TrustManager createX509TrustManager(SslConfiguration config) { TrustManager trustManager = createTrustManagers(config)[0]; if (trustManager instanceof X509TrustManager) { return (X509TrustManager) trustManager; } else { throw new RuntimeException(String.format( "First TrustManager associated with SslConfiguration was expected to be a %s, but was a %s: %s", X509TrustManager.class.getSimpleName(), trustManager.getClass().getSimpleName(), config.trustStorePath())); } }
Source:
<code>public List<CheckedFuture<?, IOException>> <START> update( <END> Project.NameKey project) throws IOException { try { return new ProjectUpdateTask(schemaFactory, project).call(); } catch (Exception e) { Throwables.propagateIfPossible(e); throw MAPPER.apply(e); } }</code><technical_language>s/update/updateAsync</technical_language>

Target:
public void update(Project.NameKey project) throws IOException { try { for (CheckedFuture<?, IOException> f : new ProjectUpdateTask( schemaFactory, project, false).call()) { f.checkedGet(); } } catch (Exception e) { Throwables.propagateIfPossible(e); throw MAPPER.apply(e); } }
Source:
<code>protected List<StorageServerConnections> filterConnectionsUsedByOthers( List<StorageServerConnections> connections, String vgId, Guid poolId) { List<StorageServerConnections> connsToClose = new ArrayList<>(); for (StorageServerConnections conn : connections) { List<LUNs> luns = DbFacade.getInstance().getLunDao().getAllForStorageServerConnection(conn.getid()); <START> if (poolId != null && !activeSDsExist(luns, vgId, poolId) && !activePluggedDirectLunsExist(luns)) { <END> connsToClose.add(conn); } } return connsToClose; }</code><technical_language>I poolId check is needed, if is needed need verify throw if null..if null dont check here</technical_language>

Target:
protected List<StorageServerConnections> filterConnectionsUsedByOthers( List<StorageServerConnections> connections, String vgId, Guid poolId) { List<StorageServerConnections> connsToClose = new ArrayList<>(); for (StorageServerConnections conn : connections) { List<LUNs> luns = DbFacade.getInstance().getLunDao().getAllForStorageServerConnection(conn.getid()); if (!activeSDsExist(luns, vgId, poolId) && !activePluggedDirectLunsExist(poolId, luns)) { connsToClose.add(conn); } } return connsToClose; }
Source:
<code>public C map(int i, ResultSet rs, StatementContext ctx) throws SQLException { C obj; logger.debug("map {}", clazz); try { Constructor<C> constructor = clazz.getDeclaredConstructor(); constructor.setAccessible(true); obj = constructor.newInstance(); for (int colIndex = rs.getMetaData().getColumnCount(); colIndex >= 1; colIndex--) { String columnLabel = rs.getMetaData().getColumnLabel(colIndex); <START> JpaMember member = jpaClass.lookupMember(columnLabel); <END> if (member != null) { Class<?> memberType = member.getType(); ResultColumnMapper<?> columnMapper = ctx.columnMapperFor(memberType); Object value = columnMapper.mapColumn(rs, columnLabel, ctx); member.write(obj, value); } } } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e); } return obj; }</code><technical_language>This property mapping strategy #212</technical_language>

Target:
public C map(int i, ResultSet rs, StatementContext ctx) throws SQLException { logger.debug("map {}", clazz); try { return tryMap(rs, ctx); } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) { throw new EntityMemberAccessException(String.format("Unable to map %s entity", clazz), e); } }
Source:
<code>public static EncodeFormat checkedValueOf(String name) { try { <START> return Enum.valueOf(EncodeFormat.class, name); <END> } catch (Exception ex) { VoltDB.crashLocalVoltDB("Illegal encoding format " + name, true, ex); } return null; }</code><technical_language>EncodeFormat.valueOf</technical_language>

Target:
public static EncodeFormat checkedValueOf(String name) { try { return valueOf(EncodeFormat.class, name); } catch (Exception ex) { VoltDB.crashLocalVoltDB("Illegal encoding format " + name, true, ex); } return null; }
Source:
<code>private boolean applyViolation(final H canvasHandler, final RuleViolation violation) { if (hasViolations(violation)) { final Canvas canvas = canvasHandler.getCanvas(); final Shape shape = getShape(canvasHandler, violation.getUUID()); if (null != shape) { shape.applyState(ShapeState.INVALID); <START> } <END> return true; } return false; }</code><technical_language>lines remove [1] of this change. [1] java final Canvas canvas = canvasHandler.getCanvas();</technical_language>

Target:
private boolean applyViolation(final H canvasHandler, final RuleViolation violation) { if (hasViolations(violation)) { final Shape shape = getShape(canvasHandler, violation.getUUID()); if (null != shape) { shape.applyState(ShapeState.INVALID); } return true; } return false; }
Source:
<code>public static int getFirstBinInLevel(final int levelNumber) { if (levelNumber >= getNumIndexLevels()) { <START> throw new SAMException("Level number is too big (" + levelNumber + ")."); <END> } return GenomicIndexUtil.LEVEL_STARTS[levelNumber]; }</code><technical_language>useful include max in error message</technical_language>

Target:
public static int getFirstBinInLevel(final int levelNumber) { assertLevelIsValid(levelNumber); return GenomicIndexUtil.LEVEL_STARTS[levelNumber]; }
Source:
<code>public void run(Session session, String keyspace, boolean resetDB, int replicationFactor, boolean updateVersion) { CassalogBuilder builder = new CassalogBuilder(); Cassalog cassalog = builder.withKeyspace(keyspace).withSession(session).build(); Map<String, ?> vars = ImmutableMap.of( "keyspace", keyspace, "reset", resetDB, "session", session, "replicationFactor", replicationFactor, "logger", logger ); List<String> tags = asList("0.15.x", "0.18.x", "0.19.x", "0.20.x", "0.21.x", "0.23.x", "0.26.x", "0.27.x"); URI script = getScript(); cassalog.execute(script, tags, vars); if (updateVersion) { try { updateVersion(session, keyspace, 0, 0); <START> } catch (Exception e) { <END> throw new VersionUpdateException("Failed to update version in system configuration", e); } } }</code><technical_language>InterruptedException is transformed VersionUpdateException? slightly confused Exception transformations catches RuntimeExceptions</technical_language>

Target:
public void run(Session session, String keyspace, boolean resetDB, int replicationFactor, boolean updateVersion) { CassalogBuilder builder = new CassalogBuilder(); Cassalog cassalog = builder.withKeyspace(keyspace).withSession(session).build(); Map<String, ?> vars = ImmutableMap.of( "keyspace", keyspace, "reset", resetDB, "session", session, "replicationFactor", replicationFactor, "logger", logger ); List<String> tags = asList("0.15.x", "0.18.x", "0.19.x", "0.20.x", "0.21.x", "0.23.x", "0.26.x", "0.27.x"); URI script = getScript(); cassalog.execute(script, tags, vars); if (updateVersion) { updateVersion(session, keyspace, 0, 0); } }
Source:
<code>public void serialize( final ActorRef value, final JsonGenerator gen, final SerializerProvider serializers) throws IOException { <START> gen.writeString(value.path().toStringWithAddress(_system.provider().getDefaultAddress())); <END> }</code><technical_language>[Akka docs serialization](<LINK_0> suggest Serialization.serializedActorPath(theActorRef). in cases yields a result this code here</technical_language>

Target:
public void serialize( final ActorRef value, final JsonGenerator gen, final SerializerProvider serializers) throws IOException { gen.writeString(Serialization.serializedActorPath(value)); }
Source:
<code><START> public SCIMSearchResult<User> searchUser(String query, Integer limit, Long offset, String orderBy, <END> Boolean ascending, String attributes) { QueryBuilder qb = new QueryBuilder(); qb.filter(query); if (attributes != null) { qb.attributes(attributes); } if (limit != null) { qb.count(limit); } if (offset != null) { qb.startIndex(offset); } if (orderBy != null && ascending != null) { if (ascending) { qb.ascending(orderBy); } else { qb.descending(orderBy); } } return connector.searchUsers(qb.build(), sessionData.getAccesstoken()); }</code><technical_language>QueryBuilder multiple parameters null? in line 19 28 is hard understand nulls for</technical_language>

Target:
public SCIMSearchResult<User> searchUser(String query, Integer limit, Long offset, String orderBy, Boolean ascending, String attributes) { QueryBuilder qb = new QueryBuilder(); qb.filter(query); qb.attributes(attributes); qb.count(limit); qb.startIndex(offset); if (ascending) { qb.ascending(orderBy); } else { qb.descending(orderBy); } return connector.searchUsers(qb.build(), sessionData.getAccesstoken()); }
Source:
<code>protected int processLineContent(String line, int offset) { String text = line.substring(offset); String content; Matcher itemStartMatcher = itemStartPattern.matcher(text); if (itemStartMatcher.matches()) { if (blockLineCount == 0) { BlockType blockType = itemStartMatcher.group(1) != null ? BlockType.BULLETED_LIST : BlockType.NUMERIC_LIST; builder.beginBlock(blockType, new Attributes()); <START> builder.characters("\n"); END> } else { builder.endBlock(); builder.characters("\n"); } builder.beginBlock(BlockType.LIST_ITEM, new Attributes()); content = itemStartMatcher.group(3); } else if (!text.trim().isEmpty()) { builder.characters("\n"); content = text; } else { setClosed(true); return offset; } int textStart = 0; markupLanguage.emitMarkupLine(getParser(), state, content, textStart); blockLineCount++; return -1; }</code><technical_language>add newline</technical_language>

Target:
protected int processLineContent(String line, int offset) { String text = line.substring(offset); String content; Matcher itemStartMatcher = itemStartPattern.matcher(text); if (itemStartMatcher.matches()) { if (blockLineCount == 0) { BlockType blockType = itemStartMatcher.group(1) != null ? BlockType.BULLETED_LIST : BlockType.NUMERIC_LIST; builder.beginBlock(blockType, new Attributes()); } else { builder.endBlock(); } builder.beginBlock(BlockType.LIST_ITEM, new Attributes()); content = itemStartMatcher.group(3); } else if (!text.trim().isEmpty()) { builder.characters("\n"); content = text; } else { setClosed(true); return offset; } int textStart = 0; markupLanguage.emitMarkupLine(getParser(), state, content, textStart); blockLineCount++; return -1; }
Source:
<code>public void compile() throws DbException { Preconditions.checkArgument(needsCompiling(), "This expression does not need to be compiled."); String javaExpression = getJavaExpression(); IScriptEvaluator se; try { se = CompilerFactoryFactory.getDefaultCompilerFactory().newExpressionEvaluator(); } catch (Exception e) { <START> LOGGER.error("Could not create expression evaluator", e); <END> throw new DbException("Could not create expression evaluator", e); } try { evaluator = (EvalInterface) se.createFastEvaluator(javaExpression, EvalInterface.class, new String[] { Expression.TB, Expression.ROW, Expression.RESULT, Expression.STATE }); } catch (CompileException e) { LOGGER.error("Error when compiling expression: {}", javaExpression); throw new DbException("Error when compiling expression: " + javaExpression, e); } }</code><technical_language>In case create evaluator</technical_language>

Target:
public void compile() throws DbException { Preconditions.checkArgument(needsCompiling(), "This expression does not need to be compiled."); String javaExpression = getJavaExpression(); IScriptEvaluator se; try { se = CompilerFactoryFactory.getDefaultCompilerFactory().newExpressionEvaluator(); } catch (Exception e) { LOGGER.error("Could not create expression evaluator", e); throw new DbException("Could not create expression evaluator", e); } try { evaluator = (EvalInterface) se.createFastEvaluator(javaExpression, EvalInterface.class, new String[] { Expression.TB, Expression.ROW, Expression.RESULT, Expression.STATE }); } catch (CompileException e) { LOGGER.error("Error when compiling expression {}: {}", javaExpression, e); throw new DbException("Error when compiling expression: " + javaExpression, e); } }
Source:
<code>public MissingColumnError(String file, String field) { <START> super(file, 0, field); <END> }</code><technical_language>this line 1? important</technical_language>

Target:
public MissingColumnError(String file, String field) { super(file, 1, field); }
Source:
<code><START> public void onTestStart(ITestResult iTestResult) { <END> Object[] parameters = iTestResult.getParameters(); ITestNGMethod method = iTestResult.getMethod(); ConstructorOrMethod constructorOrMethod = method.getConstructorOrMethod(); if (constructorOrMethod != null) { Method nativeMethod = constructorOrMethod.getMethod(); boolean atLeastJava8 = isAtLeastJava8(); String[] parameterNames = null; if (atLeastJava8) { parameterNames = getParameterNames(nativeMethod); } for (int i = 0; i < parameters.length; i++) { String name = "arg" + i; if (parameterNames != null) { name = parameterNames[i]; } String value = parameters[i].toString(); getLifecycle().fire(new AddParameterEvent(name, value, ParameterKind.ARGUMENT)); } } String suitePrefix = getCurrentSuitePrefix(iTestResult); String testName = getName(iTestResult); startedTestNames.add(testName); testName = testName.replace(suitePrefix, ""); Description description = new Description().withValue(method.getDescription()); TestCaseStartedEvent event = new TestCaseStartedEvent(getSuiteUid(iTestResult.getTestContext()), testName); if (description.getValue() != null) { event.setDescription(description); } AnnotationManager am = new AnnotationManager(getMethodAnnotations(iTestResult)); am.setDefaults(getClassAnnotations(iTestResult)); am.update(event); getLifecycle().fire(event); }</code><technical_language>reduce complexity of this method</technical_language>

Target:
public void onTestStart(ITestResult iTestResult) { ITestNGMethod method = iTestResult.getMethod(); String suitePrefix = getCurrentSuitePrefix(iTestResult); String testName = getName(iTestResult); startedTestNames.add(testName); testName = testName.replace(suitePrefix, ""); Description description = new Description().withValue(method.getDescription()); TestCaseStartedEvent event = new TestCaseStartedEvent(getSuiteUid(iTestResult.getTestContext()), testName); if (description.getValue() != null) { event.setDescription(description); } AnnotationManager am = new AnnotationManager(getMethodAnnotations(iTestResult)); am.setDefaults(getClassAnnotations(iTestResult)); am.update(event); getLifecycle().fire(event); fireAddParameterEvents(iTestResult); }
Source:
<code>private CqlSessionBuilder buildCluster(int port) { String host = resolveHost(); return CqlSession.builder().addContactPoint(InetSocketAddress.createUnresolved(host, port)) <START> .withLocalDatacenter("datacenter1").withConfigLoader( <END> DriverConfigLoader.programmaticBuilder().withString(DefaultDriverOption.PROTOCOL_VERSION, "V5").build()); }</code><technical_language>Integration tests run against: * A local Cassandra instance * embedded * TestContainers suggest performing a version check configured Cassandra instance. If is version 4+, default protocol V5. Otherwise, stick driver defaults safely assume driver perform a handshake newest version fall highest supported version</technical_language>

Target:
private CqlSessionBuilder buildCluster(int port) { String host = resolveHost(); CqlSessionBuilder builder = CqlSession.builder().addContactPoint(InetSocketAddress.createUnresolved(host, port)) .withLocalDatacenter("datacenter1"); CqlSession cqlSession = builder.build(); if (cassandraVersionGreaterThanOrEqualTo4(cqlSession)) { return builder.withConfigLoader( DriverConfigLoader.programmaticBuilder().withString(DefaultDriverOption.PROTOCOL_VERSION, "V5").build()); } else { return builder; } }
Source:
<code>public Pair<Vertex, Edge> nextMinimum() { Edge nextMinimum = new Edge(Integer.MAX_VALUE); Vertex nextVertex = this; <START> Iterator it = edges.entrySet() .iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry) it.next(); if (!((Vertex) pair.getKey()).isVisited()) { if (!((Edge) pair.getValue()).isIncluded()) { if (((Edge) pair.getValue()).getWeight() < nextMinimum.getWeight()) { nextMinimum = (Edge) pair.getValue(); nextVertex = (Vertex) pair.getKey(); } } } } <END> return new Pair<>(nextVertex, nextMinimum); }</code><technical_language>A typed iterator code more readable cast times iteration of loop</technical_language>

Target:
public Pair<Vertex, Edge> nextMinimum(){ Edge nextMinimum = new Edge(Integer.MAX_VALUE); Vertex nextVertex = this; Iterator<Map.Entry<Vertex,Edge>> it = edges.entrySet().iterator(); while (it.hasNext()) { Map.Entry<Vertex,Edge> pair = it.next(); if (!pair.getKey().isVisited()){ if (!pair.getValue().isIncluded()) { if (pair.getValue().getWeight() < nextMinimum.getWeight()) { nextMinimum = pair.getValue(); nextVertex = pair.getKey(); } } } } return new Pair<>(nextVertex, nextMinimum); }
Source:
<code>public void testAggregates() throws Exception { AggregateDefinition aggDef = new AggregateDescriptor(); aggDef.setId("cardinal"); aggDef.setType(AGG_CARDINALITY); aggDef.setDocumentField("dc:title"); AggregateDefinition avggDef = new AggregateDescriptor(); avggDef.setId("average"); avggDef.setType(AGG_AVG); avggDef.setDocumentField("dc:created"); SingleValueMetricAggregate cardinality = (SingleValueMetricAggregate) AggregateFactory.create(aggDef, null); SingleValueMetricAggregate average = (SingleValueMetricAggregate) AggregateFactory.create(avggDef, null); <START> NxQueryBuilder qb = new NxQueryBuilder(session).nxql("select * From Document") <END> .limit(0) .addAggregate(cardinality) .addAggregate(average) .onlyElasticsearchResponse(); EsResult esRes = ess.queryAndAggregate(qb); Assert.assertNotNull(cardinality.getValue()); }</code><technical_language>Nitpick: write SQL keywords in all-caps (SELECT, FROM)</technical_language>

Target:
public void testAggregates() throws Exception { AggregateDefinition aggDef = new AggregateDescriptor(); aggDef.setId("cardinal"); aggDef.setType(AGG_CARDINALITY); aggDef.setDocumentField("dc:title"); AggregateDefinition avggDef = new AggregateDescriptor(); avggDef.setId("average"); avggDef.setType(AGG_AVG); avggDef.setDocumentField("dc:created"); SingleValueMetricAggregate cardinality = (SingleValueMetricAggregate) AggregateFactory.create(aggDef, null); SingleValueMetricAggregate average = (SingleValueMetricAggregate) AggregateFactory.create(avggDef, null); NxQueryBuilder qb = new NxQueryBuilder(session).nxql("SELECT * FROM Document") .limit(0) .addAggregate(cardinality) .addAggregate(average) .onlyElasticsearchResponse(); EsResult esRes = ess.queryAndAggregate(qb); Assert.assertNotNull(cardinality.getValue()); }
Source:
<code>public static void deleteFile(Connection connection, int fid) throws ServiceException{ try { PreparedStatement deleteStatement = connection.prepareStatement(DELETE_FILE_QUERY); deleteStatement.setInt(1, fid); <START> if (deleteStatement.executeUpdate() != -1) { <END> deleteStatement.close(); throw new ServiceException(ServiceStatus.APP_FILE_NOT_EXIST); } } catch (SQLException ex){ throw new ServiceException(ServiceStatus.DATABASE_ERROR, ex); } }</code><technical_language>This 1, -1. executeUpdate() returns number of rows updated. Also, deleteStatement.close() is run if is error. another deleteStatement.close() if block</technical_language>

Target:
public static void deleteFile(Connection connection, int fid) throws ServiceException { try { PreparedStatement deleteStatement = connection.prepareStatement(DELETE_FILE_QUERY); deleteStatement.setInt(1, fid); if (deleteStatement.executeUpdate() != 1) { deleteStatement.close(); throw new ServiceException(ServiceStatus.APP_FILE_NOT_EXIST); } deleteStatement.close(); } catch (SQLException ex){ throw new ServiceException(ServiceStatus.DATABASE_ERROR, ex); } }
Source:
<code>public HiveSplitManager( HiveClientConfig hiveClientConfig, Function<HiveTransactionHandle, SemiTransactionalHiveMetastore> metastoreProvider, NamenodeStats namenodeStats, HdfsEnvironment hdfsEnvironment, DirectoryLister directoryLister, @ForHiveClient ExecutorService executorService, CoercionPolicy coercionPolicy) { this( metastoreProvider, namenodeStats, hdfsEnvironment, directoryLister, new BoundedExecutor(executorService, hiveClientConfig.getMaxSplitIteratorThreads()), coercionPolicy, new CounterStat(), hiveClientConfig.getMaxOutstandingSplits(), hiveClientConfig.getMaxOutstandingSplitsSize(), hiveClientConfig.getMinPartitionBatchSize(), hiveClientConfig.getMaxPartitionBatchSize(), hiveClientConfig.getMaxInitialSplits(), hiveClientConfig.getSplitLoaderConcurrency(), hiveClientConfig.getRecursiveDirWalkerEnabled(), <START> new S3SelectPushdown(hiveClientConfig)); <END> }</code><technical_language>a general coding convention, store config objects in classes, config objects mutable beans. Instead, constructor extract values immutable fields</technical_language>

Target:
public HiveSplitManager( HiveClientConfig hiveClientConfig, Function<HiveTransactionHandle, SemiTransactionalHiveMetastore> metastoreProvider, NamenodeStats namenodeStats, HdfsEnvironment hdfsEnvironment, DirectoryLister directoryLister, @ForHiveClient ExecutorService executorService, CoercionPolicy coercionPolicy) { this( metastoreProvider, namenodeStats, hdfsEnvironment, directoryLister, new BoundedExecutor(executorService, hiveClientConfig.getMaxSplitIteratorThreads()), coercionPolicy, new CounterStat(), hiveClientConfig.getMaxOutstandingSplits(), hiveClientConfig.getMaxOutstandingSplitsSize(), hiveClientConfig.getMinPartitionBatchSize(), hiveClientConfig.getMaxPartitionBatchSize(), hiveClientConfig.getMaxInitialSplits(), hiveClientConfig.getSplitLoaderConcurrency(), hiveClientConfig.getRecursiveDirWalkerEnabled()); }
Source:
<code>public List<NetworkMetaData> getNetworksMetaData(long accountId) { MultiRecordMapper<NetworkMetaData> mapper = new MultiRecordMapper<NetworkMetaData>() { @Override protected NetworkMetaData map(List<Object> input) { Network ntwk = (Network) input.get(0); <START> Map<String, Object> meta = DataAccessor.fields(ntwk).withKey(ServiceConstants.FIELD_METADATA) <END> .withDefault(Collections.EMPTY_MAP).as(Map.class); NetworkMetaData data = new NetworkMetaData(ntwk.getName(), ntwk.getUuid(), meta); return data; } }; NetworkTable ntwk = mapper.add(NETWORK); return create() .select(mapper.fields()) .from(ntwk) .where(ntwk.REMOVED.isNull()) .and(ntwk.ACCOUNT_ID.eq(accountId)) .fetch().map(mapper); }</code><technical_language>I need add NETWORK.DATA select. is DataAccessor.fieldMap() for this</technical_language>

Target:
public List<NetworkMetaData> getNetworksMetaData(long accountId) { MultiRecordMapper<NetworkMetaData> mapper = new MultiRecordMapper<NetworkMetaData>() { @Override protected NetworkMetaData map(List<Object> input) { Network ntwk = (Network) input.get(0); Map<String, Object> meta = DataAccessor.fieldMap(ntwk, ServiceConstants.FIELD_METADATA); NetworkMetaData data = new NetworkMetaData(ntwk.getName(), ntwk.getUuid(), meta); return data; } }; NetworkTable ntwk = mapper.add(NETWORK, NETWORK.NAME, NETWORK.UUID, NETWORK.DATA); return create() .select(mapper.fields()) .from(ntwk) .where(ntwk.REMOVED.isNull()) .and(ntwk.ACCOUNT_ID.eq(accountId)) .fetch().map(mapper); }
Source:
<code>public static CompletedCheckpointStore createCompletedCheckpointStore( Configuration configuration, FlinkKubeClient kubeClient, Executor executor, String configMapName, String lockIdentity, int maxNumberOfCheckpointsToRetain) throws Exception { final RetrievableStateStorageHelper<CompletedCheckpoint> stateStorage = new FileSystemStateStorageHelper<>(HighAvailabilityServicesUtils .getClusterHighAvailableStoragePath(configuration), COMPLETED_CHECKPOINT_FILE_SUFFIX); final KubernetesStateHandleStore<CompletedCheckpoint> stateHandleStore = new KubernetesStateHandleStore<>( kubeClient, configMapName, stateStorage, k -> k.startsWith(CHECKPOINT_ID_KEY_PREFIX), lockIdentity); return new DefaultCompletedCheckpointStore( maxNumberOfCheckpointsToRetain, stateHandleStore, <START> new KubernetesCheckpointStoreUtil(), <END> executor); }</code><technical_language>this a singleton enum</technical_language>

Target:
public static CompletedCheckpointStore createCompletedCheckpointStore( Configuration configuration, FlinkKubeClient kubeClient, Executor executor, String configMapName, String lockIdentity, int maxNumberOfCheckpointsToRetain) throws Exception { final RetrievableStateStorageHelper<CompletedCheckpoint> stateStorage = new FileSystemStateStorageHelper<>(HighAvailabilityServicesUtils .getClusterHighAvailableStoragePath(configuration), COMPLETED_CHECKPOINT_FILE_SUFFIX); final KubernetesStateHandleStore<CompletedCheckpoint> stateHandleStore = new KubernetesStateHandleStore<>( kubeClient, configMapName, stateStorage, k -> k.startsWith(CHECKPOINT_ID_KEY_PREFIX), lockIdentity); return new DefaultCompletedCheckpointStore<>( maxNumberOfCheckpointsToRetain, stateHandleStore, KubernetesCheckpointStoreUtil.INSTANCE, executor); }