auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static long makeUUID(byte mateId, byte libraryId, long readId, int offset) { <START> if (mateId != (mateId & ~(-1 << bitsForMate))) <END> throw new IllegalArgumentException("byte specified for mateId will lose some of its bits when saved! (was: " + mateId + " but only allowed " + bitsForMate + " bits!"); if (libraryId != (libraryId & ~(-1 << bitsForLibrary))) throw new IllegalArgumentException("byte specified for libraryId will lose some of its bits when saved! (was: " + libraryId + " but only allowed " + bitsForLibrary + " bits!"); if (readId != (readId & ~(-1 << bitsForReadId))) throw new IllegalArgumentException("byte specified for readId will lose some of its bits when saved! (was: " + readId + " but only allowed " + bitsForReadId + " bits!"); if (offset != (offset & ~(-1 << bitsForLibrary))) throw new IllegalArgumentException("byte specified for offset will lose some of its bits when saved! (was: " + offset + " but only allowed " + offset + " bits!"); return ((mateId << mateIdShift) + (libraryId << libraryIdShift) + (readId << readIdShift) + (offset << offsetShift)); }</code><technical_language>advantage of -1</technical_language>

Target:
public static long makeUUID(byte mateId, byte libraryId, long readId, int offset) { if (mateId != (mateId & ~(-1 << bitsForMate))) throw new IllegalArgumentException("byte specified for mateId will lose some of its bits when saved! (was: " + mateId + " but only allowed " + bitsForMate + " bits!"); if (libraryId != (libraryId & ~(-1 << bitsForLibrary))) throw new IllegalArgumentException("byte specified for libraryId will lose some of its bits when saved! (was: " + libraryId + " but only allowed " + bitsForLibrary + " bits!"); if (readId != (readId & ~(-1 << bitsForReadId))) throw new IllegalArgumentException("byte specified for readId will lose some of its bits when saved! (was: " + readId + " but only allowed " + bitsForReadId + " bits!"); if (offset != (offset & ~(-1 << bitsForOffset))) throw new IllegalArgumentException("byte specified for offset will lose some of its bits when saved! (was: " + offset + " but only allowed " + offset + " bits!"); return ((offset << offsetShift) + (libraryId << libraryIdShift) + (mateId << mateIdShift) + (readId << readIdShift)); }
Source:
<code>private Set<SignatureAlgorithm> parseAlgorithms(JWKSet jwkSet) { <START> if (jwkSet == null) { <END> return Collections.emptySet(); } List<JWK> jwks = new ArrayList<>(); for (JWK jwk : jwkSet.getKeys()) { KeyUse keyUse = jwk.getKeyUse(); if (keyUse != null && keyUse.equals(KeyUse.SIGNATURE)) { jwks.add(jwk); } } Set<SignatureAlgorithm> algorithms = new HashSet<>(); for (JWK jwk : jwks) { Algorithm algorithm = jwk.getAlgorithm(); if (algorithm != null) { SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.from(algorithm.getName()); if (signatureAlgorithm != null) { algorithms.add(signatureAlgorithm); } } } return algorithms; }</code><technical_language>This feels error situation. If keys back, authorization server able sign keys? I throwing IllegalStateException is returning empty set in this case</technical_language>

Target:
private Set<SignatureAlgorithm> parseAlgorithms(JWKSet jwkSet) { if (jwkSet == null) { throw new IllegalArgumentException(String.format("No JWKs received from %s", jwkSetUri)); } List<JWK> jwks = new ArrayList<>(); for (JWK jwk : jwkSet.getKeys()) { KeyUse keyUse = jwk.getKeyUse(); if (keyUse != null && keyUse.equals(KeyUse.SIGNATURE)) { jwks.add(jwk); } } Set<SignatureAlgorithm> algorithms = new HashSet<>(); for (JWK jwk : jwks) { Algorithm algorithm = jwk.getAlgorithm(); if (algorithm != null) { SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.from(algorithm.getName()); if (signatureAlgorithm != null) { algorithms.add(signatureAlgorithm); } } } return algorithms; }
Source:
<code>public PsAll(final List<? extends Pass> passes, final int identity) { <START> this.all = passes; <END> this.index = identity; if (this.index < 0) { throw new IllegalArgumentException("Index must be >= 0"); } if (this.index >= this.all.size()) { throw new IllegalArgumentException( String.format( "Trying to return index %s from a list of %s passes", this.index, this.all.size() ) ); } }</code><technical_language>@Suseika clone list instead assignment</technical_language>

Target:
public PsAll(final List<? extends Pass> passes, final int identity) { this.all = new ArrayList<Pass>(passes); this.index = identity; if (this.index < 0) { throw new IllegalArgumentException("Index must be >= 0"); } if (this.index >= this.all.size()) { throw new IllegalArgumentException( String.format( "Trying to return index %s from a list of %s passes", this.index, this.all.size() ) ); } }
Source:
<code><START> public synchronized void incGeneration() { <END> currentGeneration++; }</code><technical_language>time generally a practice synchronize object other users end lead surprising locking issues. a private Object a lock. However, is real coordination of state here, opt currentGeneration AtomicInt CAS update it. Reads cheaper too</technical_language>

Target:
public void incGeneration() { currentGeneration.incrementAndGet(); }
Source:
<code>public void testJmxRegistrationAtStartupAndStop(Method m) throws Exception { final String otherJmxDomain = getMethodSpecificJmxDomain(m, JMX_DOMAIN); CacheContainer otherContainer = TestCacheManagerFactory.createCacheManagerEnforceJmxDomain(otherJmxDomain, true, false); ObjectName otherName = getCacheManagerObjectName(otherJmxDomain); try { assertEquals("0", server.getAttribute(otherName, "CreatedCacheCount")); } finally { otherContainer.stop(); } <START> try { <END> server.getAttribute(otherName, "CreatedCacheCount").equals("0"); fail("Failure expected, " + otherName + " shouldn't be registered in mbean server"); } catch (InstanceNotFoundException e) { } }</code><technical_language>Exceptions.expectException(). .equals("0") is in line Exceptions.expectException(InstanceNotFoundException.class, () -> server.getAttribute(otherName, "CreatedCacheCount"));</technical_language>

