auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>void setData(List<List<String>> listOfGroups) { this.listOfGroups.clear(); <START> this.listOfGroups = listOfGroups; <END> notifyDataSetChanged(); delegate.setNoGroup(); }</code><technical_language>point clearing list if drop assign reference a new one. conserve memory allocation. suggestion this.listOfGroups.addAll(listOfGroups);</technical_language>

Target:
void setData(List<List<String>> listOfGroups) { this.listOfGroups.clear(); this.listOfGroups.addAll(listOfGroups); notifyDataSetChanged(); }
Source:
<code>private void writeMessageToPartition(final int partition) throws InterruptedException, ExecutionException { final KafkaProducer<String, String> producer = kafkaHelper.createProducer(); final ProducerRecord<String, String> producerRecord = new ProducerRecord<>(TEST_TOPIC, partition, "blah_key", <START> "blah_value"); <END> producer.send(producerRecord).get(); }</code><technical_language>overworked a bit :)</technical_language>

Target:
private void writeMessageToPartition(final int partition) throws InterruptedException, ExecutionException { final KafkaProducer<String, String> producer = kafkaHelper.createProducer(); final ProducerRecord<String, String> producerRecord = new ProducerRecord<>(TEST_TOPIC, partition, "blahKey", "blahValue"); producer.send(producerRecord).get(); }
Source:
<code><START> public boolean canPushMerges() { <END> return projectControl.controlForRef(getRefName()).canPerform( Permission.PUSH_MERGE) && canWrite(); }</code><technical_language>Do logic here. if push merge plain ref: OK else if push merge 'refs/for/ + plain ref OK else fail</technical_language>

Target:
public boolean canPushMerges() { if (projectControl.controlForRef(getRefName()).canPerform( Permission.PUSH_MERGE) && canWrite()) { return true; } else if (projectControl.controlForRef( MagicBranch.NEW_CHANGE + getRefName()) .canPerform(Permission.PUSH_MERGE) && canWrite()) { return true; } return false; }
Source:
<code>private Request makeRequest(@Nonnull String type, @Nonnull String sparql, @Nullable String accept) { Request post = httpClient.newRequest(uri); post.method(POST); if (!timeout.isNegative() || <START> timeout.isZero()) { <END> post.timeout(timeout.toMillis(), MILLISECONDS); } if (accept != null) { post.header("Accept", accept); } final Fields fields = new Fields(); fields.add(type, sparql); final FormContentProvider form = new FormContentProvider(fields, UTF_8); post.content(form); return post; }</code><technical_language>settng timeout is zero? zero non-negative anyway</technical_language>

Target:
private Request makeRequest(@Nonnull String type, @Nonnull String sparql, @Nullable String accept) { Request post = httpClient.newRequest(uri); post.method(POST); if (!(timeout.isNegative() || timeout.isZero())) { post.timeout(timeout.toMillis(), MILLISECONDS); } if (accept != null) { post.header("Accept", accept); } final Fields fields = new Fields(); fields.add(type, sparql); final FormContentProvider form = new FormContentProvider(fields, UTF_8); post.content(form); return post; }
Source:
<code>public Set<String> getInvalidActiveSenses(@Scope(OAuthScope.ADMINISTRATION_READ) final AccessToken accessToken, @QueryParam("start_ts") final Long startTs, @QueryParam("end_ts") final Long endTs) { if (startTs == null || endTs == null) { throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST) .entity("Require start_ts & end_ts").build()); } final Jedis jedis = jedisPool.getResource(); final Set<String> allSeenSenses = new HashSet<>(); final Set<String> allValidSeenSenses = new HashSet<>(); try { <START> allSeenSenses.addAll(jedis.zrangeByScore(ActiveDevicesTrackerConfiguration.ALL_DEVICES_SEEN_SET_KEY, startTs, endTs)); <END> allValidSeenSenses.addAll(jedis.zrangeByScore(ActiveDevicesTrackerConfiguration.SENSE_ACTIVE_SET_KEY, startTs, endTs)); } catch (Exception e) { LOGGER.error("Failed retrieving fw history for device.", e.getMessage()); } finally { jedisPool.returnResource(jedis); } allSeenSenses.removeAll(allValidSeenSenses); return allSeenSenses; }</code><technical_language>a Redis.Pipe here. do in connection instead of two</technical_language>

Target:
public Set<String> getInvalidActiveSenses(@Scope(OAuthScope.ADMINISTRATION_READ) final AccessToken accessToken, @QueryParam("start_ts") final Long startTs, @QueryParam("end_ts") final Long endTs) { if (startTs == null || endTs == null) { throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST) .entity("Require start_ts & end_ts").build()); } final Jedis jedis = jedisPool.getResource(); final Set<String> allSeenSenses = new HashSet<>(); final Set<String> allValidSeenSenses = new HashSet<>(); try { final Pipeline pipe = jedis.pipelined(); final redis.clients.jedis.Response<Set<String>> allDevs = pipe.zrangeByScore(ActiveDevicesTrackerConfiguration.ALL_DEVICES_SEEN_SET_KEY, startTs, endTs); final redis.clients.jedis.Response<Set<String>> allValid = pipe.zrangeByScore(ActiveDevicesTrackerConfiguration.SENSE_ACTIVE_SET_KEY, startTs, endTs); pipe.sync(); allSeenSenses.addAll(allDevs.get()); allValidSeenSenses.addAll(allValid.get()); } catch (Exception e) { LOGGER.error("Failed retrieving invalid active senses.", e.getMessage()); } finally { jedisPool.returnResource(jedis); } allSeenSenses.removeAll(allValidSeenSenses); return allSeenSenses; }
Source:
<code>public SWTGridDescription getGridDescription(SWTGridDescription gridDescription) { if (rendererGridDescription == null) { rendererGridDescription = GridDescriptionFactory.INSTANCE.createSimpleGrid(1, 2, this); final SWTGridCell label = rendererGridDescription.getGrid().get(0); label.setHorizontalGrab(false); label.setVerticalGrab(false); label.setVerticalFill(false); final Optional<Integer> labelWidth = getLabelWidth(); if (labelWidth.isPresent()) { <START> label.setPreferredSize(labelWidth.get(), SWT.DEFAULT); <END> } final SWTGridCell controls = rendererGridDescription.getGrid().get(1); controls.setVerticalGrab(false); controls.setVerticalFill(false); } return rendererGridDescription; }</code><technical_language>label a height this point</technical_language>

