auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static void setFilePermissionsTo700(File file) throws IOException { file.createNewFile(); file.setExecutable(false, false); file.setReadable(false, false); file.setWritable(false, false); file.setReadable(true, true); file.setWritable(true, true); <START> file.setExecutable(true, true); <END> }</code><technical_language>worth checking return values set calls logging a warning if false</technical_language>

Target:
public static void setFilePermissionsTo700(File file) throws IOException { file.createNewFile(); boolean setRead = file.setReadable(false, false) & file.setReadable(true, true); boolean setWrite = file.setWritable(false, false) & file.setWritable(true, true); boolean setExec = file.setExecutable(false, false) & file.setExecutable(true, true); if (setRead && setWrite && setExec) { if (LOG.isTraceEnabled()) LOG.trace("Set permissions to 700 for file {}", file.getAbsolutePath()); } else { if (loggedSetFilePermissionsWarning) { if (LOG.isTraceEnabled()) LOG.trace("Failed to set permissions to 700 for file {}: setRead={}, setWrite={}, setExecutable={}", new Object[] {file.getAbsolutePath(), setRead, setWrite, setExec}); } else { LOG.warn("Failed to set permissions to 700 for file {}: setRead={}, setWrite={}, setExecutable={}; subsequent failures (on any file) will be logged at trace", new Object[] {file.getAbsolutePath(), setRead, setWrite, setExec}); loggedSetFilePermissionsWarning = true; } } }
Source:
<code>private List<JavaType> getCompletedClassSymbolsType(@Nullable String[] bytecodeNames) { if (bytecodeNames == null) { return ImmutableList.of(); } List<JavaType> types = new ArrayList<>(); for (String bytecodeName : bytecodeNames) { JavaSymbol.TypeJavaSymbol completedClassSymbol = getClassSymbol(bytecodeName); <START> if(!completedClassSymbol.isUnknown()) { <END> types.add(completedClassSymbol.type); } } return types; }</code><technical_language>remove unknown exception types, fail replacing thrown types IndexOutOfBoundExceptions</technical_language>

Target:
private List<JavaType> getCompletedClassSymbolsType(@Nullable String[] bytecodeNames) { if (bytecodeNames == null) { return ImmutableList.of(); } return Arrays.stream(bytecodeNames).map(bName -> getClassSymbol(bName).type).collect(Collectors.toList()); }
Source:
<code>public static Object[][] disableGptOasis() { return new Object[][]{ { "project43", "SyntheticTests/ProvidersChain", "InstantGlobals.wgAdDriverRubiconFastlaneProviderCountries=[]", <START> "TOP_LEADERBOARD", <END> "Liftium" }, { "project43", "SyntheticTests/ProvidersChain", "InstantGlobals.wgAdDriverRubiconFastlaneProviderCountries=[XX]", "TOP_LEADERBOARD", "RubiconFastlane" }, }; }</code><technical_language>do AdsContent.TOP_LEADERBOARD instead</technical_language>

Target:
public static Object[][] disableGptOasis() { return new Object[][]{ { "project43", "SyntheticTests/ProvidersChain", "InstantGlobals.wgAdDriverRubiconFastlaneProviderCountries=[]", AdsContent.TOP_LB, "Liftium" }, { "project43", "SyntheticTests/ProvidersChain", "InstantGlobals.wgAdDriverRubiconFastlaneProviderCountries=[XX]", AdsContent.TOP_LB, "RubiconFastlane" }, }; }
Source:
<code>public String toString() { String[] ipv4withmask = getIPv4addr(); if (this.ipv4.length == this.subnetMasks.length) { for (int i = 0; i < this.subnetMasks.length; i++) { ipv4withmask[i] += "/" + this.subnetMasks[i]; } } String[] ipv6withprefixlength = getIPv6addr(); if (this.ipv6.length == this.prefixLengths.length) { <START> for (int j = 0; j < this.prefixLengths.length; i++) { <END> ipv6withprefixlength[i] += "/" + this.prefixLengths[i]; } } StringBuilder sb = new StringBuilder(); sb.append("Name: ").append(getName()).append(" ").append("(").append(getDisplayName()).append(")").append("\n"); sb.append(" MAC Address: ").append(getMacaddr()).append("\n"); sb.append(" MTU: ").append(getMTU()).append(", ").append("Speed: ").append(getSpeed()).append("\n"); sb.append(" IPv4: ").append(Arrays.toString(ipv4withmask)).append("\n"); sb.append(" IPv6: ").append(Arrays.toString(ipv6withprefixlength)).append("\n"); sb.append(" Traffic: received ").append(getPacketsRecv()).append(" packets/") .append(FormatUtil.formatBytes(getBytesRecv())).append(" (" + getInErrors() + " err, ") .append(getInDrops() + " drop);"); sb.append(" transmitted ").append(getPacketsSent()).append(" packets/") .append(FormatUtil.formatBytes(getBytesSent())).append(" (" + getOutErrors() + " err, ") .append(getCollisions() + " coll);"); return sb.toString(); }</code><technical_language>compiling j (but i++ [i] below)</technical_language>

Target:
public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Name: ").append(getName()).append(" ").append("(").append(getDisplayName()).append(")").append("\n"); sb.append(" MAC Address: ").append(getMacaddr()).append("\n"); sb.append(" MTU: ").append(getMTU()).append(", ").append("Speed: ").append(getSpeed()).append("\n"); String[] ipv4withmask = getIPv4addr(); if (this.ipv4.length == this.subnetMasks.length) { for (int i = 0; i < this.subnetMasks.length; i++) { ipv4withmask[i] += "/" + this.subnetMasks[i]; } } sb.append(" IPv4: ").append(Arrays.toString(ipv4withmask)).append("\n"); String[] ipv6withprefixlength = getIPv6addr(); if (this.ipv6.length == this.prefixLengths.length) { for (int j = 0; j < this.prefixLengths.length; j++) { ipv6withprefixlength[j] += "/" + this.prefixLengths[j]; } } sb.append(" IPv6: ").append(Arrays.toString(ipv6withprefixlength)).append("\n"); sb.append(" Traffic: received ").append(getPacketsRecv()).append(" packets/") .append(FormatUtil.formatBytes(getBytesRecv())).append(" (" + getInErrors() + " err, ") .append(getInDrops() + " drop);"); sb.append(" transmitted ").append(getPacketsSent()).append(" packets/") .append(FormatUtil.formatBytes(getBytesSent())).append(" (" + getOutErrors() + " err, ") .append(getCollisions() + " coll);"); return sb.toString(); }
Source:
<code>public void testRun() throws IOException { String jobFile = JobRunner.jobFileFor(csvFile); String jobCollection = null; JobRunner jobRunner = new JobRunner(); jobRunner.setLogger(logger); jobRunner.setRoles(role); try ( InputStream csvStream = openStream(csvFile); InputStream jobStream = openStream(jobFile); InputStream jobStream2 = openStream(jobFile) ) { jobRunner.run(client, csvStream, jobStream); jobCollection = JobRunner.getJobCollection(jobRunner.getJobId()); ObjectMapper objectMapper = new ObjectMapper(); ObjectNode jobControlObj = (ObjectNode) objectMapper.readTree(jobStream2); testBeforeJobDocument(jobControlObj); testAfterJobDocument(jobControlObj); testJsonDataStructure(jobControlObj); <START> testLoggerStatus(jobRunner.getStatus()); <END> } catch(Exception ex) { ex.printStackTrace(); fail("test exception"); } finally { if (jobCollection != null) { QueryManager queryMgr = client.newQueryManager(); DeleteQueryDefinition deleteDef = queryMgr.newDeleteDefinition(); deleteDef.setCollections(jobCollection); queryMgr.delete(deleteDef); } } }</code><technical_language>Instead, test create a TestJobLogger class implements JobLogger, initialize jobRunner instance of class, assertions status objects passed TestJobLogger</technical_language>