Target:
public void testJmxRegistrationAtStartupAndStop(Method m) throws Exception { final String otherJmxDomain = getMethodSpecificJmxDomain(m, JMX_DOMAIN); CacheContainer otherContainer = TestCacheManagerFactory.createCacheManagerEnforceJmxDomain(otherJmxDomain, true, false); ObjectName otherName = getCacheManagerObjectName(otherJmxDomain); try { assertEquals("0", server.getAttribute(otherName, "CreatedCacheCount")); } finally { otherContainer.stop(); } Exceptions.expectException(InstanceNotFoundException.class, () -> server.getAttribute(otherName, "CreatedCacheCount")); }
Source:
<code>public Path createDirectory(Path parent, String name, String... files) { Path directory = parent.resolve(name); try { java.nio.file.Files.createDirectory(directory); Arrays.stream(files) .forEach(f -> { try { java.nio.file.Files.createFile(directory.resolve(f)); } catch (IOException e) { assertThat(e).describedAs("Should not happen").isNull(); } <START> }); <END> } catch (IOException e) { assertThat(e).describedAs("Should not happen").isNull(); } return directory; }</code><technical_language>For readability, extract a private method a method reference in forEach</technical_language>

Target:
public Path createDirectory(Path parent, String name, String... files) { Path directory = parent.resolve(name); try { java.nio.file.Files.createDirectory(directory); Arrays.stream(files) .forEach(f -> createFile(directory, f)); } catch (IOException e) { throw new UncheckedIOException("error during fixture directory creation", e); } return directory; }
Source:
<code>public Page getOutput() { if ((state != State.FINISHING) || !finishFuture.isDone()) { return null; } state = State.FINISHED; Collection<Slice> fragments = getFutureValue(finishFuture); PageBuilder page = new PageBuilder(fragments.size() + 2, TYPES); BlockBuilder rowsBuilder = page.getBlockBuilder(0); BlockBuilder fragmentBuilder = page.getBlockBuilder(1); BlockBuilder operatorExecutionInfoBuilder = page.getBlockBuilder(2); page.declarePosition(); BIGINT.writeLong(rowsBuilder, rowCount); fragmentBuilder.appendNull(); operatorExecutionInfoBuilder.appendNull(); for (Slice fragment : fragments) { page.declarePosition(); rowsBuilder.appendNull(); VARBINARY.writeSlice(fragmentBuilder, fragment); operatorExecutionInfoBuilder.appendNull(); } page.declarePosition(); rowsBuilder.appendNull(); fragmentBuilder.appendNull(); TaskId taskId = operatorContext.getDriverContext().getPipelineContext().getTaskId(); OperatorExecutionContext operatorExecutionContext = new OperatorExecutionContext(operatorContext.getDriverContext().getLifespan(), taskId.getStageId().getId(), taskId.getId()); <START> Slice operatorExecutionContextSlice = wrappedBuffer(OPERATOR_EXECUTION_CONTEXT_JSON_CODEC.toJsonBytes(operatorExecutionContext)); <END> VARBINARY.writeSlice(operatorExecutionInfoBuilder, operatorExecutionContextSlice); return page.build(); }</code><technical_language>nit: this inlined</technical_language>

Target:
public Page getOutput() { if ((state != State.FINISHING) || !finishFuture.isDone()) { return null; } state = State.FINISHED; Collection<Slice> fragments = getFutureValue(finishFuture); int positionCount = fragments.size() + 1; BlockBuilder rowsBuilder = BIGINT.createBlockBuilder(null, positionCount); BlockBuilder fragmentBuilder = VARBINARY.createBlockBuilder(null, positionCount); rowsBuilder.writeLong(rowCount); fragmentBuilder.appendNull(); for (Slice fragment : fragments) { rowsBuilder.appendNull(); VARBINARY.writeSlice(fragmentBuilder, fragment); } TaskId taskId = operatorContext.getDriverContext().getPipelineContext().getTaskId(); Slice tableCommitContext = wrappedBuffer(tableCommitContextCodec.toJsonBytes( new TableCommitContext( operatorContext.getDriverContext().getLifespan(), taskId.getStageId().getId(), taskId.getId(), false, true))); return new Page(positionCount, rowsBuilder.build(), fragmentBuilder.build(), RunLengthEncodedBlock.create(VARBINARY, tableCommitContext, positionCount)); }
Source:
<code>static void printAndReset() { for (int size : memoryUsages.keySet()) { System.out.println(String.format("\nfor %d elements", size)); for (String usages : memoryUsages.get(size).get()) { System.out.println("\t" + usages); } } <START> memoryUsages = memoryUsages.dropWhile(v -> true); END> }</code><technical_language>if take(0)? _(We clear() removed user request looked mutable is Scala.)_</technical_language>

Target:
static void printAndReset() { for (int size : memoryUsages.keySet()) { System.out.println(String.format("\nfor %d elements", size)); for (String usages : memoryUsages.get(size).get()) { System.out.println("\t" + usages); } } memoryUsages = memoryUsages.take(0); }
Source:
<code><START> public <T> T[] toArray(@Nullable T[] a) { <END> if (a == null) { throw new IllegalArgumentException(); } fLock.readLock().lock(); try { int size = size(); @SuppressWarnings("unchecked") final @NonNull T[] ret = checkNotNull((T[]) Array.newInstance(a.getClass().getComponentType(), size)); int i = 0; for (E elem : this) { @SuppressWarnings("unchecked") T arrayElem = (T) elem; ret[i++] = arrayElem; } return ret; } finally { fLock.readLock().unlock(); } }</code><technical_language>fstarttimesindex.values.toArray(a); ? is avoid concurrent modifications? wrap in immutablelist</technical_language>

