auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void assignLowLatency(JsonObject llStart) { final String lowLatencyTag = "__spl_lowLatencyRegionId" + lowLatencyRegionCount++; Set<JsonObject> llStartChildren = getDownstream(llStart, graph); <START> Boolean[] isAlreadyTagged = {false}; <END> llStartChildren.forEach(oper -> { JsonObject placement = object(oper, CONFIG, PLACEMENT); if(placement!=null && jstring(placement, PLACEMENT_LOW_LATENCY_REGION_ID) != null) isAlreadyTagged[0]=true; }); if(isAlreadyTagged[0]) return; Set<BVirtualMarker> boundaries = EnumSet.of(LOW_LATENCY, END_LOW_LATENCY); GraphUtilities.visitOnce(llStartChildren, boundaries, graph, new Consumer<JsonObject>() { @Override public void accept(JsonObject op) { JsonObject placement = objectCreate(op, CONFIG, PLACEMENT); assert jstring(placement, PLACEMENT_LOW_LATENCY_REGION_ID) == null || jstring(placement, PLACEMENT_LOW_LATENCY_REGION_ID).equals(lowLatencyTag); placement.addProperty(PLACEMENT_LOW_LATENCY_REGION_ID, lowLatencyTag); } }); }</code><technical_language>Normal approach is AtomicBoolean</technical_language>

Target:
private void assignLowLatency(JsonObject llStart) { final String lowLatencyTag = "__spl_lowLatencyRegionId" + lowLatencyRegionCount++; Set<JsonObject> llStartChildren = getDownstream(llStart, graph); AtomicBoolean isAlreadyTagged = new AtomicBoolean(false); llStartChildren.forEach(oper -> { JsonObject placement = object(oper, CONFIG, PLACEMENT); if(placement!=null && jstring(placement, PLACEMENT_LOW_LATENCY_REGION_ID) != null) isAlreadyTagged.set(true);; }); if(isAlreadyTagged.get()) return; Set<BVirtualMarker> boundaries = EnumSet.of(LOW_LATENCY, END_LOW_LATENCY); GraphUtilities.visitOnce(llStartChildren, boundaries, graph, new Consumer<JsonObject>() { @Override public void accept(JsonObject op) { JsonObject placement = objectCreate(op, CONFIG, PLACEMENT); assert jstring(placement, PLACEMENT_LOW_LATENCY_REGION_ID) == null || jstring(placement, PLACEMENT_LOW_LATENCY_REGION_ID).equals(lowLatencyTag); placement.addProperty(PLACEMENT_LOW_LATENCY_REGION_ID, lowLatencyTag); } }); }
Source:
<code>private Function<PollingContext<OperationResult>, Mono<OperationResult>> receiptStreamActivationOperation( Flux<ByteBuffer> data, long length, FormContentType formContentType, boolean includeTextDetails) { Objects.requireNonNull(data, "'data' is required and cannot be null."); final long[] bufferedDataSize = {0}; final List<ByteBuffer> cachedBuffers = new LinkedList<>(); final AtomicBoolean[] isGuessed = {new AtomicBoolean(true)}; final ContentType[] contentType = new ContentType[1]; return pollingContext -> data.filter(ByteBuffer::hasRemaining) .windowUntil(buffer -> { if (bufferedDataSize[0] >= length) { return false; } bufferedDataSize[0] += buffer.remaining(); if (formContentType == null && isGuessed[0].get() && bufferedDataSize[0] >= 4) { byte[] bytes = buffer.array(); contentType[0] = getContentType(ByteBuffer.wrap(bytes)); isGuessed[0].compareAndSet(true, false); } ByteBuffer cachedBuffer = ByteBuffer.allocate(buffer.remaining()).put(buffer); cachedBuffer.flip(); cachedBuffers.add(cachedBuffer); if (bufferedDataSize[0] >= length) { return true; } return false; }, true, Integer.MAX_VALUE) <START> .next() <END> .flatMap(newData -> { final ContentType contentTypeFinal = formContentType == null ? contentType[0] : ContentType.fromString(formContentType.toString()); return service.analyzeReceiptAsyncWithResponseAsync(contentTypeFinal, Flux.fromIterable(cachedBuffers), length, includeTextDetails).map(response -> new OperationResult( parseModelId(response.getDeserializedHeaders().getOperationLocation()))); }); }</code><technical_language>explicit contentType check java if (contentType == null) { return callApi(data, ..); } else { return data.windowUntil(..).flatMap(fluxes -> { var contentType = getContentType(cachedBuffers); if (fluxes.size() == 1) { return callAPI(Flux.fromIterable(cachedBuffers)); } else { return callAPI(Flux.fromIterable(cachedBuffers).concatWith(fluxes.get(1))); } }); } I cache in windowUntil operator i.e. contentType check in windowUntil, check deferred flatmap operator</technical_language>

Target:
private Function<PollingContext<OperationResult>, Mono<OperationResult>> receiptStreamActivationOperation( Flux<ByteBuffer> data, long length, FormContentType formContentType, boolean includeTextDetails) { Objects.requireNonNull(data, "'data' is required and cannot be null."); return pollingContext -> { if (formContentType != null) { try { return service.analyzeReceiptAsyncWithResponseAsync( ContentType.fromString(formContentType.toString()), data, length, includeTextDetails) .map(response -> new OperationResult( parseModelId(response.getDeserializedHeaders().getOperationLocation()))); } catch (RuntimeException ex) { return monoError(logger, ex); } } else { return detectContentType(data) .flatMap(contentType -> service.analyzeReceiptAsyncWithResponseAsync(contentType, data, length, includeTextDetails) .map(response -> new OperationResult( parseModelId(response.getDeserializedHeaders().getOperationLocation())))); } }; }
Source:
<code>public void onError(Throwable cause) { <START> cause.printStackTrace(System.out); <END> }</code><technical_language>this System.err instead</technical_language>