Target:
public void testRun() throws IOException { String jobFile = JobRunner.jobFileFor(csvFile); String jobCollection = null; JobRunner jobRunner = new JobRunner(); jobRunner.setLogger(logger); jobRunner.setRoles(role); try ( InputStream csvStream = openStream(csvFile); InputStream jobStream = openStream(jobFile); InputStream jobStream2 = openStream(jobFile) ) { jobRunner.run(client, csvStream, jobStream); jobCollection = JobRunner.getJobCollection(jobRunner.getJobId()); ObjectMapper objectMapper = new ObjectMapper(); ObjectNode jobControlObj = (ObjectNode) objectMapper.readTree(jobStream2); testBeforeJobDocument(jobControlObj); testAfterJobDocument(jobControlObj); testJsonDataStructure(jobControlObj); } catch(Exception ex) { ex.printStackTrace(); fail("test exception"); } finally { if (jobCollection != null) { QueryManager queryMgr = client.newQueryManager(); DeleteQueryDefinition deleteDef = queryMgr.newDeleteDefinition(); deleteDef.setCollections(jobCollection); queryMgr.delete(deleteDef); } } }
Source:
<code>boolean validate() { getTemplateName().validateEntity( new IValidation[]{ new LengthValidation(BusinessEntitiesDefinitions.VM_TEMPLATE_NAME_SIZE), new I18NNameValidation(){ @Override protected String end() { <START> return "]*$"; END> } } }); return getTemplateName().getIsValid(); }</code><technical_language>I18NExtraNameOrNoneValidation instead.</technical_language>

Target:
boolean validate() { getTemplateName().validateEntity( new IValidation[] { new LengthValidation(BusinessEntitiesDefinitions.VM_TEMPLATE_NAME_SIZE), new I18NExtraNameOrNoneValidation() }); return getTemplateName().getIsValid(); }
Source:
<code>public Coordinate geometryCentroid(Geometry g, Envelope bbox, KmlCentroidOptions opts) { if (opts == null) { opts = KmlCentroidOptions.DEFAULT; } if (opts.isClip()) { if (bbox != null) { g = clipGeometry(g, bbox); <START> } <END> else { LOG.warning("Clip option specified for kml centroids, but no bbox available"); } } if (g instanceof GeometryCollection) { g = selectRepresentativeGeometry((GeometryCollection) g); } if (g == null) { return null; } else if (g instanceof Point) { return g.getCoordinate(); } else if (g instanceof LineString) { LineString line = (LineString) g; LengthIndexedLine lil = new LengthIndexedLine(line); return lil.extractPoint(line.getLength() / 2.0); } else if (g instanceof Polygon) { if (opts.isContain()) { try { Point p = RendererUtilities.sampleForInternalPoint( (Polygon)g, null, null, null, -1, opts.getSamples()); if (p != null && !p.isEmpty()) return p.getCoordinate(); } catch(Exception e) { LOG.log(Level.WARNING, "Unable to calculate central point for polygon", e); } } } return g.getCentroid().getCoordinate(); }</code><technical_language>Formatting :-)</technical_language>

Target:
public Coordinate geometryCentroid(Geometry g, Envelope bbox, KmlCentroidOptions opts) { if (opts == null) { opts = KmlCentroidOptions.DEFAULT; } if (opts.isClip()) { if (bbox != null) { g = clipGeometry(g, bbox); } else { LOG.warning("Clip option specified for kml centroids, but no bbox available"); } } if (g instanceof GeometryCollection) { g = selectRepresentativeGeometry((GeometryCollection) g); } if (g == null) { return null; } else if (g instanceof Point) { return g.getCoordinate(); } else if (g instanceof LineString) { LineString line = (LineString) g; LengthIndexedLine lil = new LengthIndexedLine(line); return lil.extractPoint(line.getLength() / 2.0); } else if (g instanceof Polygon) { if (opts.isContain()) { try { Point p = RendererUtilities.sampleForInternalPoint( (Polygon)g, null, null, null, -1, opts.getSamples()); if (p != null && !p.isEmpty()) { return p.getCoordinate(); } } catch(Exception e) { LOG.log(Level.WARNING, "Unable to calculate central point for polygon", e); } } } return g.getCentroid().getCoordinate(); }
Source:
<code>public void testIsStsStorageLocation_StorageLocationNotFound() { when(mockStorageLocationDAO.get(STORAGE_LOCATION_ID)).thenThrow(NotFoundException.class); <START> assertThrows(IllegalArgumentException.class, () -> projectSettingsManagerImpl.isStsStorageLocationSetting( <END> uploadDestinationListSetting), "Storage location " + STORAGE_LOCATION_ID + " not found"); verify(mockStorageLocationDAO).get(STORAGE_LOCATION_ID); }</code><technical_language>false illegal arg</technical_language>