Target:
public SWTGridDescription getGridDescription(SWTGridDescription gridDescription) { if (rendererGridDescription == null) { rendererGridDescription = GridDescriptionFactory.INSTANCE.createSimpleGrid(1, 2, this); final SWTGridCell label = rendererGridDescription.getGrid().get(0); label.setHorizontalGrab(false); label.setVerticalGrab(false); label.setVerticalFill(false); final Optional<Integer> labelWidth = getLabelWidth(); if (labelWidth.isPresent()) { label.setPreferredSize( labelWidth.get(), label.getPreferredSize() == null ? SWT.DEFAULT : label.getPreferredSize().y); } final SWTGridCell controls = rendererGridDescription.getGrid().get(1); controls.setVerticalGrab(false); controls.setVerticalFill(false); } return rendererGridDescription; }
Source:
<code><START> public List<String> findAll() { <END> return encodings; }</code><technical_language>return List of Enumerations? this remove logic in constructor..</technical_language>

Target:
public List<Encoding> findAll() { return encodings; }
Source:
<code>public void testGenerateMapGeneratorPresent() { when(applicationContext.getBean(GenerateMapTask.class)).thenReturn(generateMapTask); instance.generateMap(testMapNameGenerator).join(); verify(taskService).submitTask(generateMapTask); verify(generateMapTask).setVersion(versionGeneratorPresent); verify(generateMapTask).setSeed(seed); <START> verify(generateMapTask).setGeneratorExecutableFile(fafDataDirectory.getRoot().toPath().resolve(MapGeneratorService.GENERATOR_EXECUTABLE_SUB_DIRECTORY).resolve(String.format(MapGeneratorService.getGENERATOR_EXECUTABLE_FILENAME(), versionGeneratorPresent)).toFile()); <END> verify(generateMapTask).setMapFilename(testMapNameGenerator); verifyNoMoreInteractions(taskService); }</code><technical_language>Split readable</technical_language>

Target:
public void testGenerateMapGeneratorPresent() throws Exception { when(applicationContext.getBean(GenerateMapTask.class)).thenReturn(generateMapTask); String mapName = instance.generateMap(testMapNameGenerator).get(); assertThat(mapName, equalTo(testMapNameGenerator)); verify(taskService).submitTask(generateMapTask); verify(generateMapTask).setVersion(versionGeneratorPresent); verify(generateMapTask).setSeed(seed); verify(generateMapTask).setMapFilename(testMapNameGenerator); String generatorExecutableName = String.format(MapGeneratorService.getGENERATOR_EXECUTABLE_FILENAME(), versionGeneratorPresent); verify(generateMapTask).setGeneratorExecutableFile(fafDataDirectory.getRoot().toPath().resolve(MapGeneratorService.GENERATOR_EXECUTABLE_SUB_DIRECTORY).resolve(generatorExecutableName).toFile()); verifyNoMoreInteractions(taskService); }
Source:
<code>void shutdown(final boolean clean) { final AtomicReference<RuntimeException> firstException = new AtomicReference<>(null); final Iterator<Task> iterator = tasks.values().iterator(); while (iterator.hasNext()) { final Task task = iterator.next(); cleanupTask(task); if (clean) { try { task.closeClean(); } catch (final TaskMigratedException e) { task.closeDirty(); } catch (final RuntimeException e) { firstException.compareAndSet(null, e); task.closeDirty(); } } else { task.closeDirty(); } if (task.isActive()) { try { activeTaskCreator.closeAndRemoveTaskProducerIfNeeded(task.id()); } catch (final RuntimeException e) { if (clean) { firstException.compareAndSet(null, e); } else { <START> log.warn("Ignoring an exception while closing task producer.", e); <END> } } } iterator.remove(); } try { activeTaskCreator.closeThreadProducerIfNeeded(); } catch (final RuntimeException e) { if (clean) { firstException.compareAndSet(null, e); } else { log.warn("Ignoring an exception while closing thread producer.", e); } } final RuntimeException fatalException = firstException.get(); if (fatalException != null) { throw new RuntimeException("Unexpected exception while closing task", fatalException); } }</code><technical_language>Ditto error message</technical_language>

Target:
void shutdown(final boolean clean) { final AtomicReference<RuntimeException> firstException = new AtomicReference<>(null); final Iterator<Task> iterator = tasks.values().iterator(); while (iterator.hasNext()) { final Task task = iterator.next(); cleanupTask(task); if (clean) { try { task.closeClean(); } catch (final TaskMigratedException e) { task.closeDirty(); } catch (final RuntimeException e) { firstException.compareAndSet(null, e); task.closeDirty(); } } else { task.closeDirty(); } if (task.isActive()) { try { activeTaskCreator.closeAndRemoveTaskProducerIfNeeded(task.id()); } catch (final RuntimeException e) { if (clean) { firstException.compareAndSet(null, e); } else { log.warn("Ignoring an exception while closing task " + task.id() + " producer.", e); } } } iterator.remove(); } try { activeTaskCreator.closeThreadProducerIfNeeded(); } catch (final RuntimeException e) { if (clean) { firstException.compareAndSet(null, e); } else { log.warn("Ignoring an exception while closing thread producer.", e); } } final RuntimeException fatalException = firstException.get(); if (fatalException != null) { throw new RuntimeException("Unexpected exception while closing task", fatalException); } }
Source:
<code>private static FileOutputStream updateCertEntry(final String oldAlias, final String newAlias, Certificate certificate, final String storeLoc, final String passkey, KeyStore tstore) throws CertificateManagerException, IOException { FileOutputStream os = null; try { tstore.deleteEntry(oldAlias); os = new FileOutputStream(storeLoc); tstore.setCertificateEntry(newAlias, certificate); tstore.store(os, passkey.toCharArray()); } catch (final IOException | NoSuchAlgorithmException | CertificateException | KeyStoreException ex) { LOG.error("Unable to update the Certifiate: ", ex.getLocalizedMessage(), ex); throw new CertificateManagerException(ex.getMessage(), ex); } finally { <START> IOUtils.closeQuietly(os); <END> } return os; }</code><technical_language>Unsure if this change. returning actual stream in method. stream this method returns, if are, closing affect implementation</technical_language>