Target:
public void onError(Throwable cause) { logger.error("Error while streaming audio data to transcription service" , cause); }
Source:
<code>public void setButtonData(UIInputBind bindButton) { this.bindButton = bindButton; String messageText = "Key " + bindButton.getNewInput().getDisplayName() + " has already been assigned an action. Press ok to change anyway."; <START> find("title", UILabel.class).setText("Rebinding"); <END> find("message", UILabel.class).setText(messageText); }</code><technical_language>label text is static, set in confirmChangePopup.ui instead. ("text": "Rebinding instead of "text": "Title")</technical_language>

Target:
public void setButtonData(UIInputBind bindButton) { this.bindButton = bindButton; String messageText = "Key " + bindButton.getNewInput().getDisplayName() + " has already been assigned an action. Press ok to change anyway."; find("message", UILabel.class).setText(messageText); }
Source:
<code>public <T extends DataSerializable> Optional<DataBuilder<T>> getBuilder(Class<T> clazz) { Preconditions.checkNotNull(clazz); <START> if (this.builders.containsKey(clazz)) { <END> return Optional.of((DataBuilder<T>) this.builders.get(clazz)); } else if (this.immutableDataBuilderMap.containsKey(clazz)) { return Optional.of((DataBuilder<T>) this.immutableDataBuilderMap.get(clazz)); } else { return Optional.empty(); } }</code><technical_language>Replace contains + get get check if return is null</technical_language>

Target:
public <T extends DataSerializable> Optional<DataBuilder<T>> getBuilder(Class<T> clazz) { Preconditions.checkNotNull(clazz); DataBuilder<?> dataBuilder = this.builders.get(clazz); if (dataBuilder != null) { return Optional.of((DataBuilder<T>) dataBuilder); } return Optional.ofNullable((DataBuilder<T>) this.immutableDataBuilderMap.get(clazz)); }
Source:
<code>public DistributedObjectEvent(EventType eventType, String serviceName, String objectName, DistributedObject distributedObject, UUID source) { super(source); this.eventType = eventType; this.serviceName = serviceName; this.objectName = objectName; this.distributedObject = distributedObject; <START> this.source = source; <END> }</code><technical_language>This line is unnecessary</technical_language>

Target:
public DistributedObjectEvent(EventType eventType, String serviceName, String objectName, DistributedObject distributedObject, UUID source) { super(source); this.eventType = eventType; this.serviceName = serviceName; this.objectName = objectName; this.distributedObject = distributedObject; }
Source:
<code>public Response<Key> getKey() { <START> return withContext(context -> client.getKey(context)).block(); <END> }</code><technical_language>In sync client, context is passed explicit "Context" argument. [This](<LINK_0> is a good example. Need for sync Client methods</technical_language>

Target:
public Key getKey() { return getKeyWithResponse(Context.NONE).value(); }
Source:
<code>protected ListBranchesResult() { <START> this(new ArrayList<Branch>(), false); <END> }</code><technical_language>this constructor exists for JSON encoding, recursively process populate fields, need call this(). accept default initialization of false/null for fields JSON decoder finish building object</technical_language>

Target:
protected ListBranchesResult() { }
Source:
<code><START> public TablespaceProto getTablespace(final String tablespaceName) throws UndefinedTableException { <END> try { final BlockingInterface stub = getStub(); final GetTablespaceResponse response = stub.getTablespace(null, ProtoUtil.convertString(tablespaceName)); throwsIfThisError(response.getState(), UndefinedTableException.class); ensureOk(response.getState()); return response.getTablespace(); } catch (ServiceException e) { throw new RuntimeException(e); } }</code><technical_language>This method throw UndefinedTablespaceException</technical_language>

Target:
public TablespaceProto getTablespace(final String tablespaceName) throws UndefinedTablespaceException { try { final BlockingInterface stub = getStub(); final GetTablespaceResponse response = stub.getTablespace(null, ProtoUtil.convertString(tablespaceName)); throwsIfThisError(response.getState(), UndefinedTablespaceException.class); ensureOk(response.getState()); return response.getTablespace(); } catch (ServiceException e) { throw new RuntimeException(e); } }
Source:
<code>public final void setClockSkew(Duration clockSkew) { Assert.notNull(clockSkew, "clockSkew cannot be null"); <START> Assert.isTrue(clockSkew.compareTo(MINIMUM_CLOCK_SKEW) >=0, "clockSkew should be greater than 0"); <END> this.clockSkew = clockSkew; }</code><technical_language>remove MINIMUM_CLOCK_SKEW update assertion follows: Assert.isTrue(clockSkew.getSeconds() >= 0, "clockSkew >= 0");</technical_language>

Target:
public final void setClockSkew(Duration clockSkew) { Assert.notNull(clockSkew, "clockSkew cannot be null"); Assert.isTrue(clockSkew.getSeconds() >= 0, "clockSkew must be >= 0"); this.clockSkew = clockSkew; }
Source:
<code><START> public Collection<SerializationContextInitializer> getContextInitializers() { <END> return contextInitializers; }</code><technical_language>I saying, List. I actual impl is ArrayList List API level</technical_language>

Target:
public List<SerializationContextInitializer> getContextInitializers() { return contextInitializers; }
Source:
<code>public void testHeaderBytes() { final String expectedHeaderString = "LA:testProject \n" + (char) 0x1A + ("ST:3 \n" + (char) 0x1A + "CO:1 \n" + (char) 0x1A + "+X:20 \n" + (char) 0x1A + "-X:0 \n" + (char) 0x1A + "+Y:20 \n" + (char) 0x1A + "-Y:0 \n" + (char) 0x1A + "AX:0 \n" + (char) 0x1A + "AY:0 \n" + (char) 0x1A + "MX:0 \n" + (char) 0x1A + "MY:0 \n" + (char) 0x1A + "PD:*****\n" + (char) 0x1A).replace(' ', '\0') + String.format("%388s", " "); EmbroideryList points = new EmbroideryList(); points.add(new PointF(0, 0)); points.add(new PointF(10, 10)); points.add(new PointF(0, 0)); ArrayList<DSTFileGenerator.StitchPoint> stitchPoints = fileGenerator.prepareStitchPoints(points); byte[] header = fileGenerator.getHeaderBytes(stitchPoints); byte[] expectedHeader = expectedHeaderString.getBytes(); <START> assertEquals(DSTFileGenerator.HEADERMAXBYTE, header.length); <END> assertArrayEquals(expectedHeader, header); }</code><technical_language>please remove this, if this isnt true, next assertion fail give a pointer length is wrong</technical_language>

Target:
public void testHeaderBytes() { final String expectedHeaderString = "LA:DSTFileGenerato\n" + (char) 0x1A + ("ST:3 \n" + (char) 0x1A + "CO:1 \n" + (char) 0x1A + "+X:20 \n" + (char) 0x1A + "-X:0 \n" + (char) 0x1A + "+Y:20 \n" + (char) 0x1A + "-Y:0 \n" + (char) 0x1A + "AX:0 \n" + (char) 0x1A + "AY:0 \n" + (char) 0x1A + "MX:0 \n" + (char) 0x1A + "MY:0 \n" + (char) 0x1A + "PD:*****\n" + (char) 0x1A).replace(' ', '\0') + String.format("%388s", " "); EmbroideryList points = new EmbroideryList(); points.add(new PointF(0, 0)); points.add(new PointF(10, 10)); points.add(new PointF(0, 0)); ArrayList<DSTFileGenerator.StitchPoint> stitchPoints = fileGenerator.prepareStitchPoints(points); byte[] header = fileGenerator.getHeaderBytes(stitchPoints); byte[] expectedHeader = expectedHeaderString.getBytes(); assertArrayEquals(expectedHeader, header); }
Source:
<code>private void equalizeIrrelevantData(CourseAttributes expected, CourseAttributes actual) { expected.createdAt = actual.createdAt; expected.sanitizeForSaving(); <START> } <END></code><technical_language>irrelevant this PR? need sanitise field here</technical_language>

Target:
private void equalizeIrrelevantData(CourseAttributes expected, CourseAttributes actual) { expected.createdAt = actual.createdAt; }
Source:
<code>public List<FeedbackQuestionAttributes> getFeedbackQuestionsForStudent( String feedbackSessionName, String courseId, StudentAttributes student) { List<FeedbackQuestionAttributes> questions = new ArrayList<FeedbackQuestionAttributes>(); questions.addAll( fqDb.getFeedbackQuestionsForGiverType( feedbackSessionName, courseId, FeedbackParticipantType.STUDENTS)); questions.addAll( fqDb.getFeedbackQuestionsForGiverType( feedbackSessionName, courseId, FeedbackParticipantType.TEAMS)); List<FeedbackQuestionAttributes> questionsWithCustomFeedbackPaths = fqDb.getFeedbackQuestionsForGiverType( feedbackSessionName, courseId, FeedbackParticipantType.CUSTOM); for (FeedbackQuestionAttributes question : questionsWithCustomFeedbackPaths) { <START> if (question.hasStudentAsGiverInFeedbackPathAttributesList(student)) { <END> questions.add(question); } } Collections.sort(questions); return questions; }</code><technical_language>While this fine too, consider a bidirectional relationship path question, storing question's Id/key in feedback path, logic clearer possibly faster</technical_language>

Target:
public List<FeedbackQuestionAttributes> getFeedbackQuestionsForStudent( String feedbackSessionName, String courseId, StudentAttributes student) { List<FeedbackQuestionAttributes> questions = new ArrayList<FeedbackQuestionAttributes>(); questions.addAll( fqDb.getFeedbackQuestionsForGiverType( feedbackSessionName, courseId, FeedbackParticipantType.STUDENTS)); questions.addAll( fqDb.getFeedbackQuestionsForGiverType( feedbackSessionName, courseId, FeedbackParticipantType.TEAMS)); List<FeedbackQuestionAttributes> questionsWithCustomFeedbackPaths = fqDb.getFeedbackQuestionsForGiverType( feedbackSessionName, courseId, FeedbackParticipantType.CUSTOM); for (FeedbackQuestionAttributes question : questionsWithCustomFeedbackPaths) { if (question.hasStudentAsGiverInFeedbackPaths(student)) { questions.add(question); } } Collections.sort(questions); return questions; }
Source:
<code>public void shouldUpdateDocumentConcurrently() throws Exception { final String key = testName.getMethodName(); remove(key); final AtomicLong counter = new AtomicLong(); VersionedData initial = new VersionedData(key, "value-initial"); versionedDataRepository.save(initial); assertNotEquals(0L, initial.version); Callable<Void> task = new Callable<Void>() { @Override public Void call() throws Exception { boolean saved = false; while(!saved) { long counterValue = counter.incrementAndGet(); VersionedData messageData = versionedDataRepository.findOne(key); messageData.data = "value-" + counterValue; try { versionedDataRepository.save(messageData); saved = true; } catch (OptimisticLockingFailureException e) { <START> } <END> } return null; } }; AsyncUtils.executeConcurrently(5, task); assertNotEquals(initial.data, versionedDataRepository.findOne(key).data); }</code><technical_language>add a counter too, assert 1 out of 5 concurrent updates succeeded</technical_language>

Target:
public void shouldUpdateDocumentConcurrently() throws Exception { final String key = testName.getMethodName(); remove(key); final AtomicLong counter = new AtomicLong(); final AtomicLong updatedCounter = new AtomicLong(); VersionedData initial = new VersionedData(key, "value-initial"); versionedDataRepository.save(initial); assertNotEquals(0L, initial.version); Callable<Void> task = new Callable<Void>() { @Override public Void call() throws Exception { boolean updated = false; while(!updated) { long counterValue = counter.incrementAndGet(); VersionedData messageData = versionedDataRepository.findOne(key); messageData.data = "value-" + counterValue; try { versionedDataRepository.save(messageData); updated = true; updatedCounter.incrementAndGet(); } catch (OptimisticLockingFailureException e) { } } return null; } }; AsyncUtils.executeConcurrently(5, task); assertNotEquals(initial.data, versionedDataRepository.findOne(key).data); assertEquals(5, updatedCounter.intValue()); }
Source:
<code>public void doPrefetch(int index, long relativeOffset, long size) { try { readOptions.get(index).doPrefetch(relativeOffset, size); } catch (Exception e) { <START> logger.error("Data Prefetch failed", e); <END> } }</code><technical_language>is this error a warning? system proceeds giving up, I a warning</technical_language>

Target:
public void doPrefetch(int index, long relativeOffset, long size) throws IOException { readOptions.get(index).doPrefetch(relativeOffset, size); }
Source:
<code>private Key readKey(InputStream input) throws IOException { byte[] data = new byte[260]; <START> input.read(data, 0, 4); END> input.read(data, 0, 256); SRand srand = new SRand(LittleEndian.getInt(data)); byte xor = 0; for (int i = 0, n = 0; i < 256; i++, n--) { if (n == 0) { xor = (byte) (srand.rand() & 0xFF); n = (int) ((srand.rand() & 0xF) + 1); } if (i >= 4) { data[i] = (byte) ((data[i]) ^ (xor)); } } int offset = 4 + (data[0] & 0xF); byte[] key = Arrays.copyOfRange(data, offset, offset + 16); SecretKeySpec secretKey = new SecretKeySpec(key, "AES"); return secretKey; }</code><technical_language>IOUtils readFully check for read length if readfully doesn't</technical_language>

Target:
private Key readKey(InputStream input) throws IOException { byte[] data = new byte[260]; if (IOUtils.readFully(input, data, 0, 4) != 4) throw new EOFException(); if (IOUtils.readFully(input, data, 0, 256) != 256) throw new EOFException(); SRand srand = new SRand(LittleEndian.getInt(data)); byte xor = 0; for (int i = 0, n = 0; i < 256; i++, n--) { if (n == 0) { xor = (byte) (srand.rand() & 0xFF); n = (int) ((srand.rand() & 0xF) + 1); } if (i >= 4) { data[i] = (byte) ((data[i]) ^ (xor)); } } int offset = 4 + (data[0] & 0xF); byte[] key = Arrays.copyOfRange(data, offset, offset + 16); SecretKeySpec secretKey = new SecretKeySpec(key, "AES"); return secretKey; }
Source:
<code><START> public synchronized DateFormat get() { <END> DateFormat dateFormat = threadMap.get(Thread.currentThread()); if (dateFormat == null) { dateFormat = (DateFormat) templateFormat.clone(); threadMap.put(Thread.currentThread(), dateFormat); } return dateFormat; }</code><technical_language>@ztravis synchronized scope, more smaller, below. private final Object getDateFormatLock = new Object(); public DateFormat get() { DateFormat dateFormat; synchronized (getDateFormatLock) { dateFormat = (DateFormat) threadMap.get(Thread.currentThread()); } ... return dateFormat; }</technical_language>

Target:
public DateFormat get() { DateFormat dateFormat = threadMap.get(Thread.currentThread()); if (dateFormat == null) { dateFormat = (DateFormat) templateFormat.clone(); threadMap.put(Thread.currentThread(), dateFormat); } return dateFormat; }
Source:
<code>public void getListeningSockets() { ServerStatusManager ssm = mock(ServerStatusManager.class); Map<SocketAddress, ChannelInitializer<?>> initializers = new HashMap<>(); <START> initializers.put( <END> new InetSocketAddress(0), new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) }); ClientConnectionsShutdown ccs = new ClientConnectionsShutdown( new DefaultChannelGroup(GlobalEventExecutor.INSTANCE), GlobalEventExecutor.INSTANCE, null); EventLoopGroupMetrics elgm = new EventLoopGroupMetrics(Spectator.globalRegistry()); EventLoopConfig elc = new EventLoopConfig() { @Override public int eventLoopCount() { return 1; } @Override public int acceptorCount() { return 1; } }; Server s = new Server(ssm, initializers, ccs, elgm, elc); s.start( false); List<SocketAddress> addrs = s.getListeningAddresses(); assertEquals(1, addrs.size()); assertTrue(addrs.get(0) instanceof InetSocketAddress); assertNotEquals(((InetSocketAddress) addrs.get(0)).getPort(), 0); s.stop(); }</code><technical_language>want init 2 addrs. Weird manifest in collections of a single size</technical_language>