Target:
public void testIsStsStorageLocation_StorageLocationNotFound() { when(mockStorageLocationDAO.get(STORAGE_LOCATION_ID)).thenThrow(NotFoundException.class); boolean result = projectSettingsManagerImpl.isStsStorageLocationSetting(uploadDestinationListSetting); assertFalse(result); verify(mockStorageLocationDAO).get(STORAGE_LOCATION_ID); }
Source:
<code>public static StructuredRecord asRecord(SparseVector vector) { return StructuredRecord.builder(SPARSE_SCHEMA) .set("size", vector.size()) <START> .set("indices", ArrayUtils.toObject(vector.indices())) <END> .set("vectorValues", ArrayUtils.toObject(vector.values())) .build(); }</code><technical_language>pass vector.indices()</technical_language>

Target:
public static StructuredRecord asRecord(SparseVector vector) { return StructuredRecord.builder(SPARSE_SCHEMA) .set("size", vector.size()) .set("indices", vector.indices()) .set("vectorValues", vector.values()) .build(); }
Source:
<code>public SymbolStatsEstimate visitCall(CallExpression call, Void context) { if (resolution.isCastFunction(call.getFunctionHandle())) { return visitCast(call, context); } if (resolution.isNegateFunction(call.getFunctionHandle())) { return visitArithmeticUnary(call, context); } <START> if (StandardFunctionResolution.isArithmeticFunction(call.getFunctionHandle())) { <END> return visitArithmeticBinary(call, context); } Object value = new RowExpressionInterpreter(call, metadata, session, true).optimize(); if (value == null) { return nullStatsEstimate(); } if (value instanceof RowExpression) { return SymbolStatsEstimate.unknown(); } return SymbolStatsEstimate.builder() .setNullsFraction(0) .setDistinctValuesCount(1) .build(); }</code><technical_language>static import</technical_language>

Target:
public SymbolStatsEstimate visitCall(CallExpression call, Void context) { if (resolution.isCastFunction(call.getFunctionHandle())) { return visitCast(call, context); } if (resolution.isNegateFunction(call.getFunctionHandle())) { return visitArithmeticUnary(call, context); } FunctionMetadata functionMetadata = metadata.getFunctionManager().getFunctionMetadata(call.getFunctionHandle()); if (functionMetadata.getOperatorType().map(OperatorType::isArithmeticOperator).orElse(false)) { return visitArithmeticBinary(call, context); } Object value = new RowExpressionInterpreter(call, metadata, session, true).optimize(); if (value == null) { return nullStatsEstimate(); } if (value instanceof RowExpression) { return SymbolStatsEstimate.unknown(); } return SymbolStatsEstimate.builder() .setNullsFraction(0) .setDistinctValuesCount(1) .build(); }
Source:
<code>public VolumeBrickModel() { setReplicaCount(new EntityModel()); <START> getReplicaCount().setEntity(2); <END> getReplicaCount().setIsChangable(false); setStripeCount(new EntityModel()); getStripeCount().setEntity(4); getStripeCount().setIsChangable(false); setBricks(new ListModel()); }</code><technical_language>constants</technical_language>

Target:
public VolumeBrickModel() { setReplicaCount(new EntityModel()); getReplicaCount().setEntity(VolumeListModel.REPLICATE_COUNT_DEFAULT); getReplicaCount().setIsChangable(false); setStripeCount(new EntityModel()); getStripeCount().setEntity(VolumeListModel.STRIPE_COUNT_DEFAULT); getStripeCount().setIsChangable(false); setBricks(new ListModel()); }
Source:
<code>public void testMakeObject() { final Geometry fish = mockFactory.makeObject(assManager, app); <START> assertTrue(fish != null); <END> }</code><technical_language>is this a test? makeobject return null</technical_language>

Target:
public void testMakeObject() { final Geometry fish = mockFactory.makeObject(assManager, app); assertTrue(((FishControl) (fish).getControl(0)).isEnabled()); }
Source:
<code>private void generateReadList(StructMember member, String variable) { ListType type = (ListType) member.getType(); Type elementType = type.getElementType(); <START> if (elementType instanceof PrimitiveType) { <END> buffer.addLine("empty = reader.empty_element()"); buffer.addLine("reader.read()"); buffer.addLine("if not empty:"); buffer.startBlock(); buffer.addLine("%1$s = List()", variable); buffer.addLine("while reader.forward():"); buffer.startBlock(); buffer.addLine("%1$s.append(Reader.read_string(reader))", variable); buffer.endBlock(); buffer.addLine("reader.read()"); buffer.endBlock(); } else if (elementType instanceof StructType) { PythonClassName readerName = pythonNames.getReaderName(elementType); buffer.addLine("%1$s = %2$s.read_many(reader)", variable, readerName.getClassName()); } else { buffer.addLine("reader.next_element()"); } }</code><technical_language>I in this case generate code "Reader.read_strings" method, instead if re-implementing logic. this care of types primitive types, String: Boolean, Integer, Date Decimal. handle enum types well. Actually, in case type of attribute NetworkUsage enum, string, is need fix in model, handle correctly here</technical_language>

Target:
private void generateReadList(StructMember member, String variable) { ListType type = (ListType) member.getType(); Type elementType = type.getElementType(); if (elementType instanceof PrimitiveType) { generateReadPrimitives((PrimitiveType) elementType, variable); } else if (elementType instanceof EnumType) { generateReadEnum((EnumType) elementType, variable); } else if (elementType instanceof StructType) { PythonClassName readerName = pythonNames.getReaderName(elementType); buffer.addLine("%1$s = %2$s.read_many(reader)", variable, readerName.getClassName()); } else { buffer.addLine("reader.next_element()"); } }
Source:
<code>public void initialize() { loginProgressPane.setVisible(false); loginErrorLabel.managedProperty().bind(loginErrorLabel.visibleProperty()); loginErrorLabel.setVisible(false); <START> Font.loadFont(LoginController.class.getResource("/font/dfc-icons.ttf").toExternalForm(), 10); <END> }</code><technical_language>I realize this font loaded anymore, in CSS? This intended :) load this font in class Main so: Font.loadFont(getClass().getResourceAsStream("/font/dfc-icons.ttf"), defaultFontSize); Open Sans font loaded in CSS file (I swear there....). However, this, unfortunately, issues SceneBuilder (doesn't render style anymore). I this: @font-face { src: url("@../font/dfc-icons.ttf"); } or: @font-face { src: url("/font/dfc-icons.ttf"); } IIRC worked in SceneBuilder, while other worked in program</technical_language>

Target:
public void initialize() { loginProgressPane.setVisible(false); loginErrorLabel.managedProperty().bind(loginErrorLabel.visibleProperty()); loginErrorLabel.setVisible(false); }
Source:
<code>public static Bitmap rotateImage(final Bitmap bitmap, final String storagePath){ try { ExifInterface exifInterface = new ExifInterface(storagePath); final int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1); Matrix matrix = new Matrix(); switch(orientation) { case ExifInterface.ORIENTATION_FLIP_HORIZONTAL: matrix.postScale(-1.0f, 1.0f); break; case ExifInterface.ORIENTATION_ROTATE_180: matrix.postRotate(180); break; case ExifInterface.ORIENTATION_FLIP_VERTICAL: <START> matrix.postRotate(-90); <END> matrix.postScale(1.0f, -1.0f); break; case ExifInterface.ORIENTATION_TRANSPOSE: matrix.postRotate(-90); matrix.postScale(1.0f, -1.0f); break; case ExifInterface.ORIENTATION_ROTATE_90: matrix.postRotate(90); break; case ExifInterface.ORIENTATION_TRANSVERSE: matrix.postRotate(90); matrix.postScale(1.0f, -1.0f); break; case ExifInterface.ORIENTATION_ROTATE_270: matrix.postRotate(270); break; } final Bitmap resultBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true); if (resultBitmap != bitmap) { bitmap.recycle(); } return resultBitmap; } catch (Exception exception) { Log_OC.e("BitmapUtil", "Could not rotate the image: " + storagePath); return bitmap; } }</code><technical_language>This line is included in previous changes for this case</technical_language>