Target:
public <T> T[] toArray(@Nullable T[] a) { fLock.readLock().lock(); try { return checkNotNull(fStartTimesIndex.values().toArray(a)); } finally { fLock.readLock().unlock(); } }
Source:
<code>private void updateController() { this.controller = modelProvider.getModel(); final GridTimer modelTimer = getModelTimer(); final boolean wasTimerActive = modelTimer.isActive(); if (statusUpdateHandlerRegistration != null) { statusUpdateHandlerRegistration.removeHandler(); } statusUpdateHandlerRegistration = modelTimer.addValueChangeHandler(new ValueChangeHandler<String>() { @Override public void onValueChange(ValueChangeEvent<String> event) { onRefresh(modelTimer.getValue()); } }); if (wasTimerActive) { <START> modelTimer.start(); <END> } }</code><technical_language>If GridTimer.active == true timer is in of states: * started running * started paused do need start timer here? (The updateController method is invoked early part of AbstractRefreshManager constructor.) If need start timer here, call GridTimer.resume method instead, resets GridTimer.paused flag false invokes GridTimer.start method</technical_language>

Target:
private void updateController() { this.controller = modelProvider.getModel(); updateTimer(); }
Source:
<code>public void testSplitColumnInvalidType() throws DbException { final Schema schema = new Schema(ImmutableList.of(Type.LONG_TYPE), ImmutableList.of("long")); final TupleBatchBuffer input = new TupleBatchBuffer(schema); input.putLong(0, 1L); Split splitOp = new Split(new TupleSource(input), 0, ":"); splitOp.open(TestEnvVars.get()); <START> splitOp.close(); <END> }</code><technical_language>close necessary</technical_language>

Target:
public void testSplitColumnInvalidType() throws DbException { final Schema schema = Schema.ofFields("long", Type.LONG_TYPE); final TupleBatchBuffer input = new TupleBatchBuffer(schema); input.putLong(0, 1L); Split splitOp = new Split(new TupleSource(input), 0, ":"); splitOp.open(TestEnvVars.get()); }
Source:
<code>public static String getVolumeName(String userName) { <START> Objects.nonNull(userName); <END> return DigestUtils.md5Hex(userName); }</code><technical_language>I here, requireNotNull(userName)</technical_language>

Target:
public static String getVolumeName(String userName) { Objects.requireNonNull(userName); return DigestUtils.md5Hex(userName); }
Source:
<code>public List<ITmfStateInterval> queryHistoryRange(int attributeQuark, long t1, long t2, long resolution, IProgressMonitor monitor) throws TimeRangeException, AttributeNotFoundException, StateSystemDisposedException { if (isDisposed) { throw new StateSystemDisposedException(); } List<ITmfStateInterval> intervals; ITmfStateInterval currentInterval; long ts, tEnd; IProgressMonitor mon = monitor; if (mon == null) { mon = new NullProgressMonitor(); } if (t2 < t1 || resolution <= 0) { throw new TimeRangeException(); } if (t2 > this.getCurrentEndTime()) { tEnd = this.getCurrentEndTime(); } else { tEnd = t2; } intervals = new ArrayList<>(); currentInterval = querySingleState(t1, attributeQuark); intervals.add(currentInterval); for (ts = t1; ts < tEnd; ts += ((currentInterval.getEndTime() - ts) / resolution + 1) * resolution) { if (mon.isCanceled()) { return intervals; } currentInterval = querySingleState(ts, attributeQuark); intervals.add(currentInterval); } <START> if (currentInterval.getEndTime() < tEnd) { <END> currentInterval = querySingleState(tEnd, attributeQuark); intervals.add(currentInterval); } return intervals; }</code><technical_language>I necessary if want interval t2</technical_language>

Target:
public List<ITmfStateInterval> queryHistoryRange(int attributeQuark, long t1, long t2, long resolution, IProgressMonitor monitor) throws TimeRangeException, AttributeNotFoundException, StateSystemDisposedException { if (isDisposed) { throw new StateSystemDisposedException(); } List<ITmfStateInterval> intervals = new LinkedList<>(); ITmfStateInterval currentInterval; long ts, tEnd; IProgressMonitor mon = monitor; if (mon == null) { mon = new NullProgressMonitor(); } if (t2 < t1 || resolution <= 0) { throw new TimeRangeException(); } if (t2 > this.getCurrentEndTime()) { tEnd = this.getCurrentEndTime(); } else { tEnd = t2; } for (ts = t1; ts <= tEnd; ts += ((currentInterval.getEndTime() - ts) / resolution + 1) * resolution) { if (mon.isCanceled()) { return intervals; } currentInterval = querySingleState(ts, attributeQuark); intervals.add(currentInterval); } return intervals; }
Source:
<code>public IPropertyDescriptor[] getPropertyDescriptors() { <START> Map<String, String> envVariables = getTraceProperties(); <END> if (!envVariables.isEmpty()) { IPropertyDescriptor[] propertyDescriptorArray = new IPropertyDescriptor[envVariables.size()+sfDescriptors.length]; int index =0; for (Map.Entry<String, String> varName : envVariables.entrySet()) { ReadOnlyTextPropertyDescriptor descriptor = new ReadOnlyTextPropertyDescriptor(varName.getKey(), varName.getKey()); descriptor.setCategory(sfTracePropertiesCategory); propertyDescriptorArray[index] = descriptor; index++; } for(int i=0; i<sfDescriptors.length; i++) { propertyDescriptorArray[index] = sfDescriptors[i]; index++; } return propertyDescriptorArray; } return Arrays.copyOf(sfDescriptors, sfDescriptors.length); }</code><technical_language>Suggest rename traceProperties</technical_language>

Target:
public IPropertyDescriptor[] getPropertyDescriptors() { Map<String, String> traceProperties = getTraceProperties(); if (!traceProperties.isEmpty()) { IPropertyDescriptor[] propertyDescriptorArray = new IPropertyDescriptor[traceProperties.size() + sfDescriptors.length]; int index = 0; for (Map.Entry<String, String> varName : traceProperties.entrySet()) { ReadOnlyTextPropertyDescriptor descriptor = new ReadOnlyTextPropertyDescriptor(this.getName() + "_" + varName.getKey(), varName.getKey()); descriptor.setCategory(sfTracePropertiesCategory); propertyDescriptorArray[index] = descriptor; index++; } for (int i = 0; i < sfDescriptors.length; i++) { propertyDescriptorArray[index] = sfDescriptors[i]; index++; } return propertyDescriptorArray; } return Arrays.copyOf(sfDescriptors, sfDescriptors.length); }
Source:
<code>public static void hl7v2MessageList(String hl7v2StoreName) throws IOException { CloudHealthcare client = createClient(); String pageToken = null; try { Messages.List request = client .projects() .locations() .datasets() .hl7V2Stores() .messages() .list(hl7v2StoreName) .setPageSize(100) .setPageToken(pageToken); ListMessagesResponse response; do { response = request.execute(); if (response.getHl7V2Messages() == null) { continue; } System.out.printf("Retrieved %s HL7v2 messages: \n", response.getHl7V2Messages().size()); for (Message message : response.getHl7V2Messages()) { System.out.println("\t" + message); } request.setPageToken(response.getNextPageToken()); } while (response.getNextPageToken() != null); } catch (IOException e) { <START> System.out.println("Unable to list HL7v2 messages: \n" + e.toString()); <END> } }</code><technical_language>need extra \n println</technical_language>