Target:
private static void updateCertEntry(final String oldAlias, final String newAlias, Certificate certificate, final String storeLoc, final String passkey, KeyStore tstore) throws CertificateManagerException { try (FileOutputStream os = new FileOutputStream(storeLoc)) { tstore.deleteEntry(oldAlias); tstore.setCertificateEntry(newAlias, certificate); tstore.store(os, passkey.toCharArray()); } catch (final IOException | NoSuchAlgorithmException | CertificateException | KeyStoreException ex) { LOG.error("Unable to update the Certifiate: ", ex.getLocalizedMessage(), ex); throw new CertificateManagerException(ex.getMessage(), ex); } }
Source:
<code>public void setup() { SWTBotUtils.openView(getViewID()); fViewBot = fBot.viewById(getViewID()); fViewBot.show(); Matcher<Chart> widgetOfType = WidgetOfType.widgetOfType(Chart.class); fChart = fViewBot.bot().widget(widgetOfType); fTrace = getTestTrace(); File file = new File(fTrace.getPath()); SWTBotUtils.openTrace(TRACE_PROJECT_NAME, file.getAbsolutePath(), fTrace.getTraceTypeId()); String analysisId = getAnalysisId(); if (analysisId != null) { IAnalysisModule module = <START> fTrace.getAnalysisModule(analysisId); <END> assertNotNull(module); module.schedule(); assertTrue(module.waitForCompletion()); } SWTBotUtils.activateEditor(fBot, fTrace.getName()); }</code><technical_language>I this returns null fTrace objects instances of CtfTmfTraceStubs this point, set of analysis modules is empty</technical_language>

Target:
public void setup() { SWTBotUtils.openView(getViewID()); fViewBot = fBot.viewById(getViewID()); fViewBot.show(); Matcher<Chart> widgetOfType = WidgetOfType.widgetOfType(Chart.class); fChart = fViewBot.bot().widget(widgetOfType); fTrace = getTestTrace(); File file = new File(fTrace.getPath()); SWTBotUtils.openTrace(TRACE_PROJECT_NAME, file.getAbsolutePath(), fTrace.getTraceTypeId()); String analysisId = getAnalysisId(); if (analysisId != null) { Set<@NonNull ITmfTrace> traces = TmfTraceManager.getInstance().getOpenedTraces(); ITmfTrace trace = Iterables.find(traces, t -> t.getName().equals(fTrace.getName())); IAnalysisModule module = trace.getAnalysisModule(analysisId); assertNotNull(module); module.schedule(); assertTrue(module.waitForCompletion()); } SWTBotUtils.activateEditor(fBot, fTrace.getName()); }
Source:
<code>protected static void addRange(Map<String,Map<KeyExtent,List<Range>>> binnedRanges, String location, KeyExtent ke, Range range) { <START> Map<KeyExtent,List<Range>> tablets = binnedRanges.computeIfAbsent(location, k -> new HashMap<>()); List<Range> tabletsRanges = tablets.computeIfAbsent(ke, k -> new ArrayList<>()); <END> tabletsRanges.add(range); }</code><technical_language>simplify to: java binnedRanges.computeIfAbsent(location, -> new HashMap<>()) .computeIfAbsent(ke, -> new ArrayList<>()) .add(range);</technical_language>

Target:
protected static void addRange(Map<String,Map<KeyExtent,List<Range>>> binnedRanges, String location, KeyExtent ke, Range range) { binnedRanges.computeIfAbsent(location, k -> new HashMap<>()) .computeIfAbsent(ke, k -> new ArrayList<>()).add(range); }
Source:
<code>private static Slice codePointsToSliceUtf8(List<Integer> codePoints) { int length = codePoints.stream() .mapToInt(SliceUtf8::lengthOfCodePoint) .sum(); byte[] result = new byte[length]; int offset = 0; for (int codePoint : codePoints) { <START> byte[] codePointUtf8 = SliceUtf8.codePointToUtf8(codePoint).getBytes(); <END> System.arraycopy(codePointUtf8, 0, result, offset, codePointUtf8.length); offset += codePointUtf8.length; } return Slices.wrappedBuffer(result); }</code><technical_language>lengthOfCodePoint setCodePointAt, instead? way, avoid intermediate slice, byte[] array copy</technical_language>

Target:
private static Slice codePointsToSliceUtf8(List<Integer> codePoints) { int length = codePoints.stream() .mapToInt(SliceUtf8::lengthOfCodePoint) .sum(); Slice result = Slices.wrappedBuffer(new byte[length]); int offset = 0; for (int codePoint : codePoints) { setCodePointAt(codePoint, result, offset); offset += lengthOfCodePoint(codePoint); } return result; }
Source:
<code>static zipkin.Span convert(Span span, Host host) { Builder zipkinSpan = new zipkin.Span.Builder(); Endpoint ep = Endpoint.create(host.getServiceName(), host.getIpv4(), host.getPort().shortValue()); <START> if (span.logs().isEmpty() && span.tags().isEmpty()) { <END> addLocalComponentAnnotation(span, zipkinSpan, ep); } else { ZipkinMessageListener.addZipkinAnnotations(zipkinSpan, span, ep); ZipkinMessageListener.addZipkinBinaryAnnotations(zipkinSpan, span, ep); } if (!spanContainsAnyZipkinConstant(span)) { addLocalComponentAnnotation(span, zipkinSpan, ep); } else if (spanContainsAnyZipkinClientConstantAndSaIsNotSet(span)) { addServerAddressAnnotation(zipkinSpan, ep); } zipkinSpan.timestamp(span.getBegin() * 1000); zipkinSpan.duration(span.getAccumulatedMillis() * 1000); zipkinSpan.traceId(span.getTraceId()); if (span.getParents().size() > 0) { if (span.getParents().size() > 1) { SamplingZipkinSpanIterator.log .debug("zipkin doesn't support spans with multiple parents. Omitting " + "other parents for " + span); } zipkinSpan.parentId(span.getParents().get(0)); } zipkinSpan.id(span.getSpanId()); if (StringUtils.hasText(span.getName())) { zipkinSpan.name(span.getName()); } return zipkinSpan.build(); }</code><technical_language>replace this test !spanContainsAnyZipkinConstant(span) reduce if statements</technical_language>