Target:
public static Bitmap rotateImage(final Bitmap bitmap, final String storagePath){ try { ExifInterface exifInterface = new ExifInterface(storagePath); final int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1); Matrix matrix = new Matrix(); switch(orientation) { case ExifInterface.ORIENTATION_FLIP_HORIZONTAL: matrix.postScale(-1.0f, 1.0f); break; case ExifInterface.ORIENTATION_ROTATE_180: matrix.postRotate(180); break; case ExifInterface.ORIENTATION_FLIP_VERTICAL: matrix.postScale(1.0f, -1.0f); break; case ExifInterface.ORIENTATION_TRANSPOSE: matrix.postRotate(-90); matrix.postScale(1.0f, -1.0f); break; case ExifInterface.ORIENTATION_ROTATE_90: matrix.postRotate(90); break; case ExifInterface.ORIENTATION_TRANSVERSE: matrix.postRotate(90); matrix.postScale(1.0f, -1.0f); break; case ExifInterface.ORIENTATION_ROTATE_270: matrix.postRotate(270); break; } final Bitmap resultBitmap =Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true); if (resultBitmap != bitmap) { bitmap.recycle(); } return resultBitmap; } catch (Exception exception) { Log_OC.e("BitmapUtil", "Could not rotate the image: " + storagePath); return bitmap; } }
Source:
<code>public void run() { log.info("Starting " + getWorkerName()); while (true) { try { listenForMessages(); } catch (Throwable e) { log.error("Unexpected error running " + getWorkerName() + ", restarting", e); <START> } <END> } }</code><technical_language>if echo instance drops out of discovery, subscriptions stop / no-op</technical_language>

Target:
public void run() { log.info("Starting " + getWorkerName()); initializeQueue(); while (true) { try { listenForMessages(); } catch (QueueDoesNotExistException e){ log.warn("Queue does not exist, recreating", queueARN); initializeQueue(); } catch (Exception e) { log.error("Unexpected error running " + getWorkerName() + ", restarting worker", e); try { Thread.sleep(500); } catch (InterruptedException e1) { log.error("Thread interrupted while sleeping", getWorkerName(), e1); } } } }
Source:
<code>private void logAndCheckSkipTest(IllegalStateException e) { <START> LOGGER.error("Cannot initial a docker container because: {}", String.valueOf(e)); <END> if (e.getMessage().startsWith(NO_DOCKER_ENVIRONMENT)) { Assume.assumeTrue(SKIPPING_TEST_CAUTION, false); } }</code><technical_language>LOGGER.error("Cannot initial a docker container", e); ;-)</technical_language>

Target:
private void logAndCheckSkipTest(IllegalStateException e) { LOGGER.error("Cannot initial a docker container", e); if (e.getMessage().startsWith(NO_DOCKER_ENVIRONMENT)) { Assume.assumeTrue(SKIPPING_TEST_CAUTION, false); } }
Source:
<code>public ChangeInfo get() throws RestApiException { String version = getVersion(); <START> Set<ListChangesOption> options = EnumSet.allOf(ListChangesOption.class) <END> .stream() .filter(option -> ListChangesOptionByVersion.isSupportedOnVersion(option, version)) .filter(option -> option != ListChangesOption.CHECK) .collect(Collectors.toSet()); EnumSet enumOption = EnumSet.noneOf(ListChangesOption.class); enumOption.addAll(options); return get(enumOption); }</code><technical_language>extract this logic a method in ListChangesOptionByVersion</technical_language>

Target:
public ChangeInfo get() throws RestApiException { return get(ListChangesOptionByVersion.allSupported(serverRestClient.getVersionCached())); }
Source:
<code>public void init() { super.init(); setStorageDomainId(getDiskImage().getStorageIds().get(0)); setStoragePoolId(getDiskImage().getStoragePoolId()); setImageGroupId(getDiskImage().getId()); setVm(vmDao .getVmsWithPlugInfo(getDiskImage().getId()) .stream() .filter(p -> <START> p.getFirst().getStatus() != VMStatus.Down) <END> .filter(p -> p.getSecond().isPlugged()) .map(Pair::getFirst) .findFirst() .orElse(null)); if (getVm() != null) { setVdsId(getVm().getRunOnVds()); } }</code><technical_language>want isRunning? so: p.getFirst().getStatus().isRunning() I assume want filteout VMs Suspended status well</technical_language>

Target:
public void init() { super.init(); setStorageDomainId(getDiskImage().getStorageIds().get(0)); setStoragePoolId(getDiskImage().getStoragePoolId()); setImageGroupId(getDiskImage().getId()); setVm(vmDao .getVmsWithPlugInfo(getDiskImage().getId()) .stream() .filter(p -> p.getFirst().getStatus().isRunning()) .filter(p -> p.getSecond().isPlugged()) .map(Pair::getFirst) .findFirst() .orElse(null)); if (getVm() != null) { setVdsId(getVm().getRunOnVds()); } }
Source:
<code><START> public static @NotNull Map<String, String> sanitizeException(@Nullable Throwable t) <END> { return ImmutableMap.of( "error", t == null ? "null" : (t.getMessage() == null ? t.toString() : t.getMessage()) ); }</code><technical_language>@NotNull means ? thought is default</technical_language>