Target:
public static void hl7v2MessageList(String hl7v2StoreName) throws IOException { CloudHealthcare client = createClient(); String pageToken = null; try { Messages.List request = client .projects() .locations() .datasets() .hl7V2Stores() .messages() .list(hl7v2StoreName) .setPageSize(100) .setPageToken(pageToken); ListMessagesResponse response; do { response = request.execute(); if (response.getHl7V2Messages() == null) { continue; } System.out.printf("Retrieved %s HL7v2 messages: \n", response.getHl7V2Messages().size()); for (Message message : response.getHl7V2Messages()) { System.out.println("\t" + message); } request.setPageToken(response.getNextPageToken()); } while (response.getNextPageToken() != null); } catch (IOException e) { System.out.println("Unable to list HL7v2 messages:" + e.toString()); } }
Source:
<code>public void ValidationStereotypesListClass3Test() { EList<Stereotype> appliedStereotypes = class3.getAppliedStereotypes(); List<Stereotype> expectedStereotypes = new ArrayList<Stereotype>(); expectedStereotypes.add(stereotype1); expectedStereotypes.add(stereotype3); <START> assertEquals(appliedStereotypes, expectedStereotypes); <END> }</code><technical_language>Please add error message</technical_language>

Target:
public void ValidationStereotypesListClass3Test() { EList<Stereotype> appliedStereotypes = class3.getAppliedStereotypes(); List<Stereotype> expectedStereotypes = new ArrayList<Stereotype>(); expectedStereotypes.add(stereotype1); expectedStereotypes.add(stereotype3); assertEquals("The stereotypes applied on the class must be the same as the expected stereotypes.", appliedStereotypes, expectedStereotypes); }
Source:
<code>protected void compute(CoreSession session, List<String> ids, Map<String, Serializable> properties) { Map<String, Serializable> actualProperties = new HashMap<>(properties); String eventId = (String) actualProperties.remove(NOTIFY); Collection<DocumentRef> refs = ids.stream().map(IdRef::new).collect(Collectors.toList()); ids.forEach(id -> actualProperties.forEach((k, v) -> session.setDocumentSystemProp(new IdRef(id), k, v))); session.save(); if (eventId != null) { EventService eventService = Framework.getService(EventService.class); DocumentModelList docs = session.getDocuments(refs.toArray(new DocumentRef[refs.size()])); docs.forEach(d -> { <START> DocumentEventContext ctx = new DocumentEventContext(session, session.getPrincipal(), d); <END> ctx.setProperties(new HashMap<>(d.getContextData())); ctx.setCategory(DocumentEventCategories.EVENT_DOCUMENT_CATEGORY); ctx.setProperty(CoreEventConstants.REPOSITORY_NAME, session.getRepositoryName()); ctx.setProperty(CoreEventConstants.SESSION_ID, session.getSessionId()); Event event = ctx.newEvent(eventId); event.setInline(false); event.setImmediate(false); eventService.fireEvent(event); }); } }</code><technical_language>extract this a raiseEvent method</technical_language>

Target:
protected void compute(CoreSession session, List<String> ids, Map<String, Serializable> properties) { Map<String, Serializable> actualProperties = new HashMap<>(properties); String eventId = (String) actualProperties.remove(NOTIFY); Collection<DocumentRef> refs = ids.stream().map(IdRef::new).collect(Collectors.toList()); ids.forEach(id -> actualProperties.forEach((k, v) -> session.setDocumentSystemProp(new IdRef(id), k, v))); session.save(); if (eventId != null) { fireEvent(session, eventId, refs); } }
Source:
<code>public void should_balance_requests_across_connections() throws InterruptedException { CqlSession session = SESSION_RULE.session(); int simultaneousRequests = CONNECTIONS * REQUESTS_PER_CONNECTION; ExecutorService requestExecutor = Executors.newFixedThreadPool(simultaneousRequests); AtomicReference<Throwable> unexpectedErrorRef = new AtomicReference<>(); ScheduledExecutorService timeoutExecutor = Executors.newScheduledThreadPool(1); CountDownLatch done = new CountDownLatch(1); for (int i = 0; i < simultaneousRequests; i++) { requestExecutor.submit( () -> { while (!Thread.currentThread().isInterrupted()) { try { session.execute("SELECT release_version FROM system.local"); } catch (Throwable t) { unexpectedErrorRef.compareAndSet(null, t); done.countDown(); } } }); } <START> timeoutExecutor.schedule(done::countDown, 5, SECONDS); <END> done.await(); Throwable unexpectedError = unexpectedErrorRef.get(); if (unexpectedError != null) { fail("At least one request failed unexpectedly", unexpectedError); } requestExecutor.shutdownNow(); timeoutExecutor.shutdownNow(); }</code><technical_language>this test wait 5 seconds, if is error time finish, right? Is a reason is 5 seconds</technical_language>