Target:
public void getListeningSockets() throws Exception { ServerStatusManager ssm = mock(ServerStatusManager.class); Map<SocketAddress, ChannelInitializer<?>> initializers = new HashMap<>(); ChannelInitializer<Channel> init = new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) }; initializers.put(new InetSocketAddress(0), init); initializers.put(new InetSocketAddress(InetAddress.getLocalHost(), 0), init); ClientConnectionsShutdown ccs = new ClientConnectionsShutdown( new DefaultChannelGroup(GlobalEventExecutor.INSTANCE), GlobalEventExecutor.INSTANCE, null); EventLoopGroupMetrics elgm = new EventLoopGroupMetrics(Spectator.globalRegistry()); EventLoopConfig elc = new EventLoopConfig() { @Override public int eventLoopCount() { return 1; } @Override public int acceptorCount() { return 1; } }; Server s = new Server(ssm, initializers, ccs, elgm, elc); s.start( false); List<SocketAddress> addrs = s.getListeningAddresses(); assertEquals(2, addrs.size()); assertTrue(addrs.get(0) instanceof InetSocketAddress); assertNotEquals(((InetSocketAddress) addrs.get(0)).getPort(), 0); assertTrue(addrs.get(1) instanceof InetSocketAddress); assertNotEquals(((InetSocketAddress) addrs.get(1)).getPort(), 0); s.stop(); }
Source:
<code>public boolean removeMemberFromReplicaSet(MongoDBServer server) { BSONObject existingConfig = getReplicaSetConfig(); if (existingConfig == null) { <START> LOG.warn("Couldn't load config for replica set."); <END> return false; } BasicBSONObject newConfig = ReplicaSetConfig.fromExistingConfig(existingConfig) .remove(server) .build(); return reconfigureReplicaSet(newConfig); }</code><technical_language>here: include context in log message (e.g. instance connect to)</technical_language>