Target:
public static Map<String, String> sanitizeException(@Nullable Throwable t) { return ImmutableMap.of( "error", t == null ? "null" : (t.getMessage() == null ? t.toString() : t.getMessage()) ); }
Source:
<code>public void abort(String reason, Throwable cause) { <START> synchronized (this) { <END> if (abortRequested) { LOG.debug( "Abort already in progress. Ignoring the current request with reason: {}", reason); return; } setAbortRequested(); } String msg = "***** ABORTING region server " + this + ": " + reason + " *****"; if (cause != null) { LOG.error(HBaseMarkers.FATAL, msg, cause); } else { LOG.error(HBaseMarkers.FATAL, msg); } LOG.error(HBaseMarkers.FATAL, "RegionServer abort: loaded coprocessors are: " + CoprocessorHost.getLoadedCoprocessors()); try { LOG.info("Dump of metrics as JSON on abort: " + DumpRegionServerMetrics.dumpMetrics()); } catch (MalformedObjectNameException | IOException e) { LOG.warn("Failed dumping metrics", e); } try { if (cause != null) { msg += "\nCause:\n" + Throwables.getStackTraceAsString(cause); } RegionServerStatusService.BlockingInterface rss = rssStub; if (rss != null && this.serverName != null) { ReportRSFatalErrorRequest.Builder builder = ReportRSFatalErrorRequest.newBuilder(); builder.setServer(ProtobufUtil.toServerName(this.serverName)); builder.setErrorMessage(msg); rss.reportRSFatalError(null, builder.build()); } } catch (Throwable t) { LOG.warn("Unable to report fatal error to master", t); } scheduleAbortTimer(); stop(reason, true, null); }</code><technical_language>AtomicBoolean CAS is enough</technical_language>

Target:
public void abort(String reason, Throwable cause) { if (!setAbortRequested()) { LOG.debug( "Abort already in progress. Ignoring the current request with reason: {}", reason); return; } String msg = "***** ABORTING region server " + this + ": " + reason + " *****"; if (cause != null) { LOG.error(HBaseMarkers.FATAL, msg, cause); } else { LOG.error(HBaseMarkers.FATAL, msg); } LOG.error(HBaseMarkers.FATAL, "RegionServer abort: loaded coprocessors are: " + CoprocessorHost.getLoadedCoprocessors()); try { LOG.info("Dump of metrics as JSON on abort: " + DumpRegionServerMetrics.dumpMetrics()); } catch (MalformedObjectNameException | IOException e) { LOG.warn("Failed dumping metrics", e); } try { if (cause != null) { msg += "\nCause:\n" + Throwables.getStackTraceAsString(cause); } RegionServerStatusService.BlockingInterface rss = rssStub; if (rss != null && this.serverName != null) { ReportRSFatalErrorRequest.Builder builder = ReportRSFatalErrorRequest.newBuilder(); builder.setServer(ProtobufUtil.toServerName(this.serverName)); builder.setErrorMessage(msg); rss.reportRSFatalError(null, builder.build()); } } catch (Throwable t) { LOG.warn("Unable to report fatal error to master", t); } scheduleAbortTimer(); stop(reason, true, null); }
Source:
<code>public void prepareSplitsForEpoch() { trainingDataSplits.clear(); final Set<K> keys = memoryStore.getAll().keySet(); final int sizeOfTrainingDataSplit = keys.size() / numMiniBatchesPerEpoch; int splitIndex = 0; <START> for (final K key : keys) { <END> if (trainingDataSplits.size() < splitIndex + 1) { trainingDataSplits.add(new ArrayList()); } trainingDataSplits.get(splitIndex).add(key); if (trainingDataSplits.get(splitIndex).size() == sizeOfTrainingDataSplit && (splitIndex + 1) < numMiniBatchesPerEpoch) { splitIndex++; } } currentMiniBatch = 0; }</code><technical_language>reason round-robin? put a number of keys split once</technical_language>

Target:
public void prepareSplitsForEpoch() { trainingDataSplits.clear(); final Set<K> keys = memoryStore.getAll().keySet(); final int sizeOfTrainingDataSplit = keys.size() / numMiniBatchesPerEpoch; final int numberOfSplitsToTakeExtra = keys.size() % numMiniBatchesPerEpoch; List<K> currentSplitList = null; int splitSize = 0; for (final K key : keys) { if (currentSplitList == null) { final int splitIndex = trainingDataSplits.size(); trainingDataSplits.add(new ArrayList<>()); currentSplitList = trainingDataSplits.get(splitIndex); splitSize = splitIndex < numberOfSplitsToTakeExtra ? sizeOfTrainingDataSplit + 1 : sizeOfTrainingDataSplit; } currentSplitList.add(key); if (currentSplitList.size() == splitSize) { currentSplitList = null; } } trainingDataSplitsIterator = trainingDataSplits.iterator(); }
Source:
<code><START> public void testReferenceSourceUpperCasesBases() throws NoSuchAlgorithmException, IOException { <END> final String sequenceName = "1"; final String nonIupacCharacters = "1=eE"; final byte[] originalRefBases = (nonIupacCharacters+SequenceUtil.IUPAC_CODES_STRING).getBytes(); SAMSequenceRecord sequenceRecord = new SAMSequenceRecord(sequenceName, originalRefBases.length); InMemoryReferenceSequenceFile memoryReferenceSequenceFile = new InMemoryReferenceSequenceFile(); memoryReferenceSequenceFile.add(sequenceName, Arrays.copyOf(originalRefBases, originalRefBases.length)); Assert.assertEquals(memoryReferenceSequenceFile.getSequence(sequenceName).getBases(), originalRefBases); ReferenceSource referenceSource = new ReferenceSource(memoryReferenceSequenceFile); byte[] refBasesFromSource = referenceSource.getReferenceBases(sequenceRecord, false); Assert.assertNotEquals(refBasesFromSource, originalRefBases); Assert.assertEquals(refBasesFromSource, SequenceUtil.upperCase(originalRefBases)); }</code><technical_language>throws clauses imports unused</technical_language>