Target:
public void should_balance_requests_across_connections() throws InterruptedException { int simultaneousRequests = POOL_SIZE * REQUESTS_PER_CONNECTION; for (int i = 0; i < simultaneousRequests; i++) { reschedule(null, null); } SECONDS.sleep(1); done.countDown(); Throwable unexpectedError = unexpectedErrorRef.get(); if (unexpectedError != null) { fail("At least one request failed unexpectedly", unexpectedError); } }
Source:
<code>public void allParentObjectShouldBeInChangeSet() { Realm realm = looperThread.realm; realm.beginTransaction(); Owner owner = realm.createObject(Owner.class); Dog dog1 = realm.createObject(Dog.class); <START> dog1.setHasTail(true); <END> dog1.setOwner(owner); owner.getDogs().add(dog1); Dog dog2 = realm.createObject(Dog.class); dog2.setOwner(owner); dog2.setHasTail(true); owner.getDogs().add(dog2); Dog dog3 = realm.createObject(Dog.class); dog3.setOwner(owner); dog3.setHasTail(true); owner.getDogs().add(dog3); realm.commitTransaction(); RealmResults<Dog> dogs = realm.where(Dog.class).equalTo(Dog.FIELD_HAS_TAIL, true).findAll(); looperThread.keepStrongReference.add(dogs); dogs.addChangeListener(new OrderedRealmCollectionChangeListener<RealmResults<Dog>>() { @Override public void onChange(RealmResults<Dog> collection, OrderedCollectionChangeSet changeSet) { assertEquals(1, changeSet.getDeletions().length); assertEquals(0, changeSet.getInsertions().length); assertEquals(1, changeSet.getChangeRanges().length); assertEquals(0, changeSet.getChangeRanges()[0].startIndex); assertEquals(2, changeSet.getChangeRanges()[0].length); looperThread.testComplete(); } }); realm.beginTransaction(); dog3.setHasTail(false); realm.commitTransaction(); looperThread.testComplete(); }</code><technical_language>Swap this line next setHasTail/setOwner in order for dogs</technical_language>

Target:
public void allParentObjectShouldBeInChangeSet() { Realm realm = looperThread.realm; realm.beginTransaction(); Owner owner = realm.createObject(Owner.class); Dog dog1 = realm.createObject(Dog.class); dog1.setOwner(owner); dog1.setHasTail(true); owner.getDogs().add(dog1); Dog dog2 = realm.createObject(Dog.class); dog2.setOwner(owner); dog2.setHasTail(true); owner.getDogs().add(dog2); Dog dog3 = realm.createObject(Dog.class); dog3.setOwner(owner); dog3.setHasTail(true); owner.getDogs().add(dog3); realm.commitTransaction(); RealmResults<Dog> dogs = realm.where(Dog.class).equalTo(Dog.FIELD_HAS_TAIL, true).findAll(); looperThread.keepStrongReference.add(dogs); dogs.addChangeListener(new OrderedRealmCollectionChangeListener<RealmResults<Dog>>() { @Override public void onChange(RealmResults<Dog> collection, OrderedCollectionChangeSet changeSet) { assertEquals(1, changeSet.getDeletions().length); assertEquals(0, changeSet.getInsertions().length); assertEquals(1, changeSet.getChangeRanges().length); assertEquals(0, changeSet.getChangeRanges()[0].startIndex); assertEquals(2, changeSet.getChangeRanges()[0].length); looperThread.testComplete(); } }); realm.beginTransaction(); dog3.setHasTail(false); realm.commitTransaction(); looperThread.testComplete(); }
Source:
<code>public void persistComponent(DistributionSnapshot snapshot, ComponentInfo ci, CoreSession session, String label, DocumentModel parent) { DocumentModel componentDoc = createComponentDoc(snapshot, session, label, ci, parent); for (ExtensionPointInfo epi : ci.getExtensionPoints()) { createExtensionPointDoc(snapshot, session, label, epi, componentDoc); } Map<String, Integer> comps = new HashMap<String, Integer>(); for (ExtensionInfo ei : ci.getExtensions()) { <START> String id = ei.getId(); if (comps.containsKey(id)) { comps.put(id, comps.get(id) + 1); } else { comps.put(id, Integer.valueOf(0)); } createContributionDoc(snapshot, session, label, ei, comps.get(id), componentDoc); } for (ServiceInfo si : ci.getServices()) { <END> createServiceDoc(snapshot, session, label, si, componentDoc); } }</code><technical_language>simplified to: java String id = ei.getId(); comps.computeIfPresent(id, (k,v) -> v + 1); comps.computeIfAbsent(id, -> Integer.valueOf(0));</technical_language>

Target:
public void persistComponent(DistributionSnapshot snapshot, ComponentInfo ci, CoreSession session, String label, DocumentModel parent) { DocumentModel componentDoc = createComponentDoc(snapshot, session, label, ci, parent); for (ExtensionPointInfo epi : ci.getExtensionPoints()) { createExtensionPointDoc(snapshot, session, label, epi, componentDoc); } Map<String, AtomicInteger> comps = new HashMap<>(); for (ExtensionInfo ei : ci.getExtensions()) { String id = ei.getId(); comps.computeIfAbsent(id, k -> new AtomicInteger(-1)).incrementAndGet(); createContributionDoc(snapshot, session, label, ei, comps.get(id).get(), componentDoc); } for (ServiceInfo si : ci.getServices()) { createServiceDoc(snapshot, session, label, si, componentDoc); } }
Source:
<code>private DhisDataValueStatusResponse importDataValues(Settings settings, String uri, String json) { HttpUriRequest request = generatePostRequest(settings, uri, json); LOGGER.debug(String.format("Initiating request to create resource: %s, request: %s", json, request.toString())); CloseableHttpResponse response = getResponseForRequest(request); DhisDataValueStatusResponse status; try (InputStream content = getContentForResponse(response)) { String contentString = IOUtils.toString(content); LOGGER.debug(String.format("Received response to create resource: %s, request: %s", json, contentString)); status = new ObjectMapper().readValue(contentString, DhisDataValueStatusResponse.class); if (status.getStatus() == DhisStatus.ERROR) { String msg = String.format("Error in DHIS2 status response, error details: %s", contentString); throw new DhisWebException(msg); <START> } <END> } catch (IOException e) { String msg = String.format("Error parsing response from uri: %s, exception: %s", uri, e.toString()); statusMessageService.warn(msg, MODULE_NAME); throw new DhisWebException(msg, e); } finally { closeResponse(response); } return status; }</code><technical_language>create separate method for this, this is code</technical_language>