Target:
public boolean removeMemberFromReplicaSet(MongoDBServer server) { BSONObject existingConfig = getReplicaSetConfig(); if (existingConfig == null) { LOG.warn("Couldn't load existing config for replica set from {}. Server not removed.", getServerAddress(), server); return false; } BasicBSONObject newConfig = ReplicaSetConfig.fromExistingConfig(existingConfig) .remove(server) .build(); return reconfigureReplicaSet(newConfig); }
Source:
<code>public void close() throws IOException { if (mCachedDataReader.deRef() > 0) { return; } try (LockResource lockResource = new LockResource(getLock(mBlockId).writeLock())) { if (mCachedDataReader.getRefCount() == 0) { BLOCK_READERS.remove(mBlockId); } } <START> if (mCachedDataReader.getRefCount() == 0) { mCachedDataReader.close(); <END> } }</code><technical_language>I this is atomic</technical_language>

Target:
public void close() throws IOException { if (mCachedDataReader.deRef() > 0) { return; } try (LockResource lockResource = new LockResource(getLock(mBlockId).writeLock())) { if (mCachedDataReader.getRefCount() == 0) { BLOCK_READERS.remove(mBlockId); mCachedDataReader.close(); } } }
Source:
<code>static void resetDir() throws IOException { <START> File f = new File("/tmp/" + System.getProperty("user.name")); <END> VoltFile.recursivelyDelete(f); f.mkdirs(); }</code><technical_language>This directory defined in a common place if want move another location is a single update</technical_language>