Target:
public void testReferenceSourceUpperCasesBases() { final String sequenceName = "1"; final String nonIupacCharacters = "1=eE"; final byte[] originalRefBases = (nonIupacCharacters + SequenceUtil.getIUPACCodesString()).getBytes(); SAMSequenceRecord sequenceRecord = new SAMSequenceRecord(sequenceName, originalRefBases.length); InMemoryReferenceSequenceFile memoryReferenceSequenceFile = new InMemoryReferenceSequenceFile(); memoryReferenceSequenceFile.add(sequenceName, Arrays.copyOf(originalRefBases, originalRefBases.length)); Assert.assertEquals(memoryReferenceSequenceFile.getSequence(sequenceName).getBases(), originalRefBases); ReferenceSource referenceSource = new ReferenceSource(memoryReferenceSequenceFile); byte[] refBasesFromSource = referenceSource.getReferenceBases(sequenceRecord, false); Assert.assertNotEquals(refBasesFromSource, originalRefBases); Assert.assertEquals(refBasesFromSource, SequenceUtil.upperCase(originalRefBases)); }
Source:
<code>public void testHidingTags() throws ApiException { ApiClient client = getAdminWebClient(); ContainersApi containersApi = new ContainersApi(client); DockstoreTool c = containersApi.getContainerByToolPath(REGISTRY_HUB_DOCKER_COM_SEQWARE_SEQWARE, null); <START> assertEquals("should see one tag as an admin, saw " + c.getWorkflowVersions().size(), 2, c.getWorkflowVersions().size()); <END> ApiClient muggleClient = getWebClient(); ContainersApi muggleContainersApi = new ContainersApi(muggleClient); final DockstoreTool registeredContainer = muggleContainersApi.getPublishedContainer(c.getId(), null); assertEquals("should see no tags as a regular user, saw " + registeredContainer.getWorkflowVersions().size(), 1, registeredContainer.getWorkflowVersions().size()); }</code><technical_language>error message mismatch</technical_language>

Target:
public void testHidingTags() throws ApiException { ApiClient client = getAdminWebClient(); ContainersApi containersApi = new ContainersApi(client); DockstoreTool c = containersApi.getContainerByToolPath(REGISTRY_HUB_DOCKER_COM_SEQWARE_SEQWARE, null); assertEquals("should see all tags even if hidden as an admin", 2, c.getWorkflowVersions().size()); ApiClient muggleClient = getWebClient(); ContainersApi muggleContainersApi = new ContainersApi(muggleClient); final DockstoreTool registeredContainer = muggleContainersApi.getPublishedContainer(c.getId(), null); assertEquals("should only see non-hidden tags as a regular user", 1, registeredContainer.getWorkflowVersions().size()); }
Source:
<code>public void streamerRespectsMaxMessageSize() { InternalDistributedMember member1; member1 = new InternalDistributedMember("localhost", 1234); DistributionMessage message = new SerialAckedMessage(); message.setRecipients(Arrays.asList(member1)); when(connection1.getRemoteAddress()).thenReturn(member1); when(connection1.getRemoteVersion()).thenReturn(KnownVersion.CURRENT); <START> when(connection1.getSendBufferSize()).thenReturn(Connection.MAX_MSG_SIZE * 2); <END> List<Connection> connections = Arrays.asList(connection1); final BaseMsgStreamer msgStreamer = MsgStreamer.create(connections, message, false, stats, pool); assertThat(((MsgStreamer) msgStreamer).getBuffer().capacity()) .isEqualTo(Connection.MAX_MSG_SIZE); }</code><technical_language>This test stronger if requested message size MAX_MSG_SIZE + 1. stands this test allows a lot of wiggle-room for implementation</technical_language>

Target:
public void streamerRespectsMaxMessageSize() { InternalDistributedMember member1; member1 = new InternalDistributedMember("localhost", 1234); DistributionMessage message = new SerialAckedMessage(); message.setRecipients(Arrays.asList(member1)); when(connection1.getRemoteAddress()).thenReturn(member1); when(connection1.getRemoteVersion()).thenReturn(KnownVersion.CURRENT); when(connection1.getSendBufferSize()).thenReturn(Connection.MAX_MSG_SIZE + 1); List<Connection> connections = Arrays.asList(connection1); final BaseMsgStreamer msgStreamer = MsgStreamer.create(connections, message, false, stats, pool); assertThat(((MsgStreamer) msgStreamer).getBuffer().capacity()) .isEqualTo(Connection.MAX_MSG_SIZE); }
Source:
<code>public BlobDownloadResponse downloadWithResponse(OutputStream stream, BlobRange range, DownloadRetryOptions options, BlobRequestConditions requestConditions, boolean getRangeContentMd5, Duration timeout, Context context) { <START> Context updatedContext = context == null ? Context.NONE.addData(CoreConstants.DISABLE_BUFFER_COPY, true) : context.addData(CoreConstants.DISABLE_BUFFER_COPY, true); <END> StorageImplUtils.assertNotNull("stream", stream); Mono<BlobDownloadResponse> download = client .downloadWithResponse(range, options, requestConditions, getRangeContentMd5, updatedContext) .flatMap(response -> response.getValue().reduce(stream, (outputStream, buffer) -> { try { outputStream.write(FluxUtil.byteBufferToArray(buffer)); return outputStream; } catch (IOException ex) { throw logger.logExceptionAsError(Exceptions.propagate(new UncheckedIOException(ex))); } }).thenReturn(new BlobDownloadResponse(response))); return blockWithOptionalTimeout(download, timeout); }</code><technical_language>this kind of repetitive (and verbose) code moved a utility method</technical_language>

Target:
public BlobDownloadResponse downloadWithResponse(OutputStream stream, BlobRange range, DownloadRetryOptions options, BlobRequestConditions requestConditions, boolean getRangeContentMd5, Duration timeout, Context context) { StorageImplUtils.assertNotNull("stream", stream); Mono<BlobDownloadResponse> download = client .downloadWithResponse(range, options, requestConditions, getRangeContentMd5, context) .flatMap(response -> response.getValue().reduce(stream, (outputStream, buffer) -> { try { outputStream.write(FluxUtil.byteBufferToArray(buffer)); return outputStream; } catch (IOException ex) { throw logger.logExceptionAsError(Exceptions.propagate(new UncheckedIOException(ex))); } }).thenReturn(new BlobDownloadResponse(response))); return blockWithOptionalTimeout(download, timeout); }
Source:
<code>public List<SecurityTeam> getSecurityTeams(PerunSession sess) throws PrivilegeException, InternalErrorException { Utils.checkPerunSession(sess); if (AuthzResolverBlImpl.isAuthorized(sess, Role.PERUNADMIN) || <START> AuthzResolver.isAuthorized(sess, Role.PERUNOBSERVER)) { <END> return getSecurityTeamsManagerBl().getAllSecurityTeams(sess); } else if (AuthzResolverBlImpl.isAuthorized(sess, Role.SECURITYADMIN)) { List<SecurityTeam> securityTeams = new ArrayList<>(); for (PerunBean st: AuthzResolver.getComplementaryObjectsForRole(sess, Role.SECURITYADMIN, SecurityTeam.class)) { securityTeams.add((SecurityTeam) st); } return securityTeams; } else { throw new PrivilegeException("getSecurityTeams"); } }</code><technical_language>remove "PERUNADMIN", if is method 'isAuthorized' called PerunAdmin (with parameters) return true. testing for PERUNOBSERVER PERUNADMIN get data</technical_language>