Target:
static zipkin.Span convert(Span span, Host host) { Builder zipkinSpan = new zipkin.Span.Builder(); Endpoint ep = Endpoint.create(host.getServiceName(), host.getIpv4(), host.getPort().shortValue()); if (notClientOrServer(span)) { ensureLocalComponent(span, zipkinSpan, ep); } ZipkinMessageListener.addZipkinAnnotations(zipkinSpan, span, ep); ZipkinMessageListener.addZipkinBinaryAnnotations(zipkinSpan, span, ep); if (hasClientSend(span)) { ensureServerAddr(span, zipkinSpan, ep); } zipkinSpan.timestamp(span.getBegin() * 1000); zipkinSpan.duration(span.getAccumulatedMillis() * 1000); zipkinSpan.traceId(span.getTraceId()); if (span.getParents().size() > 0) { if (span.getParents().size() > 1) { SamplingZipkinSpanIterator.log .debug("zipkin doesn't support spans with multiple parents. Omitting " + "other parents for " + span); } zipkinSpan.parentId(span.getParents().get(0)); } zipkinSpan.id(span.getSpanId()); if (StringUtils.hasText(span.getName())) { zipkinSpan.name(span.getName()); } return zipkinSpan.build(); }
Source:
<code>public void run () throws Exception { LOG.info("Periodically making an OTP2 Raptor TransitLayer from the TimetableSnapshot at intervals of seconds.", updateIntervalSeconds); while (true) { try { Thread.sleep(1000 * updateIntervalSeconds); <START> } catch (InterruptedException e) { Thread.currentThread().interrupt(); break; } <END> if (graph.timetableSnapshotSource != null) { final TimetableSnapshot timetableSnapshot = graph.timetableSnapshotSource.getTimetableSnapshot(); if (timetableSnapshot.hashCode() != lastSnapshotHashCode) { lastSnapshotHashCode = timetableSnapshot.hashCode(); final TransitLayer realtimeTransitLayer = TransitLayerMapper.map(graph); updaterManager.execute(g -> g.realtimeTransitLayer = realtimeTransitLayer); } } } }</code><technical_language>I this is hiding original interrupt, catch it</technical_language>

Target:
public void run () { LOG.info("Periodically making an OTP2 Raptor TransitLayer from the TimetableSnapshot at intervals of seconds.", updateIntervalSeconds); while (true) { try { Thread.sleep(1000 * updateIntervalSeconds); } catch (InterruptedException e) { Thread.currentThread().interrupt(); break; } final TimetableSnapshot timetableSnapshot = graph.getTimetableSnapshot(); if (timetableSnapshot != null) { if (timetableSnapshot.hashCode() != lastSnapshotHashCode) { lastSnapshotHashCode = timetableSnapshot.hashCode(); final TransitLayer realtimeTransitLayer = TransitLayerMapper.map(graph); updaterManager.execute(g -> g.realtimeTransitLayer = realtimeTransitLayer); } } } }
Source:
<code>public static Metric<Double> distinctValuesCount(String columnName) { return new Metric<Double>() { @Override public Optional<Double> getValueFromPlanNodeEstimate(PlanNodeStatsEstimate planNodeStatsEstimate, StatsContext statsContext) { return asOptional(getSymbolStatistics(planNodeStatsEstimate, columnName, statsContext).getDistinctValuesCount()); } @Override public Optional<Double> getValueFromAggregationQueryResult(Object value) { return Optional.of(((Number) value).doubleValue()); } @Override public String getComputingAggregationSql() { return "count(distinct " + columnName + ")"; <START> } <END> @Override public String getName() { return "DISTINCT_VALUES_COUNT(" + columnName + ")"; } }; }</code><technical_language>distinct upper case</technical_language>

Target:
public static Metric distinctValuesCount(String columnName) { return new Metric() { @Override public OptionalDouble getValueFromPlanNodeEstimate(PlanNodeStatsEstimate planNodeStatsEstimate, StatsContext statsContext) { return asOptional(getSymbolStatistics(planNodeStatsEstimate, columnName, statsContext).getDistinctValuesCount()); } @Override public OptionalDouble getValueFromAggregationQueryResult(Object value) { return OptionalDouble.of(((Number) value).doubleValue()); } @Override public String getComputingAggregationSql() { return "count(distinct " + columnName + ")"; } @Override public String toString() { return "DISTINCT_VALUES_COUNT(" + columnName + ")"; } }; }
Source:
<code>@Test public void forOverrideRequest() { Action action = mockAction(ASSET_KEY_1, ASSET_URI_1); AssetRequestHandler handler = new AssetRequestHandler(context); <START> List<RequestHandler> handlers = new ArrayList<RequestHandler>(Arrays.asList(handler)); <END> Picasso picasso = new Picasso(context, dispatcher, cache, null, null, handlers, stats, false, false); BitmapHunter hunter = forRequest(picasso, dispatcher, cache, stats, action); assertThat(hunter.requestHandler).isEqualTo(handler); }</code><technical_language>need wrap in ArrayList</technical_language>

Target:
@Test public void forOverrideRequest() { Action action = mockAction(ASSET_KEY_1, ASSET_URI_1); RequestHandler handler = new AssetRequestHandler(context); List<RequestHandler> handlers = Arrays.asList(handler); Picasso picasso = new Picasso(context, dispatcher, cache, null, null, handlers, stats, false, false); BitmapHunter hunter = forRequest(picasso, dispatcher, cache, stats, action); assertThat(hunter.requestHandler).isEqualTo(handler); }
Source:
<code>private WatermarkTracker( BlockingQueue<E> queue, long lowerWatermark, long upperWatermark, Function<E, S> classifier, Consumer<S> onLowerWatermarkCrossed, Consumer<S> onUpperWatermarkCrossed) { <START> assert lowerWatermark >= 0 && lowerWatermark < upperWatermark; <END> this.queue = queue; this.lowerWatermark = lowerWatermark; this.upperWatermark = upperWatermark; this.classifier = classifier; this.onLowerWatermarkCrossed = onLowerWatermarkCrossed; this.onUpperWatermarkCrossed = onUpperWatermarkCrossed; final Map<S, StreamTracker> trackerMap = new ConcurrentHashMap<>(); this.trackerSupplier = key -> trackerMap.computeIfAbsent(key, StreamTracker::new); }</code><technical_language>I a fan of assertions in non-test code. Assertions disabled default anyway. please remove them? Thanks</technical_language>