Target:
public static void resetDir() throws IOException { File f = new File("/tmp/" + System.getProperty("user.name")); VoltFile.recursivelyDelete(f); f.mkdirs(); }
Source:
<code>public static void removeStemTable(ETL etl) { Mapping<Table> mapping = etl.getTableToTableMapping(); List<Pair<Table, Table>> tablesMappingsToRemove = new ArrayList<>(); for (ItemToItemMap sourceToTargetMap : mapping.getSourceToTargetMaps()) { Table sourceTable = (Table) sourceToTargetMap.getSourceItem(); Table targetTable = (Table) sourceToTargetMap.getTargetItem(); if (sourceTable.isStem() || targetTable.isStem()) { tablesMappingsToRemove.add(new Pair<>(sourceTable, targetTable)); <START> etl.getFieldToFieldMapping(sourceTable, targetTable).removeAllSourceToTargetMaps(); <END> } } for (Pair<Table, Table> tableTablePair : tablesMappingsToRemove) { mapping.removeSourceToTargetMap(tableTablePair.getItem1(), tableTablePair.getItem2()); } Database sourceDatabase = etl.getSourceDatabase(); List<Table> newSourceTables = new ArrayList<>(); for (Table table : sourceDatabase.getTables()) { if (!table.isStem()) { newSourceTables.add(table); } } sourceDatabase.setTables(newSourceTables); Database targetDatabase = etl.getTargetDatabase(); List<Table> newTargetTables = new ArrayList<>(); for (Table table : targetDatabase.getTables()) { if (!table.isStem()) { newTargetTables.add(table); } } targetDatabase.setTables(newTargetTables); }</code><technical_language>Move this line 103</technical_language>

Target:
public static void removeStemTable(ETL etl) { Mapping<Table> mapping = etl.getTableToTableMapping(); List<Pair<Table, Table>> tablesMappingsToRemove = new ArrayList<>(); for (ItemToItemMap sourceToTargetMap : mapping.getSourceToTargetMaps()) { Table sourceTable = (Table) sourceToTargetMap.getSourceItem(); Table targetTable = (Table) sourceToTargetMap.getTargetItem(); if (sourceTable.isStem() || targetTable.isStem()) { tablesMappingsToRemove.add(new Pair<>(sourceTable, targetTable)); } } for (Pair<Table, Table> tableTablePair : tablesMappingsToRemove) { etl.getFieldToFieldMapping(tableTablePair.getItem1(), tableTablePair.getItem2()).removeAllSourceToTargetMaps(); mapping.removeSourceToTargetMap(tableTablePair.getItem1(), tableTablePair.getItem2()); } Database sourceDatabase = etl.getSourceDatabase(); List<Table> newSourceTables = new ArrayList<>(); for (Table table : sourceDatabase.getTables()) { if (!table.isStem()) { newSourceTables.add(table); } } sourceDatabase.setTables(newSourceTables); Database targetDatabase = etl.getTargetDatabase(); List<Table> newTargetTables = new ArrayList<>(); for (Table table : targetDatabase.getTables()) { if (!table.isStem()) { newTargetTables.add(table); } } targetDatabase.setTables(newTargetTables); }
Source:
<code>public Map<String, LocalCacheStats> getStats() { Map<String, LocalCacheStats> stats = createHashMap(statistics.size()); for (Map.Entry<String, CacheStatisticsImpl> entry : statistics.entrySet()) { String cacheName = entry.getKey(); LocalCacheStatsImpl localCacheStats = new LocalCacheStatsImpl(entry.getValue()); CompletableFuture<CacheConfig> configFuture = configs.get(cacheName); if (configFuture.isDone()) { try { localCacheStats.setNativeMemoryUsed(configFuture.get().getInMemoryFormat() == NATIVE); } catch (InterruptedException | ExecutionException e) { <START> e.printStackTrace(); <END> } } stats.put(cacheName, localCacheStats); } return stats; }</code><technical_language>logged, printed standard output</technical_language>

Target:
public Map<String, LocalCacheStats> getStats() { Map<String, LocalCacheStats> stats = createHashMap(statistics.size()); for (Map.Entry<String, CacheStatisticsImpl> entry : statistics.entrySet()) { String cacheName = entry.getKey(); LocalCacheStatsImpl localCacheStats = new LocalCacheStatsImpl(entry.getValue()); CompletableFuture<CacheConfig> configFuture = configs.get(cacheName); if (configFuture.isDone()) { try { localCacheStats.setInMemoryFormat(configFuture.get().getInMemoryFormat()); } catch (InterruptedException e) { logger.severe(e); Thread.currentThread().interrupt(); throw ExceptionUtil.rethrow(e); } catch (ExecutionException e) { } } stats.put(cacheName, localCacheStats); } return stats; }
Source:
<code>public AzureBlobStore(RepositoryMetadata metadata, AzureStorageService service, ThreadPool threadPool) { this.container = Repository.CONTAINER_SETTING.get(metadata.settings()); this.clientName = Repository.CLIENT_NAME.get(metadata.settings()); this.service = service; this.threadPool = threadPool; this.locationMode = Repository.LOCATION_MODE_SETTING.get(metadata.settings()); final Map<String, AzureStorageSettings> prevSettings = this.service.refreshAndClearCache(emptyMap()); final Map<String, AzureStorageSettings> newSettings = AzureStorageSettings.overrideLocationMode(prevSettings, this.locationMode); this.service.refreshAndClearCache(newSettings); this.getMetricsCollector = (httpURLConnection) -> { if (httpURLConnection.getRequestMethod().equalsIgnoreCase("HEAD")) { stats.headOperations.incrementAndGet(); return; } stats.getOperations.incrementAndGet(); }; this.listMetricsCollector = (httpURLConnection) -> stats.listOperations.incrementAndGet(); this.uploadMetricsCollector = (httpURLConnection -> { assert httpURLConnection.getRequestMethod().equals("PUT"); String queryParams = httpURLConnection.getURL().getQuery(); <START> if (queryParams != null && (queryParams.contains("comp=block") || queryParams.contains("comp=blocklist"))) { <END> stats.putBlockOperations.incrementAndGet(); } else { stats.putOperations.incrementAndGet(); } }); }</code><technical_language>queryParams.contains("comp=blocklist") is redundant it? safer require a blockid= if a comp=block in line expectations API requests here</technical_language>