Target:
public List<SecurityTeam> getSecurityTeams(PerunSession sess) throws PrivilegeException, InternalErrorException { Utils.checkPerunSession(sess); if (AuthzResolver.isAuthorized(sess, Role.PERUNOBSERVER)) { return getSecurityTeamsManagerBl().getAllSecurityTeams(sess); } else if (AuthzResolver.isAuthorized(sess, Role.SECURITYADMIN)) { List<SecurityTeam> securityTeams = new ArrayList<>(); for (PerunBean st: AuthzResolver.getComplementaryObjectsForRole(sess, Role.SECURITYADMIN, SecurityTeam.class)) { securityTeams.add((SecurityTeam) st); } return securityTeams; } else { throw new PrivilegeException("getSecurityTeams"); } }
Source:
<code><START> private void outputProcedures(Configuration config) { <END> File outputFile = new File(config.m_getOutput); if (outputFile.exists() && !config.m_forceGetCreate) { System.err.println("FATAL: Failed to save classes, file already exists: " + config.m_getOutput); VoltDB.exit(-1); } try { InMemoryJarfile catalogJar = CatalogUtil.loadInMemoryJarFile(MiscUtils.fileToBytes(new File (config.m_pathToCatalog))); InMemoryJarfile filteredJar = CatalogUtil.getClassesFromJar(catalogJar); filteredJar.writeToFile(outputFile); System.out.println("Classes file in jar file saved at " + outputFile.getPath()); } catch (IOException e) { System.err.println("FATAL: Failed to read classes " + config.m_pathToCatalog + " : " + e.getMessage()); VoltDB.exit(-1); } }</code><technical_language>a big fan of internal methods calling System.exit(-1) logging printing out stderr. time real voltdb is in play loggers I encourage use. for system exit this method return a status invoker main method react a system exit</technical_language>

Target:
private int outputProcedures(Configuration config) { File outputFile = new File(config.m_getOutput); if (outputFile.exists() && !config.m_forceGetCreate) { consoleLog.fatal("Failed to save classes, file already exists: " + config.m_getOutput); return -1; } try { InMemoryJarfile catalogJar = CatalogUtil.loadInMemoryJarFile(MiscUtils.fileToBytes(new File (config.m_pathToCatalog))); InMemoryJarfile filteredJar = CatalogUtil.getCatalogJarWithoutDefaultArtifacts(catalogJar); filteredJar.writeToFile(outputFile); consoleLog.info("Classes file in jar file saved at " + outputFile.getPath()); } catch (IOException e) { consoleLog.fatal("Failed to read classes " + config.m_pathToCatalog + " : " + e.getMessage()); return -1; } return 0; }
Source:
<code>private void runInitScriptIfRequired(final ConnectionUrl connectionUrl, DatabaseDelegate databaseDelegate) throws SQLException { if (connectionUrl.getInitScriptPath().isPresent()) { String initScriptPath = connectionUrl.getInitScriptPath().get(); try { URL resource; if (initScriptPath.startsWith("file:")) { <START> String relativePath = System.getProperty("user.dir") + "/" + initScriptPath.substring(5); <END> resource = new File(relativePath).toURI().toURL(); } else { resource = Thread.currentThread().getContextClassLoader().getResource(initScriptPath); } if (resource == null) { LOGGER.warn("Could not load classpath init script: {}", initScriptPath); throw new SQLException("Could not load classpath init script: " + initScriptPath + ". Resource not found."); } String sql = IOUtils.toString(resource, StandardCharsets.UTF_8); ScriptUtils.executeDatabaseScript(databaseDelegate, initScriptPath, sql); } catch (IOException e) { LOGGER.warn("Could not load classpath init script: {}", initScriptPath); throw new SQLException("Could not load classpath init script: " + initScriptPath, e); } catch (ScriptException e) { LOGGER.error("Error while executing init script: {}", initScriptPath, e); throw new SQLException("Error while executing init script: " + initScriptPath, e); } } }</code><technical_language>put "file:" a constant initScriptPath.substring(FILE_PATH_PREFIX.length());</technical_language>

Target:
private void runInitScriptIfRequired(final ConnectionUrl connectionUrl, DatabaseDelegate databaseDelegate) throws SQLException { if (connectionUrl.getInitScriptPath().isPresent()) { String initScriptPath = connectionUrl.getInitScriptPath().get(); try { URL resource = Thread.currentThread().getContextClassLoader().getResource(initScriptPath); if (resource == null) { LOGGER.warn("Could not load classpath init script: {}", initScriptPath); throw new SQLException("Could not load classpath init script: " + initScriptPath + ". Resource not found."); } String sql = IOUtils.toString(resource, StandardCharsets.UTF_8); ScriptUtils.executeDatabaseScript(databaseDelegate, initScriptPath, sql); } catch (IOException e) { LOGGER.warn("Could not load classpath init script: {}", initScriptPath); throw new SQLException("Could not load classpath init script: " + initScriptPath, e); } catch (ScriptException e) { LOGGER.error("Error while executing init script: {}", initScriptPath, e); throw new SQLException("Error while executing init script: " + initScriptPath, e); } } }
Source:
<code>private void refreshIdleConsumerGroupOffset() { Map<String, KafkaFuture<ConsumerGroupDescription>> consumerGroupsDesc = targetAdminClient .describeConsumerGroups(consumerGroups).describedGroups(); for (String group : consumerGroups) { try { if (consumerGroupsDesc.get(group) == null) { newConsumerGroup.add(group); continue; } ConsumerGroupDescription consumerGroupDesc = consumerGroupsDesc.get(group).get(); <START> if (consumerGroupDesc.state().equals(ConsumerGroupState.EMPTY)) { <END> idleConsumerGroupsOffset.put(group, targetAdminClient.listConsumerGroupOffsets(group) .partitionsToOffsetAndMetadata().get().entrySet()); } } catch (InterruptedException | ExecutionException e) { log.error("Error querying for consumer group on cluster {}.", group, targetClusterAlias, e); } } }</code><technical_language>include group state DEAD? New groups in source cluster dead in target cluster</technical_language>