Target:
private WatermarkTracker( BlockingQueue<E> queue, long lowerWatermark, long upperWatermark, Function<E, S> classifier, Consumer<S> onLowerWatermarkCrossed, Consumer<S> onUpperWatermarkCrossed) { this.queue = queue; this.lowerWatermark = lowerWatermark; this.upperWatermark = upperWatermark; this.classifier = classifier; this.onLowerWatermarkCrossed = onLowerWatermarkCrossed; this.onUpperWatermarkCrossed = onUpperWatermarkCrossed; final Map<S, StreamTracker> trackerMap = new ConcurrentHashMap<>(); this.trackerSupplier = key -> trackerMap.computeIfAbsent(key, StreamTracker::new); }
Source:
<code>void testSpecificTestInstancePreDestroyCallbackIsCalled() { executeTestsForClass( <START> TestCaseWithTestSpecificTestInstancePreDestroyCallback.class).testEvents().assertStatistics( END> stats -> stats.started(1).succeeded(1)); assertThat(callSequence).containsExactly( "fooPostProcessTestInstance:TestCaseWithTestSpecificTestInstancePreDestroyCallback", "beforeEachMethod", "test", "fooPreDestroyCallbackTestInstance:TestCaseWithTestSpecificTestInstancePreDestroyCallback" ); }</code><technical_language>remove //, place</technical_language>

Target:
void testSpecificTestInstancePreDestroyCallbackIsCalled() { executeTestsForClass( TestCaseWithTestSpecificTestInstancePreDestroyCallback.class).testEvents().assertStatistics( stats -> stats.started(1).succeeded(1)); assertThat(callSequence).containsExactly( "beforeEachMethod", "test", "fooPreDestroyCallbackTestInstance:TestCaseWithTestSpecificTestInstancePreDestroyCallback" ); }
Source:
<code>public final void assertEventsMatchLoosely(Condition<? super Event>... conditions) { <START> Preconditions.notNull(conditions, "conditions must not be null"); <END> assertEventsMatchLoosely(this.events, conditions); }</code><technical_language>Individual conditions null. For add a check org.junit.platform.commons.util.Preconditions.containsNoNullElements(T[], Supplier<String>) in order avoid a subsequent NullPointerException</technical_language>

Target:
public final void assertEventsMatchLoosely(Condition<? super Event>... conditions) { Preconditions.notNull(conditions, "conditions must not be null"); Preconditions.containsNoNullElements(conditions, "conditions must not contain null elements"); assertEventsMatchLoosely(this.events, conditions); }
Source:
<code>private DruidExpression handleDateTruncationViaDateTruncation( CallExpression function, Map<VariableReferenceExpression, DruidQueryGeneratorContext.Selection> context) { RowExpression timeInputParameter = function.getArguments().get(1); String inputColumn; String inputTimeZone; String inputFormat; CallExpression timeConversion = getExpressionAsFunction(timeInputParameter, timeInputParameter); <START> switch (timeConversion.getDisplayName().toLowerCase(ENGLISH)) { <END> case FROM_UNIXTIME: inputColumn = timeConversion.getArguments().get(0).accept(this, context).getDefinition(); inputTimeZone = timeConversion.getArguments().size() > 1 ? getStringFromConstant(timeConversion.getArguments().get(1)) : DateTimeZone.UTC.getID(); inputFormat = "seconds"; break; default: throw new PrestoException(DRUID_PUSHDOWN_UNSUPPORTED_EXPRESSION, "Unsupported time function: " + timeConversion.getDisplayName() + " to pushdown for Druid connector "); } RowExpression intervalParameter = function.getArguments().get(0); if (!(intervalParameter instanceof ConstantExpression)) { throw new PrestoException(DRUID_PUSHDOWN_UNSUPPORTED_EXPRESSION, "Unsupported interval unit: " + intervalParameter + " to pushdown for Druid connector "); } return derived("dateTrunc(" + inputColumn + "," + inputFormat + ", " + inputTimeZone + ", " + getStringFromConstant(intervalParameter) + ")"); }</code><technical_language>if</technical_language>

Target:
private DruidExpression handleDateTruncationViaDateTruncation( CallExpression function, Map<VariableReferenceExpression, DruidQueryGeneratorContext.Selection> context) { RowExpression timeInputParameter = function.getArguments().get(1); String inputColumn; String inputTimeZone; String inputFormat; CallExpression timeConversion = getExpressionAsFunction(timeInputParameter, timeInputParameter); if (!timeConversion.getDisplayName().toLowerCase(ENGLISH).equals(FROM_UNIXTIME)) { throw new PrestoException(DRUID_PUSHDOWN_UNSUPPORTED_EXPRESSION, "Unsupported time function: " + timeConversion.getDisplayName() + " to pushdown for Druid connector."); } inputColumn = timeConversion.getArguments().get(0).accept(this, context).getDefinition(); inputTimeZone = timeConversion.getArguments().size() > 1 ? getStringFromConstant(timeConversion.getArguments().get(1)) : DateTimeZone.UTC.getID(); inputFormat = "seconds"; RowExpression intervalParameter = function.getArguments().get(0); if (!(intervalParameter instanceof ConstantExpression)) { throw new PrestoException(DRUID_PUSHDOWN_UNSUPPORTED_EXPRESSION, "Unsupported interval unit: " + intervalParameter + " to pushdown for Druid connector."); } return derived("dateTrunc(" + inputColumn + "," + inputFormat + ", " + inputTimeZone + ", " + getStringFromConstant(intervalParameter) + ")"); }
Source:
<code>public void startExec(String execId, MessageProcessor<LogMessage> execOutputProcessor) throws IOException { <START> final List<Pair<String, ?>> headers = new ArrayList<>(2); <END> headers.add(Pair.of("Content-Type", "application/json")); final ExecStart execStart = new ExecStart().withDetach(execOutputProcessor == null); final String entity = JsonHelper.toJson(execStart, FIRST_LETTER_LOWERCASE); headers.add(Pair.of("Content-Length", entity.getBytes().length)); try (DockerConnection connection = openConnection(dockerDaemonUri).method("POST") .path("/exec/" + execId + "/start") .headers(headers) .entity(entity)) { final DockerResponse response = connection.request(); final int status = response.getStatus(); if (status / 100 != 2) { throw new DockerException(getDockerExceptionMessage(response), status); } if (status != 204 && execOutputProcessor != null) { try (InputStream responseStream = response.getInputStream()) { new LogMessagePumper(responseStream, execOutputProcessor).start(); } } } }</code><technical_language>I in this case is define <code>headers</code> variable <code>580</code> line + move <code>headers.add(Pair.of("Content-Type", "application/json"));</code> declaration, this: java final List<Pair<String, ?>> headers = new ArrayList<>(2); headers.add(Pair.of("Content-Type", "application/json")); headers.add(Pair.of("Content-Length", entity.getBytes().length));</technical_language>