Target:
public AzureBlobStore(RepositoryMetadata metadata, AzureStorageService service, ThreadPool threadPool) { this.container = Repository.CONTAINER_SETTING.get(metadata.settings()); this.clientName = Repository.CLIENT_NAME.get(metadata.settings()); this.service = service; this.threadPool = threadPool; this.locationMode = Repository.LOCATION_MODE_SETTING.get(metadata.settings()); final Map<String, AzureStorageSettings> prevSettings = this.service.refreshAndClearCache(emptyMap()); final Map<String, AzureStorageSettings> newSettings = AzureStorageSettings.overrideLocationMode(prevSettings, this.locationMode); this.service.refreshAndClearCache(newSettings); this.getMetricsCollector = (httpURLConnection) -> { if (httpURLConnection.getRequestMethod().equals("HEAD")) { stats.headOperations.incrementAndGet(); return; } assert httpURLConnection.getRequestMethod().equals("GET"); stats.getOperations.incrementAndGet(); }; this.listMetricsCollector = (httpURLConnection) -> { assert httpURLConnection.getRequestMethod().equals("GET"); stats.listOperations.incrementAndGet(); }; this.uploadMetricsCollector = (httpURLConnection -> { assert httpURLConnection.getRequestMethod().equals("PUT"); String queryParams = httpURLConnection.getURL().getQuery(); if (queryParams != null && isBlockUpload(queryParams)) { stats.putBlockOperations.incrementAndGet(); } else { stats.putOperations.incrementAndGet(); } }); }
Source:
<code>private <START> ArrayList<DataChangedEvent> <END> getRenamedEvents(Set<IComponentNamePO> renamedCompNames) { ArrayList<DataChangedEvent> events = new ArrayList<DataChangedEvent>(); for (IComponentNamePO compName : renamedCompNames) { events.add(new DataChangedEvent(compName, DataState.Renamed, UpdateState.all)); } return events; }</code><technical_language>Please interfaces possible</technical_language>

Target:
private List<DataChangedEvent> getRenamedEvents(Set<IComponentNamePO> renamedCompNames) { List<DataChangedEvent> events = new ArrayList<DataChangedEvent>(); for (IComponentNamePO compName : renamedCompNames) { events.add(new DataChangedEvent(compName, DataState.Renamed, UpdateState.all)); } return events; }
Source:
<code>public Snippet004HideSelection(Shell shell) { <START> int style = SWT.BORDER | SWT.FULL_SELECTION; <END> final TableViewer v = new TableViewer(shell, style); v.setLabelProvider(new LabelProvider()); v.setContentProvider(ArrayContentProvider.getInstance()); MyModel[] model = createModel(); v.setInput(model); v.getTable().setLinesVisible(true); v.getTable().addMouseListener(new MouseAdapter() { @Override public void mouseDown(MouseEvent e) { if (v.getTable().getItem(new Point(e.x, e.y)) == null) { v.setSelection(new StructuredSelection()); } } }); }</code><technical_language>typically set flag in constructor, I suggest change</technical_language>

Target:
public Snippet004HideSelection(Shell shell) { final TableViewer v = new TableViewer(shell, SWT.BORDER | SWT.FULL_SELECTION); v.setLabelProvider(new LabelProvider()); v.setContentProvider(ArrayContentProvider.getInstance()); MyModel[] model = createModel(); v.setInput(model); v.getTable().setLinesVisible(true); v.getTable().addMouseListener(new MouseAdapter() { @Override public void mouseDown(MouseEvent e) { if (v.getTable().getItem(new Point(e.x, e.y)) == null) { v.setSelection(new StructuredSelection()); } } }); }
Source:
<code>public List<NewsItem> fetchNews() { List<NewsItem> result = new ArrayList<>(); SyndFeedInput input = new SyndFeedInput(); SyndFeed feed = noCatch(() -> input.build(new XmlReader(new URL(newsFeedUrl)))); for (SyndEntry syndEntry : feed.getEntries()) { String author = syndEntry.getAuthor(); String link = syndEntry.getLink(); String title = syndEntry.getTitle(); String content = syndEntry.getContents().get(0).getValue(); Date publishedDate = syndEntry.getPublishedDate(); <START> NewsCategory newsCategory = NewsCategory.fromString(syndEntry.getCategories().get(0).getName()); <END> result.add(new NewsItem(author, link, title, content, publishedDate, newsCategory)); } return result; }</code><technical_language>get(0) fails if categories. NewsCategory newsCategory = syndEntry.getCategories().stream() .filter(Objects::nonNull) .findFirst() .map(Category::getName) .map(NewsCategory::fromString) .orElse(NewsCategory.UNCATEGORIZED) compiles</technical_language>

Target:
public List<NewsItem> fetchNews() { List<NewsItem> result = new ArrayList<>(); SyndFeedInput input = new SyndFeedInput(); SyndFeed feed = noCatch(() -> input.build(new XmlReader(new URL(newsFeedUrl)))); for (SyndEntry syndEntry : feed.getEntries()) { String author = syndEntry.getAuthor(); String link = syndEntry.getLink(); String title = syndEntry.getTitle(); String content = syndEntry.getContents().get(0).getValue(); Date publishedDate = syndEntry.getPublishedDate(); NewsCategory newsCategory = syndEntry.getCategories().stream() .filter(Objects::nonNull) .findFirst() .map(SyndCategory::getName) .map(NewsCategory::fromString) .orElse(NewsCategory.UNCATEGORIZED); result.add(new NewsItem(author, link, title, content, publishedDate, newsCategory)); } return result; }
Source:
<code>@Ignore public void testJoinWithMergeProjectShouldParse() { final String sql = "WITH query as (select empno, deptno as deptno11, deptno as deptno12 from emp)\n" + "select query.deptno11, emp.deptno, query.deptno12\n" + "FROM query\n" + "JOIN emp ON (cast(query.empno as Integer) = cast(emp.empno as Integer))"; <START> sql(sql).ok(); <END> }</code><technical_language>IMHO, propose is a workaround. Users encounter this error if wants merge project in RelBuilder. Instead of changing RelBuilder#shouldMergeProject false, I wondering if find root fix it</technical_language>