Target:
private void refreshIdleConsumerGroupOffset() { Map<String, KafkaFuture<ConsumerGroupDescription>> consumerGroupsDesc = targetAdminClient .describeConsumerGroups(consumerGroups).describedGroups(); for (String group : consumerGroups) { try { ConsumerGroupDescription consumerGroupDesc = consumerGroupsDesc.get(group).get(); ConsumerGroupState consumerGroupState = consumerGroupDesc.state(); if (consumerGroupState.equals(ConsumerGroupState.EMPTY)) { idleConsumerGroupsOffset.put(group, targetAdminClient.listConsumerGroupOffsets(group) .partitionsToOffsetAndMetadata().get().entrySet().stream().collect( Collectors.toMap(e -> e.getKey(), e -> e.getValue()))); } } catch (InterruptedException | ExecutionException e) { log.error("Error querying for consumer group on cluster {}.", group, targetClusterAlias, e); } } }
Source:
<code>public void refreshExtendedPermissions() { if (getDataManager() != null) { try { Collection<Map<String, Long>> databaseGroupPermissions = <START> getDataManager().getPermissions("Group", getBaseClassName()); <END> clearGroupItems(); for (Map<String, Long> groupPermission : databaseGroupPermissions) { getGroupItems(groupPermission.get("groupId")).add(groupPermission.get(getBaseClassIdName())); } Collection<Map<String, Long>> databaseDevicePermissions = getDataManager().getPermissions("Device", getBaseClassName()); Collection<Device> allDevices = Context.getDeviceManager().getAllDevices(); clearDeviceItems(); deviceItemsWithGroups.clear(); for (Map<String, Long> devicePermission : databaseDevicePermissions) { getDeviceItems(devicePermission.get("deviceId")).add(devicePermission.get(getBaseClassIdName())); getAllDeviceItems(devicePermission.get("deviceId")).add(devicePermission.get(getBaseClassIdName())); } for (Device device : allDevices) { long groupId = device.getGroupId(); while (groupId != 0) { getAllDeviceItems(device.getId()).addAll(getGroupItems(groupId)); if (Context.getDeviceManager().getGroupById(groupId) != null) { groupId = Context.getDeviceManager().getGroupById(groupId).getGroupId(); } else { groupId = 0; } } } } catch (SQLException error) { Log.warning(error); } } }</code><technical_language>constants for names well</technical_language>

Target:
public void refreshExtendedPermissions() { if (getDataManager() != null) { try { Collection<Map<String, Long>> databaseGroupPermissions = getDataManager().getPermissions(Group.class, getBaseClass()); clearGroupItems(); for (Map<String, Long> groupPermission : databaseGroupPermissions) { getGroupItems(groupPermission.get(DataManager.makeNameId(Group.class))) .add(groupPermission.get(getBaseClassIdName())); } Collection<Map<String, Long>> databaseDevicePermissions = getDataManager().getPermissions(Device.class, getBaseClass()); Collection<Device> allDevices = Context.getDeviceManager().getAllDevices(); clearDeviceItems(); deviceItemsWithGroups.clear(); for (Map<String, Long> devicePermission : databaseDevicePermissions) { getDeviceItems(devicePermission.get(DataManager.makeNameId(Device.class))) .add(devicePermission.get(getBaseClassIdName())); getAllDeviceItems(devicePermission.get(DataManager.makeNameId(Device.class))) .add(devicePermission.get(getBaseClassIdName())); } for (Device device : allDevices) { long groupId = device.getGroupId(); while (groupId != 0) { getAllDeviceItems(device.getId()).addAll(getGroupItems(groupId)); if (Context.getDeviceManager().getGroupById(groupId) != null) { groupId = Context.getDeviceManager().getGroupById(groupId).getGroupId(); } else { groupId = 0; } } } } catch (SQLException error) { Log.warning(error); } } }
Source:
<code>private void <START> addAttribute(AttributesImpl attribute, <END> String key, String value) { attribute.addAttribute("", key, key, "", org.eclipse.mylyn.internal.commons.core.XmlStringConverter.convertToXmlString(value)); }</code><technical_language>nit: a bit weird passing implementation type. Is a reason interface</technical_language>

Target:
private void addAttribute(AttributesImpl attribute, String key, String value) { attribute.addAttribute("", key, key, "", value); }
Source:
<code>public void close() { <START> final State oldState = state; <END> try { synchronized (lock) { state = State.DONE; if (yielder != null) { Yielder<Object[]> theYielder = this.yielder; this.yielder = null; yielderOpenCloseExecutor.submit( () -> { theYielder.close(); return null; } ).get(); yielderOpenCloseExecutor.shutdownNow(); } } } catch (Throwable t) { if (oldState != State.DONE) { try { onClose.run(); } catch (Throwable t1) { t.addSuppressed(t1); } } throw Throwables.propagate(t); } if (oldState != State.DONE) { try { onClose.run(); } catch (Throwable t) { throw Throwables.propagate(t); } } }</code><technical_language>State oldState = state assignment happen synchronized (lock), unsafe read. changes close() needed, synchronization DruidConnection.statements removed onClose</technical_language>

Target:
public void close() { State oldState = null; try { synchronized (lock) { oldState = state; state = State.DONE; if (yielder != null) { Yielder<Object[]> theYielder = this.yielder; this.yielder = null; yielderOpenCloseExecutor.submit( () -> { theYielder.close(); return null; } ).get(); yielderOpenCloseExecutor.shutdownNow(); } } } catch (Throwable t) { if (oldState != State.DONE) { try { onClose.run(); sqlLifecycle.emitLogsAndMetrics(t, null, -1); } catch (Throwable t1) { t.addSuppressed(t1); } } throw Throwables.propagate(t); } if (oldState != State.DONE) { try { if (!(this.throwable instanceof ForbiddenException)) { sqlLifecycle.emitLogsAndMetrics(this.throwable, null, -1); } onClose.run(); } catch (Throwable t) { throw Throwables.propagate(t); } } }
Source:
<code>protected void createCacheConf(final ColumnFamilyDescriptor family) { <START> this.cacheConf = new CacheConfig(conf, family, region.getRegionInfo(), region.getBlockCache(), <END> region.getRegionServicesForStores().getByteBuffAllocator()); }</code><technical_language>Ya this is some avoid</technical_language>

Target:
protected void createCacheConf(final ColumnFamilyDescriptor family) { this.cacheConf = new CacheConfig(conf, family, region.getBlockCache(), region.getRegionServicesForStores().getByteBuffAllocator()); LOG.info("Created cacheConfig: " + this.getCacheConfig() + " for " + this); }