Target:
public void startExec(String execId, MessageProcessor<LogMessage> execOutputProcessor) throws IOException { final ExecStart execStart = new ExecStart().withDetach(execOutputProcessor == null); final String entity = JsonHelper.toJson(execStart, FIRST_LETTER_LOWERCASE); final List<Pair<String, ?>> headers = new ArrayList<>(2); headers.add(Pair.of("Content-Type", MediaType.APPLICATION_JSON)); headers.add(Pair.of("Content-Length", entity.getBytes().length)); try (DockerConnection connection = openConnection(dockerDaemonUri).method("POST") .path("/exec/" + execId + "/start") .headers(headers) .entity(entity)) { final DockerResponse response = connection.request(); final int status = response.getStatus(); if (status / 100 != 2) { throw new DockerException(getDockerExceptionMessage(response), status); } if (status != NO_CONTENT.getStatusCode() && execOutputProcessor != null) { try (InputStream responseStream = response.getInputStream()) { new LogMessagePumper(responseStream, execOutputProcessor).start(); } } } }
Source:
<code><START> protected void checkInitialized() throws IllegalStateException { <END> if (terminated) { throw new IllegalStateException("This SmartProxy instance has been terminated and cannot be used any more."); } if (!initialized) { throw new IllegalStateException("This SmartProxy instance has not been initialized."); } }</code><technical_language>IllegalStateException is unchecked exception, is required define method throwing this type of exception</technical_language>

Target:
protected void checkInitialized() { if (terminated) { throw new IllegalStateException("This SmartProxy instance has been terminated and cannot be used any more."); } if (!initialized) { throw new IllegalStateException("This SmartProxy instance has not been initialized."); } }
Source:
<code>public void workDirEnabledByDefaultWithFsRootAsDefaultPath() throws Exception { final File fsRootPath = temporaryRemotingFolder.newFolder("fsrootdir"); TestUtils.createSwarmClient(j, processDestroyer, temporaryFolder, "-fsroot", fsRootPath.getAbsolutePath()); <START> assertTrue("Workdir exists", new File(fsRootPath, "remoting").isDirectory()); <END> }</code><technical_language>In this test other new tests, strengthen assertions cover expected state? - fsRoot exists - workDir exists (if fsRoot) exist (if testing negative case for -failIfWorkDirIsMissing) - internalDir exists (if working directories) exist (if testing -disableWorkDir) - logs exists (if working directories) exist (if testing -disableWorkDir) - jarCache exists (if working directories -jar-cache) exist (if testing -disableWorkDir) I existing tests covering of relevant assertions, if assert expected state in test. Ideally generalize assertions a common method is called test</technical_language>

Target:
public void workDirEnabledByDefaultWithFsRootAsDefaultPath() throws Exception { final File fsRootPath = temporaryRemotingFolder.newFolder("fsrootdir"); TestUtils.createSwarmClient( j, processDestroyer, temporaryFolder, "-fsroot", fsRootPath.getAbsolutePath()); assertDirectories( fsRootPath, new File(fsRootPath, "remoting"), new File(fsRootPath, "remoting/logs"), new File(fsRootPath, "remoting/jarCache")); }
Source:
<code>private Object configure() { if (StringUtils.isEmpty(monitoredDirectory)) { <START> LOGGER.warn("Cannot setup camel route - must specify a directory to be monitored"); <END> return null; } CompletableFuture.runAsync(this::attemptAddRoutes, configurationExecutor); return null; }</code><technical_language>I synchronizing initState here. CdmServiceWaiter a reference this CdmState, synchronizes it. this guarantee classes time</technical_language>

Target:
private Object configure() { if (StringUtils.isEmpty(monitoredDirectory)) { LOGGER.warn("Cannot setup camel route - must specify a directory to be monitored"); return null; } attemptAddRoutes(); return null; }
Source:
<code>private DateTime getTimeBoundary(StorageAdapter adapter, TimeBoundaryQuery legacyQuery, boolean descending) { final Sequence<Result<DateTime>> resultSequence = QueryRunnerHelper.makeCursorBasedQuery( adapter, legacyQuery.getQuerySegmentSpec().getIntervals(), Filters.toFilter(legacyQuery.getDimensionsFilter()), descending, new AllGranularity(), skipToFirstMatching ); <START> List<Result<DateTime>> resultList = Sequences.toList(resultSequence, Lists.<Result<DateTime>>newArrayList()); <END> if (resultList.size() > 0) { return resultList.get(0).getValue(); } return null; }</code><technical_language>need materialize entire list Sequences.toList(Sequences.limit(resultSequence, 1), Lists.<List<Long>>newArrayList()).get(0);</technical_language>