Target:
@Test public void testJoinWithMergeProjectShouldParse() { final String sql = "WITH query as " + " (select empno, deptno as deptno11, deptno as deptno12 from emp)\n" + "select query.deptno11, emp.deptno, query.deptno12\n" + "FROM query\n" + "JOIN emp ON (cast(query.empno as Integer) = cast(emp.empno as Integer))"; sql(sql).ok(); }
Source:
<code>public void onConnected(Bundle connectionHint) { Log.d(TAG, "onConnected(): Connection successful"); <START> setViewVisibility(); <END> if (connectionHint != null) { mTurnBasedMatch = connectionHint.getParcelable(Multiplayer.EXTRA_TURN_BASED_MATCH); } if (mTurnBasedMatch != null) { if (mGoogleApiClient == null || !mGoogleApiClient.isConnected()) { Log.d(TAG, "Warning: accessing TurnBasedMatch when not connected"); } updateMatch(mTurnBasedMatch); return; } Games.Invitations.registerInvitationListener(mGoogleApiClient, this); Games.TurnBasedMultiplayer.registerMatchUpdateListener(mGoogleApiClient, this); }</code><technical_language>In original code, this called if a turn - is this intended</technical_language>

Target:
public void onConnected(Bundle connectionHint) { Log.d(TAG, "onConnected(): Connection successful"); if (connectionHint != null) { mTurnBasedMatch = connectionHint.getParcelable(Multiplayer.EXTRA_TURN_BASED_MATCH); if (mTurnBasedMatch != null) { if (mGoogleApiClient == null || !mGoogleApiClient.isConnected()) { Log.d(TAG, "Warning: accessing TurnBasedMatch when not connected"); } updateMatch(mTurnBasedMatch); return; } } setViewVisibility(); Games.Invitations.registerInvitationListener(mGoogleApiClient, this); Games.TurnBasedMultiplayer.registerMatchUpdateListener(mGoogleApiClient, this); }
Source:
<code>public void testGetExistingDocWithIDInBatch() throws CouchbaseLiteException { final int NUM_DOCS = 10; <START> Database.getLog().getConsole().setLevel(LogLevel.VERBOSE); <END> createDocs(NUM_DOCS); db.inBatch(new Runnable() { @Override public void run() { validateDocs(NUM_DOCS); } }); }</code><technical_language>Is this for testing if console log works? delete if need it</technical_language>

Target:
public void testGetExistingDocWithIDInBatch() throws CouchbaseLiteException { final int NUM_DOCS = 10; createDocs(NUM_DOCS); db.inBatch(new Runnable() { @Override public void run() { validateDocs(NUM_DOCS); } }); }
Source:
<code>public void testCollapseExpandTreeRow() { SWTBotNatTable nattable = bot.nattable(); nattable.collaspeAll(new Position(1,1)); int count = nattable.preferredRowCount(); assertEquals("After collapse, 3 rows", 3, count); nattable.expandTreeRow(POSITION, 1); count = nattable.preferredRowCount(); assertEquals("After expandTreeRow, 16 rows", 16, count); nattable.expandAll(POSITION); count = nattable.preferredRowCount(); assertEquals("After expand, 49 rows", 49, count); nattable.collapseTreeRow(POSITION, 24); count = nattable.preferredRowCount(); <START> assertEquals("After expand, 49 rows", <END> 26, count); }</code><technical_language>collapse, 26 rows</technical_language>

Target:
public void testCollapseExpandTreeRow() { SWTBotNatTable nattable = bot.nattable(); nattable.collapseAll(new Position(1,1)); int count = nattable.preferredRowCount(); assertEquals("After collapse, 3 rows", 3, count); nattable.expandTreeRow(POSITION, 1); count = nattable.preferredRowCount(); assertEquals("After expandTreeRow, 16 rows", 16, count); nattable.expandAll(POSITION); count = nattable.preferredRowCount(); assertEquals("After expand, 49 rows", 49, count); nattable.collapseTreeRow(POSITION, 24); count = nattable.preferredRowCount(); assertEquals("After expand, 26 rows", 26, count); }
Source:
<code>public String getPropertyName(ExecutableElement getterOrSetterMethod) { String methodName = getterOrSetterMethod.getSimpleName().toString(); <START> if ( isFluentSetter( getterOrSetterMethod ) ) { <END> if ( ( methodName.startsWith( "get" ) || methodName.startsWith( "set" ) ) && methodName.length() > 3 && Character.isUpperCase( methodName.charAt( 3 ) ) ) { return IntrospectorUtils.decapitalize( methodName.substring( 3 ) ); } else { return methodName; } } return IntrospectorUtils.decapitalize( methodName.substring( methodName.startsWith( "is" ) ? 2 : 3 ) ); }</code><technical_language>feels a bit weird.. asserting method starts "get".. move isFluentSetter isFluent</technical_language>

Target:
public String getPropertyName(ExecutableElement getterOrSetterMethod) { String methodName = getterOrSetterMethod.getSimpleName().toString(); if ( isFluentSetter( getterOrSetterMethod ) ) { if ( methodName.startsWith( "set" ) && methodName.length() > 3 && Character.isUpperCase( methodName.charAt( 3 ) ) ) { return IntrospectorUtils.decapitalize( methodName.substring( 3 ) ); } else { return methodName; } } return IntrospectorUtils.decapitalize( methodName.substring( methodName.startsWith( "is" ) ? 2 : 3 ) ); }
Source:
<code>public void notifyServerCertificate(final Certificate serverCertificate) throws IOException { final JcaX509CertificateConverter converter = new JcaX509CertificateConverter().setProvider("BC"); final List<X509Certificate> x509Certs = Lists.newArrayList(); try { for (final org.bouncycastle.asn1.x509.Certificate cert : serverCertificate.getCertificateList()) { x509Certs.add(converter.getCertificate(new X509CertificateHolder(cert))); } } catch (CertificateException e) { <START> throw Throwables.propagate(e); <END> } serverCertificates = x509Certs.toArray(new X509Certificate[0]); }</code><technical_language>interface throws IOException package exception type</technical_language>