Target:
private DhisDataValueStatusResponse importDataValues(Settings settings, String uri, String json) { HttpUriRequest request = generatePostRequest(settings, uri, json); LOGGER.debug(String.format("Initiating request to create resource: %s, request: %s", json, request.toString())); CloseableHttpResponse response = getResponseForRequest(request); return (DhisDataValueStatusResponse) getDhisResponseForHttpResponse(json, uri, response, DhisDataValueStatusResponse.class); }
Source:
<code>private void handleResult( AdminResult result, Throwable error, Function<Iterable<AdminRow>, CassandraSchemaRows.Builder> builderUpdater, boolean warnIfMissing) { if (error != null) { if (warnIfMissing || !error.getMessage().contains("does not exist")) { Loggers.warnWithException( LOG, "[{}] Error during schema refresh, new metadata might be incomplete", logPrefix, error); } } else { schemaRowsBuilder = builderUpdater.apply(result); if (result.hasNextPage()) { result .nextPage() .whenCompleteAsync( (nextResult, nextError) -> handleResult(nextResult, nextError, builderUpdater, warnIfMissing), adminExecutor); <START> return; <END> } } pendingQueries -= 1; if (pendingQueries == 0) { LOG.debug("[{}] Schema queries took {}", logPrefix, NanoTime.formatTimeSince(startTimeNs)); schemaRowsFuture.complete(schemaRowsBuilder.build()); } }</code><technical_language>if/else version a bit clearer</technical_language>

Target:
private void handleResult( AdminResult result, Throwable error, Function<Iterable<AdminRow>, CassandraSchemaRows.Builder> builderUpdater, boolean warnIfMissing) { if (error != null) { if (warnIfMissing || !error.getMessage().contains("does not exist")) { Loggers.warnWithException( LOG, "[{}] Error during schema refresh, new metadata might be incomplete", logPrefix, error); } markQueryComplete(); } else { schemaRowsBuilder = builderUpdater.apply(result); if (result.hasNextPage()) { result .nextPage() .whenCompleteAsync( (nextResult, nextError) -> handleResult(nextResult, nextError, builderUpdater, warnIfMissing), adminExecutor); } else { markQueryComplete(); } } }
Source:
<code>public static void main(String[] argv) throws Exception { CommandLineParser parser = new PosixParser(); Options options = new Options(); options.addOption("f", "file", true, "File of new structure information."); options.addOption("e", "eperson", true, "User who is manipulating the repository's structure."); options.addOption("o", "output", true, "File to receive the structure map."); options.addOption("x", "export", false, "Export the current structure as XML."); options.addOption("h", "help", false, "Print this help message."); CommandLine line = parser.parse( options, argv ); if (line.hasOption('h')) { giveHelp(options); System.exit(0); } String file = null; String eperson = null; String output = null; if (line.hasOption('f')) { file = line.getOptionValue('f'); } if (line.hasOption('e')) { eperson = line.getOptionValue('e'); } if (line.hasOption('o')) { output = line.getOptionValue('o'); } if (output == null) { usage(options); System.exit(1); } Context context = new Context(); context.setCurrentUser(ePersonService.findByEmail(context, eperson)); if (line.hasOption('x')) { <START> exportStructure(context, output); <END> } else if (line.hasOption('f')) { if (eperson == null) { usage(options); System.exit(1); } importStructure(context, file, output); } else { usage(options); System.exit(1); } System.exit(0); }</code><technical_language>a logged-in user I guess hit auth issue communities collections Anonymous READ</technical_language>

Target:
public static void main(String[] argv) throws Exception { CommandLineParser parser = new PosixParser(); Options options = new Options(); options.addOption("f", "file", true, "File of new structure information."); options.addOption("e", "eperson", true, "User who is manipulating the repository's structure."); options.addOption("o", "output", true, "File to receive the structure map."); options.addOption("x", "export", false, "Export the current structure as XML."); options.addOption("h", "help", false, "Print this help message."); CommandLine line = parser.parse( options, argv ); if (line.hasOption('h')) { giveHelp(options); System.exit(0); } if (!(line.hasOption('f') || line.hasOption('x'))) { giveHelp(options); System.exit(1); } String input = null; String eperson = null; String output = null; if (line.hasOption('f')) { input = line.getOptionValue('f'); } if (line.hasOption('e')) { eperson = line.getOptionValue('e'); } else { usage(options); System.exit(1); } if (line.hasOption('o')) { output = line.getOptionValue('o'); } else { usage(options); System.exit(1); } OutputStream outputStream; if ("-".equals(output)) { outputStream = System.out; } else { outputStream = new FileOutputStream(output); } Context context = new Context(); context.setCurrentUser(ePersonService.findByEmail(context, eperson)); if (line.hasOption('x')) { exportStructure(context, outputStream); } else { InputStream inputStream; if ("-".equals(input)) { inputStream = System.in; } else { inputStream = new FileInputStream(input); } importStructure(context, inputStream, outputStream); } System.exit(0); }
Source:
<code>static void moderateComment(final int accountId, final Comment comment, final CommentStatus newStatus, final CommentActionListener actionListener) { if (newStatus != null && (newStatus.equals(CommentStatus.TRASH) || newStatus.equals(CommentStatus.DELETE))) { deleteComment(accountId, comment, actionListener, newStatus.equals(CommentStatus.DELETE)); return; } final Blog blog = WordPress.getBlog(accountId); if (blog==null || comment==null || newStatus==null || newStatus==CommentStatus.UNKNOWN) { if (actionListener != null) actionListener.onActionResult(new CommentActionResult(CommentActionResult.COMMENT_ID_ON_ERRORS, null)); return; } final Handler handler = new Handler(); new Thread() { @Override public void run() { @SuppressWarnings("UnusedAssignment") <START> XMLRPCClientInterface client = XMLRPCFactory.instantiate(blog.getUri(), blog.getHttpuser(), <END> blog.getHttppassword()); final boolean success = ApiHelper.editComment(blog, comment, newStatus); if (success) { CommentTable.updateCommentStatus(blog.getLocalTableBlogId(), comment.commentID, CommentStatus .toString(newStatus)); } if (actionListener != null) { handler.post(new Runnable() { @Override public void run() { actionListener.onActionResult(new CommentActionResult(comment.commentID, null)); } }); } } }.start(); }</code><technical_language>get rid of this, client anywhere</technical_language>