Target:
private DateTime getTimeBoundary(StorageAdapter adapter, TimeBoundaryQuery legacyQuery, boolean descending) { final Sequence<Result<DateTime>> resultSequence = QueryRunnerHelper.makeCursorBasedQuery( adapter, legacyQuery.getQuerySegmentSpec().getIntervals(), Filters.toFilter(legacyQuery.getDimensionsFilter()), descending, new AllGranularity(), this.skipToFirstMatching ); final List<Result<DateTime>> resultList = Sequences.toList( Sequences.limit(resultSequence, 1), Lists.<Result<DateTime>>newArrayList() ); if (resultList.size() > 0) { return resultList.get(0).getValue(); } return null; }
Source:
<code>public String toString() { return "ContinuousTimeRangeCondition: <START> min=" + min() + ", max =" + max(); END> }</code><technical_language>("+min()+'\u2025'+max()+')';</technical_language>

Target:
public String toString() { return "ContinuousTimeRangeCondition: (" + min() + '\u2025' + max() + ')'; }
Source:
<code><START> private AbstractBackupPath getAbstractBackupPath(final File file, final BackupFileType type) throws Exception { <END> final AbstractBackupPath bp = pathFactory.get(); bp.parseLocal(file, type); return bp; }</code><technical_language>I this throw a ParseException, throw (no pokemon catching)</technical_language>

Target:
private AbstractBackupPath getAbstractBackupPath(final File file, final BackupFileType type) throws ParseException { final AbstractBackupPath bp = pathFactory.get(); bp.parseLocal(file, type); return bp; }
Source:
<code>public void testComputeBroadcast() throws Exception { barrier = new CyclicBarrier(6); SystemView<ComputeJobView> jobs = server.context().systemView().view(JOBS_VIEW); for (int i = 0; i < 5; i++) { client.compute().broadcastAsync(() -> { try { barrier.await(TIMEOUT, MILLISECONDS); barrier.await(TIMEOUT, MILLISECONDS); } catch (InterruptedException | BrokenBarrierException | TimeoutException e) { throw new RuntimeException(e); } }); } barrier.await(TIMEOUT, MILLISECONDS); assertEquals(5, jobs.size()); <START> ComputeJobView t = jobs.iterator().next(); <END> checkTask(t); barrier.await(TIMEOUT, MILLISECONDS); }</code><technical_language>Lets check job view: for (ComputeJobView job : jobs) checkJob(job);</technical_language>

Target:
public void testComputeBroadcast() throws Exception { barrier = new CyclicBarrier(6); SystemView<ComputeJobView> jobs = server.context().systemView().view(JOBS_VIEW); for (int i = 0; i < 5; i++) { client.compute().broadcastAsync(() -> { try { barrier.await(TIMEOUT, MILLISECONDS); barrier.await(TIMEOUT, MILLISECONDS); } catch (InterruptedException | BrokenBarrierException | TimeoutException e) { throw new RuntimeException(e); } }); } barrier.await(TIMEOUT, MILLISECONDS); assertEquals(5, jobs.size()); for (ComputeJobView job : jobs) checkJobView(job); barrier.await(TIMEOUT, MILLISECONDS); boolean res = waitForCondition(() -> jobs.size() == 0, TIMEOUT); assertTrue(res); }
Source:
<code>public void doPolling(Guid cmdId, List<Guid> childCmdIds) { DestroyImageCommand<DestroyImageParameters> command = commandCoordinatorUtil.retrieveCommand(cmdId); Set<Guid> taskIds = new HashSet<>(command.getReturnValue().getVdsmTaskIdList()); Map<Guid, AsyncTaskStatus> idToTaskStatusMap = commandCoordinatorUtil.pollTasks(taskIds); for (Map.Entry<Guid, AsyncTaskStatus> idToTaskStatus : idToTaskStatusMap.entrySet()) { Guid id = idToTaskStatus.getKey(); AsyncTaskStatus status = idToTaskStatus.getValue(); if (status.getTaskIsRunning()) { log.info("Waiting on destroy image command to complete the task (taskId = {})", id); return; } } List<Guid> failedTasks = new ArrayList<>(); <START> for (Map.Entry<Guid, AsyncTaskStatus> idToStatus : idToTaskStatusMap.entrySet()) { Guid id = idToStatus.getKey(); AsyncTaskStatus status = idToStatus.getValue(); if (!status.getTaskEndedSuccessfully()) { failedTasks.add(id); } } <END> if (failedTasks.isEmpty()) { command.setSucceeded(true); command.setCommandStatus(CommandStatus.SUCCEEDED); command.persistCommand(command.getParameters().getParentCommand()); log.info("Destroy image command has completed successfully for images '{}' with async tasks '{}'.", command.getParameters().getImageList(), taskIds); } else { command.setSucceeded(false); command.setCommandStatus(CommandStatus.FAILED); log.info("Destroy image command has failed for images '{}' with async tasks '{}'.", command.getParameters().getImageList(), failedTasks); } command.persistCommand(command.getParameters().getParentCommand()); }</code><technical_language>consider idToTaskStatusMap.forEach((k, v) -> { ... } for coolness's sake</technical_language>

Target:
public void doPolling(Guid cmdId, List<Guid> childCmdIds) { DestroyImageCommand<DestroyImageParameters> command = commandCoordinatorUtil.retrieveCommand(cmdId); Set<Guid> taskIds = new HashSet<>(command.getReturnValue().getVdsmTaskIdList()); Map<Guid, AsyncTaskStatus> idToTaskStatusMap = commandCoordinatorUtil.pollTasks(taskIds); for (Map.Entry<Guid, AsyncTaskStatus> idToTaskStatus : idToTaskStatusMap.entrySet()) { Guid id = idToTaskStatus.getKey(); AsyncTaskStatus status = idToTaskStatus.getValue(); if (status.getTaskIsRunning()) { log.info("Waiting on destroy image command to complete the task (taskId = {})", id); return; } } List<Guid> failedTasks = new ArrayList<>(); idToTaskStatusMap.forEach((id, status) -> { if (!status.getTaskEndedSuccessfully()) { failedTasks.add(id); } }); if (failedTasks.isEmpty()) { command.setSucceeded(true); command.setCommandStatus(CommandStatus.SUCCEEDED); command.persistCommand(command.getParameters().getParentCommand()); log.info("Destroy image command has completed successfully for images '{}' with async tasks '{}'.", command.getParameters().getImageList(), taskIds); } else { command.setSucceeded(false); command.setCommandStatus(CommandStatus.FAILED); log.info("Destroy image command has failed for images '{}' with async tasks '{}'.", command.getParameters().getImageList(), failedTasks); } command.persistCommand(command.getParameters().getParentCommand()); }
Source:
<code>private IProject createTestProject(IProgressMonitor monitor) throws CoreException { IProject project = getTestProject(); assertFalse("Expected test project to not exist at beginning of test", project.exists()); ensureExistsInWorkspace(project, true); assertTrue("Expected test project to be open after creation", project.isOpen()); IProjectDescription projectDescription = project.getDescription(); ICommand[] buildSpec = projectDescription.getBuildSpec(); ICommand command = projectDescription.newCommand(); <START> command.setBuilderName("Simple Builder"); <END> Collection<ICommand> builders = new ArrayList<>(Arrays.asList(buildSpec)); builders.add(command); projectDescription.setBuildSpec(builders.toArray(new ICommand[] {})); project.setDescription(projectDescription, monitor); return project; }</code><technical_language>Is this defined this in plugin.xml? I builder ID. Please org.eclipse.core.tests.resources.regression.SimpleBuilder.BUILDER_ID</technical_language>

Target:
private IProject createTestProject(IProgressMonitor monitor) throws CoreException { IProject project = getTestProject(); assertFalse("Expected test project to not exist at beginning of test", project.exists()); ensureExistsInWorkspace(project, true); assertTrue("Expected test project to be open after creation", project.isOpen()); IProjectDescription projectDescription = project.getDescription(); ICommand[] buildSpec = projectDescription.getBuildSpec(); ICommand command = projectDescription.newCommand(); command.setBuilderName(SimpleBuilder.BUILDER_ID); Collection<ICommand> builders = new ArrayList<>(Arrays.asList(buildSpec)); builders.add(command); projectDescription.setBuildSpec(builders.toArray(new ICommand[] {})); project.setDescription(projectDescription, monitor); return project; }
Source:
<code>public void writeObject(ObjectOutput output, JPAContinuousQueryCacheEventFilterConverter filterAndConverter) throws IOException { output.writeUTF(filterAndConverter.jpaQuery); Map<String, Object> namedParameters = filterAndConverter.namedParameters; if (namedParameters != null) { output.writeInt(namedParameters.size()); for (Map.Entry<String, Object> e : namedParameters.entrySet()) { output.writeUTF(e.getKey()); output.writeObject(e.getValue()); } } else { <START> output.writeInt(-1); <END> } output.writeObject(filterAndConverter.matcherImplClass); }</code><technical_language>UnsignedNumeric.writeUnsignedInt 0 params</technical_language>

Target:
public void writeObject(ObjectOutput output, JPAContinuousQueryCacheEventFilterConverter filterAndConverter) throws IOException { output.writeUTF(filterAndConverter.jpaQuery); Map<String, Object> namedParameters = filterAndConverter.namedParameters; if (namedParameters != null) { UnsignedNumeric.writeUnsignedInt(output, namedParameters.size()); for (Map.Entry<String, Object> e : namedParameters.entrySet()) { output.writeUTF(e.getKey()); output.writeObject(e.getValue()); } } else { UnsignedNumeric.writeUnsignedInt(output, 0); } output.writeObject(filterAndConverter.matcherImplClass); }
Source:
<code>public String getStripped(String input, int wordCount) { String[] words = input.split(" "); if(words.length < wordCount) return input; <START> String result = ""; <END> for (int i = 0; i < wordCount; i++){ result += words[i] + " "; } return result; }</code><technical_language>Strings here. Please read this: <LINK_0> <LINK_1></technical_language>

Target:
private String getStripped(String input, int wordCount) { String[] words = input.split(" "); if(words.length < wordCount) return input; StringBuilder result = new StringBuilder(); for (int i = 0; i < wordCount; i++){ result.append(words[i]); result.append(" "); } return result.toString(); }
Source:
<code>public static <T> Class<? extends T> defineClass(ClassDefinition classDefinition, Class<T> superType, Map<Long, MethodHandle> callSiteBindings, ClassLoader parentClassLoader) { <START> try { <END> return defineClass(classDefinition, superType, new DynamicClassLoader(parentClassLoader, callSiteBindings)); } catch (ByteCodeTooLargeException byteCodeTooLargeException) { throw new PrestoException(GENERATED_BYTECODE_TOO_LARGE, ERROR_LARGE_BYTECODE); } }</code><technical_language>This is needed if handles exception in other method</technical_language>

Target:
public static <T> Class<? extends T> defineClass(ClassDefinition classDefinition, Class<T> superType, Map<Long, MethodHandle> callSiteBindings, ClassLoader parentClassLoader) { return defineClass(classDefinition, superType, new DynamicClassLoader(parentClassLoader, callSiteBindings)); }
Source:
<code>public boolean lastDismissedReminderMoreThan24hAgo() { long now = System.currentTimeMillis(); long lastReminder = prefs.getLong(PREFS_KEY_BACKUP_SEED_LAST_DISMISSED_REMINDER, now); <START> return now - lastReminder > 86400000; <END> }</code><technical_language>@denlb , please replace this magic number 86400000 more readable, TimeUnit.HOURS.toMillis(24)</technical_language>

Target:
public boolean lastDismissedReminderMoreThan24hAgo() { long now = System.currentTimeMillis(); long lastReminder = prefs.getLong(PREFS_KEY_BACKUP_SEED_LAST_DISMISSED_REMINDER, now); return now - lastReminder > TimeUnit.HOURS.toMillis(24); }
Source:
<code>public void testNullPathWithRoot() { AbsolutePathResolver apr = new AbsolutePathResolver(null); <START> assertThat(apr.getPath("USER_DIRECTORY"), nullValue()); <END> }</code><technical_language>reference variable **USER_DIRECTORY** a String of "USER_DIRECTORY"</technical_language>

Target:
public void testNullPathWithRoot() { AbsolutePathResolver apr = new AbsolutePathResolver(null); assertThat(apr.getPath(USER_DIRECTORY), nullValue()); }
Source:
<code>public void checkAndSetupStreamsDrawer() { try { <START> if (streamsDrawer.getAdapter().getCount() != 0) return; <END> setupListViewAdapter(); } catch (NullPointerException npe) { setupListViewAdapter(); } }</code><technical_language>this is potentially confusing, please add brakcet if statement</technical_language>

Target:
public void checkAndSetupStreamsDrawer() { try { if (streamsDrawer.getAdapter().getCount() != 0) { return; } setupListViewAdapter(); } catch (NullPointerException npe) { setupListViewAdapter(); } }
Source:
<code>private void updateSnapshotConfigWithoutImage(Guid imageGroupToRemove) { List<DiskImage> snapshotDisks = getDiskImageDao().getAllSnapshotsForImageGroup(imageGroupToRemove); for (DiskImage snapshotDisk : snapshotDisks) { NGuid vmSnapshotId = snapshotDisk.getvm_snapshot_id(); if (vmSnapshotId != null && !Guid.Empty.equals(vmSnapshotId.getValue())) { try { lockSnapshotWithWait(vmSnapshotId.getValue()); final Snapshot updated = prepareSnapshotConfigWithoutImageSingleImage(vmSnapshotId.getValue(), snapshotDisk.getImageId()); if (updated != null) { <START> TransactionSupport.executeInScope(TransactionScopeOption.RequiresNew, <END> new TransactionMethod<Object>() { @Override public Object runInTransaction() { getSnapshotDao().update(updated); return null; } }); } } finally { freeSnapshotLock(); } } } }</code><technical_language>if need a new transaction</technical_language>

Target:
private void updateSnapshotConfigWithoutImage(Guid imageGroupToRemove) { List<DiskImage> snapshotDisks = getDiskImageDao().getAllSnapshotsForImageGroup(imageGroupToRemove); Collections.shuffle(snapshotDisks); for (DiskImage snapshotDisk : snapshotDisks) { NGuid vmSnapshotId = snapshotDisk.getvm_snapshot_id(); if (vmSnapshotId != null && !Guid.Empty.equals(vmSnapshotId.getValue())) { try { lockSnapshotWithWait(vmSnapshotId.getValue()); final Snapshot updated = prepareSnapshotConfigWithoutImageSingleImage(vmSnapshotId.getValue(), snapshotDisk.getImageId()); if (updated != null) { TransactionSupport.executeInScope(TransactionScopeOption.RequiresNew, new TransactionMethod<Object>() { @Override public Object runInTransaction() { getSnapshotDao().update(updated); return null; } }); } } finally { freeSnapshotLock(); } } } }