Target:
public void notifyServerCertificate(final Certificate serverCertificate) throws IOException { final JcaX509CertificateConverter converter = new JcaX509CertificateConverter().setProvider("BC"); final List<X509Certificate> x509Certs = Lists.newArrayList(); try { for (final org.bouncycastle.asn1.x509.Certificate cert : serverCertificate.getCertificateList()) { x509Certs.add(converter.getCertificate(new X509CertificateHolder(cert))); } } catch (CertificateException e) { throw new IOException("couldn't convert the server certificate", e); } serverCertificates = x509Certs.toArray(new X509Certificate[0]); }
Source:
<code>public EnvironmentDTO populate(ModelTranslator translator, Environment source, EnvironmentDTO dest) { if (source == null) { throw new IllegalArgumentException("source is null"); } if (dest == null) { throw new IllegalArgumentException("destination is null"); } Date created = source.getCreated(); <START> dest.created(created != null ? created.toInstant().atOffset(ZoneOffset.UTC) : null); Date updated = source.getUpdated(); dest.updated(updated != null ? updated.toInstant().atOffset(ZoneOffset.UTC) : null); <END> dest.id(source.getId()) .name(source.getName()) .description(source.getDescription()); if (translator != null) { Owner owner = source.getOwner(); dest.setOwner(owner != null ? translator.translate(owner, NestedOwnerDTO.class) : null); Set<EnvironmentContent> envContents = source.getEnvironmentContent(); if (envContents != null) { Set<EnvironmentContentDTO> setOfEnvironmentContents = new HashSet<>(); ObjectTranslator<Content, ContentDTO> contentTranslator = translator .findTranslatorByClass(Content.class, ContentDTO.class); for (EnvironmentContent ec : envContents) { if (ec != null) { ContentDTO dto = contentTranslator.translate(translator, ec.getContent()); if (dto != null) { setOfEnvironmentContents.add(new EnvironmentContentDTO() .content(dto) .enabled(ec.getEnabled())); } } } dest.setEnvironmentContent(setOfEnvironmentContents); } } else { dest.setOwner(null); dest.setEnvironmentContent(null); } return dest; }</code><technical_language>more minor change, apply in general on: org.candlepin.util.Util.toDateTime() a utility converter Date OffsetDateTime</technical_language>

Target:
public EnvironmentDTO populate(ModelTranslator translator, Environment source, EnvironmentDTO dest) { if (source == null) { throw new IllegalArgumentException("source is null"); } if (dest == null) { throw new IllegalArgumentException("destination is null"); } dest.created(Util.toDateTime(source.getCreated())) .updated(Util.toDateTime(source.getUpdated())) .id(source.getId()) .name(source.getName()) .description(source.getDescription()); if (translator != null) { Owner owner = source.getOwner(); dest.setOwner(owner != null ? translator.translate(owner, NestedOwnerDTO.class) : null); Set<EnvironmentContent> envContents = source.getEnvironmentContent(); if (envContents != null) { Set<EnvironmentContentDTO> setOfEnvironmentContents = new HashSet<>(); ObjectTranslator<Content, ContentDTO> contentTranslator = translator .findTranslatorByClass(Content.class, ContentDTO.class); for (EnvironmentContent ec : envContents) { if (ec != null) { ContentDTO dto = contentTranslator.translate(translator, ec.getContent()); if (dto != null) { setOfEnvironmentContents.add(new EnvironmentContentDTO() .content(dto) .enabled(ec.getEnabled())); } } } dest.setEnvironmentContent(setOfEnvironmentContents); } } else { dest.setOwner(null); dest.setEnvironmentContent(null); } return dest; }
Source:
<code>private String buildCredentialScope(String dateWithoutTimeStamp) { StringBuilder buffer = new StringBuilder(); buffer.append(dateWithoutTimeStamp).append("/"); buffer.append(REGION).append("/"); buffer.append(SERVICE).append("/"); buffer.append(TERMINATION_STRING); <START> return buffer.toString(); <END> }</code><technical_language>Reuse result of StringBuffer.append instead of buffer local variable</technical_language>

Target:
private static String buildCredentialScope(String dateWithoutTimeStamp) { return dateWithoutTimeStamp + "/" + REGION + "/" + SERVICE + "/" + TERMINATION_STRING; }
Source:
<code><START> private int getNumDaysInMonth(Calendar cal){ <END> int totalDays = cal.getActualMaximum(Calendar.DAY_OF_MONTH); cal.set(Calendar.DAY_OF_MONTH, 1); int monthStartWeekDay = cal.get(Calendar.DAY_OF_WEEK) - 1; int daysSincePreviousSunday = -monthStartWeekDay; totalDays += monthStartWeekDay; cal.add(Calendar.DAY_OF_MONTH, daysSincePreviousSunday); return totalDays; }</code><technical_language>This static</technical_language>

Target:
private static int getNumDaysInMonth(Calendar cal){ int totalDays = cal.getActualMaximum(Calendar.DAY_OF_MONTH); cal.set(Calendar.DAY_OF_MONTH, 1); int monthStartWeekDay = cal.get(Calendar.DAY_OF_WEEK) - 1; int daysSincePreviousSunday = -monthStartWeekDay; totalDays += monthStartWeekDay; cal.add(Calendar.DAY_OF_MONTH, daysSincePreviousSunday); return totalDays; }
Source:
<code>public boolean removeAll(Collection<?> c) { boolean removedSomething = false; <START> for (Object removeMe : c) { <END> removedSomething |= remove(removeMe); } return removedSomething; }</code><technical_language>s/removeMe/key/</technical_language>

Target:
public boolean removeAll(Collection<?> c) { boolean removedSomething = false; for (Object key : c) { removedSomething |= remove(key); } return removedSomething; }