Target:
static void moderateComment(final int accountId, final Comment comment, final CommentStatus newStatus, final CommentActionListener actionListener) { if (newStatus != null && (newStatus.equals(CommentStatus.TRASH) || newStatus.equals(CommentStatus.DELETE))) { deleteComment(accountId, comment, actionListener, newStatus.equals(CommentStatus.DELETE)); return; } final Blog blog = WordPress.getBlog(accountId); if (blog==null || comment==null || newStatus==null || newStatus==CommentStatus.UNKNOWN) { if (actionListener != null) actionListener.onActionResult(new CommentActionResult(CommentActionResult.COMMENT_ID_ON_ERRORS, null)); return; } final Handler handler = new Handler(); new Thread() { @Override public void run() { final boolean success = ApiHelper.editComment(blog, comment, newStatus); if (success) { CommentTable.updateCommentStatus(blog.getLocalTableBlogId(), comment.commentID, CommentStatus .toString(newStatus)); } if (actionListener != null) { handler.post(new Runnable() { @Override public void run() { actionListener.onActionResult(new CommentActionResult(comment.commentID, null)); } }); } } }.start(); }
Source:
<code>static List<String> annotationKeys(QueryRequest request) { if (request.annotations.isEmpty() && request.binaryAnnotations.isEmpty()) { return Collections.emptyList(); } <START> checkArgument(request.serviceName != null, "serviceName needed with annotation query"); <END> List<String> annotationKeys = new ArrayList<>(); annotationKeys.add(request.serviceName); for (String a : request.annotations) { if (!annotationKeys.contains(a)) annotationKeys.add(a); } for (Map.Entry<String, String> b : request.binaryAnnotations.entrySet()) { if (!annotationKeys.contains(b.getKey() + ":" + b.getValue())) annotationKeys.add(b.getKey() + ":" + b.getValue()); } return annotationKeys; }</code><technical_language>basically is edge case, request.annotations a key in request.binaryAnnotations.. dedupe in request object instead.. bother switch list a risk of accidentally making query twice.. wdyt</technical_language>

Target:
static List<String> annotationKeys(QueryRequest request) { if (request.annotations.isEmpty() && request.binaryAnnotations.isEmpty()) { return Collections.emptyList(); } checkArgument(request.serviceName != null, "serviceName needed with annotation query"); Set<String> annotationKeys = new HashSet<>(); annotationKeys.add(request.serviceName); for (String a : request.annotations) { annotationKeys.add(a); } for (Map.Entry<String, String> b : request.binaryAnnotations.entrySet()) { annotationKeys.add(b.getKey() + ":" + b.getValue()); } return sortedList(annotationKeys); }
Source:
<code>public static File makeTimeFile(File dir, ByteOrder order) { <START> return new File(dir, StringUtils.safeFormat("time_%s.drd", order)); <END> }</code><technical_language>crash if bad format string</technical_language>

Target:
public static File makeTimeFile(File dir, ByteOrder order) { return new File(dir, StringUtils.format("time_%s.drd", order)); }
Source:
<code>public void sortInput(InputStream inputStream) throws IOException { <START> InputStreamReader inputStreamReader = new InputStreamReader(inputStream); <END> BufferedReader reader = new BufferedReader(inputStreamReader); String line; while ((line = reader.readLine()) != null) { if (line.trim().length() == 0) { continue; } inputStrings.add(line.trim()); } reader.close(); Collections.sort(inputStrings); }</code><technical_language>This code is trappy. a good idea do InputStreamReader(inputStream, StandardCharsets.UTF-8) instead encoding is set UTF-8 relying platform's encoding</technical_language>

Target:
public void sortInput(InputStream inputStream) throws IOException { InputStreamReader inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8); BufferedReader reader = new BufferedReader(inputStreamReader); String line; while ((line = reader.readLine()) != null) { if (line.trim().length() == 0) { continue; } inputStrings.add(line.trim()); } reader.close(); Collections.sort(inputStrings); }
Source:
<code>private void nextReference() { if (!hasMoreReferences) { throw new RuntimeException("Cannot get next reference - already at last one"); } try { hasMoreReferences = referencesChunksIterator.hasNext(); if (!hasMoreReferences) { hasMoreAlignments = false; return; } currentReference++; Chunk refChunk = referencesChunksIterator.next(); if (refChunk == null) { hasMoreAlignments = false; return; } Reference reference = cachedReferences.get(currentReference); if (reference == null) { synchronized (cachedReferences) { reference = cachedReferences.get(currentReference); if (reference == null) { reference = run.getReference(header.getSequence(currentReference).getSequenceName()); cachedReferences.set(currentReference, reference); } } <START> } <END> alignedIterator = reference.getFilteredAlignmentSlice( refChunk.getChunkStart(), refChunk.getChunkEnd() - refChunk.getChunkStart(), Alignment.all, Alignment.startWithinSlice, 0); hasMoreAlignments = alignedIterator.nextAlignment(); } catch (ErrorMsg e) { throw new RuntimeException(e); } }</code><technical_language>This is a questionable-looking block of code. If want caching thread-safe, references cache ThreadLocal, create a ReferenceCache wrapper class synchronized methods</technical_language>

Target:
private void nextReference() { if (!hasMoreReferences) { throw new NoSuchElementException("Cannot get next reference - already at last one"); } try { hasMoreReferences = referencesChunksIterator.hasNext(); if (!hasMoreReferences) { hasMoreAlignments = false; return; } currentReference++; Chunk refChunk = referencesChunksIterator.next(); if (refChunk == null) { hasMoreAlignments = false; return; } Reference reference = cachedReferences.get(currentReference); alignedIterator = reference.getFilteredAlignmentSlice( refChunk.getChunkStart(), refChunk.getChunkEnd() - refChunk.getChunkStart(), Alignment.all, Alignment.startWithinSlice | Alignment.passDuplicates | Alignment.passFailed, 0); hasMoreAlignments = alignedIterator.nextAlignment(); } catch (ErrorMsg e) { throw new RuntimeException(e); } }
Source:
<code>public Node alloc(String label) { <START> Node b = map.get(label); <END> if ( b == null ) { b = create(); map.put(label, b); } return b; }</code><technical_language>return map.computeIfAbsent(x->create())</technical_language>

Target:
public Node alloc(String label) { return map.computeIfAbsent(label, x->create()); }
Source:
<code>public List<CategoryDTO> fetchInstallableApplications() { final Map<ApplicationsSource, List<CategoryDTO>> categoriesMap = this.applicationsSources.parallelStream() .collect( Collectors.toConcurrentMap(source -> source, ApplicationsSource::fetchInstallableApplications)); if (applicationsSources.isEmpty()) <START> return Collections.emptyList(); <END> final List<ApplicationsSource> tmpApplicationsSources = new ArrayList<>(applicationsSources); Collections.reverse(tmpApplicationsSources); final Map<String, CategoryDTO> mergedCategories = createSortedMap( categoriesMap.get(tmpApplicationsSources.remove(0)), CategoryDTO::getName); for (ApplicationsSource otherApplicationsSource : tmpApplicationsSources) { final List<CategoryDTO> otherCategories = categoriesMap.get(otherApplicationsSource); final Map<String, CategoryDTO> otherCategoriesMap = createSortedMap(otherCategories, CategoryDTO::getName); for (String categoryName : otherCategoriesMap.keySet()) { final CategoryDTO category = otherCategoriesMap.get(categoryName); if (mergedCategories.containsKey(categoryName)) { mergedCategories.put(categoryName, mergeCategories(mergedCategories.get(categoryName), category)); } else { mergedCategories.put(categoryName, category); } } } return new ArrayList<>(mergedCategories.values()); }</code><technical_language>Please put braces</technical_language>

Target:
public List<CategoryDTO> fetchInstallableApplications() { final Map<ApplicationsSource, List<CategoryDTO>> categoriesMap = Arrays.stream(this.applicationsSources) .parallel().collect( Collectors.toConcurrentMap(source -> source, ApplicationsSource::fetchInstallableApplications)); return mergeApplicationsSources(categoriesMap, applicationsSources); }
Source:
<code>SMTPConnectionPool(Vertx vertx, MailConfig config) { this.config = config; maxSockets = config.getMaxPoolSize(); <START> keepAlive = config.isKeepAlive(); <END> this.authOperationFactory = new AuthOperationFactory(new PRNG(vertx)); NetClientOptions netClientOptions = new NetClientOptions() .setSsl(config.isSsl()) .setTrustAll(config.isTrustAll()) .setEnabledSecureTransportProtocols(config.getEnabledSecureTransportProtocols()); if ((config.isSsl() || config.getStarttls() != StartTLSOptions.DISABLED) && !config.isTrustAll()) { netClientOptions.setHostnameVerificationAlgorithm("HTTPS"); } if (config.getKeyStore() != null) { netClientOptions.setTrustStoreOptions(new JksOptions().setPath(config.getKeyStore()) .setPassword(config.getKeyStorePassword())); } netClient = vertx.createNetClient(netClientOptions); }</code><technical_language>this, close of pool, close PRNG object avoid re-seediing in background needed</technical_language>

Target:
SMTPConnectionPool(Vertx vertx, MailConfig config) { this.config = config; maxSockets = config.getMaxPoolSize(); keepAlive = config.isKeepAlive(); this.prng = new PRNG(vertx); this.authOperationFactory = new AuthOperationFactory(prng); NetClientOptions netClientOptions = new NetClientOptions() .setSsl(config.isSsl()) .setTrustAll(config.isTrustAll()) .setEnabledSecureTransportProtocols(config.getEnabledSecureTransportProtocols()); if ((config.isSsl() || config.getStarttls() != StartTLSOptions.DISABLED) && !config.isTrustAll()) { netClientOptions.setHostnameVerificationAlgorithm("HTTPS"); } if (config.getKeyStore() != null) { netClientOptions.setTrustStoreOptions(new JksOptions().setPath(config.getKeyStore()) .setPassword(config.getKeyStorePassword())); } netClient = vertx.createNetClient(netClientOptions); }
Source:
<code>public void testHighFreqStatsSwapping() { List<Metric> finalList = new ArrayList<>(); for (int y = 0; y < 5; y++) { for (int x = 0; x < 3; x++) { List<Metric> list = new ArrayList<>(); for (int i = 0; i < 20; i++) { list.add( new Metric( "KEY" + y, 42.0 + i, new Date(), ImmutableSet.of(), Map.of("tag1", "value1", "what", "fun"), ImmutableMap.of(), null)); } finalList.addAll(shortSwapDetector.detect(list)); <START> sleep(300); <END> } } assertEquals(280, finalList.size()); }</code><technical_language>this sleep for a total of 300ms * 3 * 5 = 4.5 seconds. Is cool w.r.t. making unit tests run slower</technical_language>

Target:
public void testHighFreqStatsSwapping() { List<Metric> finalList = new ArrayList<>(); for (int y = 0; y < 5; y++) { for (int x = 0; x < 3; x++) { List<Metric> list = new ArrayList<>(); for (int i = 0; i < 20; i++) { list.add( new Metric( "KEY" + y, 42.0 + i, new Date(), ImmutableSet.of(), Map.of("tag1", "value1", "what", "fun"), ImmutableMap.of(), null)); } finalList.addAll(shortSwapDetector.detect(list)); try { Thread.sleep(300); } catch (InterruptedException e) { } } } assertEquals(280, finalList.size()); }
Source:
<code><START> private int nextBuf(byte[] buffer, int bufOffset) { <END> int ret; if (len - off < buffer.length - bufOffset) { ret = (int) (len - off); } else { ret = buffer.length - bufOffset; } int i; for (i = 0; i < ret; i += 6) { fillBytesImpl(buffer, i + bufOffset); } off += ret; return ret + bufOffset; }</code><technical_language>public please mentioned above</technical_language>

Target:
public int nextBuf(byte[] buffer, int bufOffset) { int ret; if (len - off < buffer.length - bufOffset) { ret = (int) (len - off); } else { ret = buffer.length - bufOffset; } int i; for (i = 0; i < ret; i += 6) { fillBytesImpl(buffer, i + bufOffset); } off += ret; return ret + bufOffset; }