auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public List<Resource> getResources(PerunSession sess, Map<String, String> attributesWithSearchingValues, boolean allowPartialMatchForString) throws PrivilegeException, InternalErrorException, AttributeNotExistsException, WrongAttributeAssignmentException { <START> if (!AuthzResolver.authorizedInternal(sess, "getResources_Map<String, String>_policy", Collections.emptyList())) <END> throw new PrivilegeException(sess, "getResources"); return searcherBl.getResources(sess, attributesWithSearchingValues, allowPartialMatchForString); }</code><technical_language>question ", " above</technical_language>

Target:
public List<Resource> getResources(PerunSession sess, Map<String, String> attributesWithSearchingValues, boolean allowPartialMatchForString) throws PrivilegeException, InternalErrorException, AttributeNotExistsException, WrongAttributeAssignmentException { if (!AuthzResolver.authorizedInternal(sess, "getResources_Map<String_String>_policy")) throw new PrivilegeException(sess, "getResources"); return searcherBl.getResources(sess, attributesWithSearchingValues, allowPartialMatchForString); }
Source:
<code><START> public UriPrefixingClientHttpRequestFactory(ClientHttpRequestFactory factory, URI uriPrefix) { <END> this.wrapped = notNull(factory, "factory"); this.prefixer = new UriPrefixer(uriPrefix); }</code><technical_language>more need for public, I guess</technical_language>

Target:
UriPrefixingClientHttpRequestFactory(ClientHttpRequestFactory factory, URI uriPrefix) { this.wrapped = notNull(factory, "factory"); this.prefixer = new UriPrefixer(uriPrefix); }
Source:
<code>public void bytesConverterTypeParseTest() { <START> Map<String, KafkaSerDe.BytesConverterType> testCases = new HashMap<String, KafkaSerDe.BytesConverterType>() {{ <END> put("confluent", KafkaSerDe.BytesConverterType.CONFLUENT); put("conFLuent", KafkaSerDe.BytesConverterType.CONFLUENT); put("Confluent", KafkaSerDe.BytesConverterType.CONFLUENT); put("CONFLUENT", KafkaSerDe.BytesConverterType.CONFLUENT); put(" confluent ", KafkaSerDe.BytesConverterType.CONFLUENT); put("skip", KafkaSerDe.BytesConverterType.SKIP); put("sKIp", KafkaSerDe.BytesConverterType.SKIP); put("SKIP", KafkaSerDe.BytesConverterType.SKIP); put(" skip ", KafkaSerDe.BytesConverterType.SKIP); put("SKIP1", KafkaSerDe.BytesConverterType.NONE); put("skipper", KafkaSerDe.BytesConverterType.NONE); put("", KafkaSerDe.BytesConverterType.NONE); put(null, KafkaSerDe.BytesConverterType.NONE); put("none", KafkaSerDe.BytesConverterType.NONE); put("NONE", KafkaSerDe.BytesConverterType.NONE); put(" none ", KafkaSerDe.BytesConverterType.NONE); }}; for(Map.Entry<String, KafkaSerDe.BytesConverterType> entry: testCases.entrySet()){ Assert.assertEquals(entry.getValue(), KafkaSerDe.BytesConverterType.fromString(entry.getKey())); } }</code><technical_language>Nit: double brace. This implemented a parameterized test</technical_language>

Target:
public void bytesConverterTypeParseTest() { Map<String, KafkaSerDe.BytesConverterType> testCases = new HashMap<String, KafkaSerDe.BytesConverterType>() {{ put("skip", KafkaSerDe.BytesConverterType.SKIP); put("sKIp", KafkaSerDe.BytesConverterType.SKIP); put("SKIP", KafkaSerDe.BytesConverterType.SKIP); put(" skip ", KafkaSerDe.BytesConverterType.SKIP); put("SKIP1", KafkaSerDe.BytesConverterType.NONE); put("skipper", KafkaSerDe.BytesConverterType.NONE); put("", KafkaSerDe.BytesConverterType.NONE); put(null, KafkaSerDe.BytesConverterType.NONE); put("none", KafkaSerDe.BytesConverterType.NONE); put("NONE", KafkaSerDe.BytesConverterType.NONE); }}; for(Map.Entry<String, KafkaSerDe.BytesConverterType> entry: testCases.entrySet()) { Assert.assertEquals(entry.getValue(), KafkaSerDe.BytesConverterType.fromString(entry.getKey())); } }
Source:
<code>public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { if (!alreadyEncoded(responseContext)) { for (Encoding encoding : ENCODINGS) { if (acceptsEncoding(requestContext, encoding.encoding)) { MultivaluedMap<String, Object> headers = responseContext.getHeaders(); headers.add(HttpHeaders.VARY, HttpHeaders.ACCEPT_ENCODING); headers.add(HttpHeaders.CONTENT_ENCODING, encoding.encoding); <START> responseContext.setEntityStream(encoding.compressor.apply(responseContext.getEntityStream())); <END> } } } }</code><technical_language>return decide encode avoid double encoding</technical_language>

Target:
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { if (isTooSmall(responseContext) || isEncoded(responseContext) || isUncompressable(responseContext)) { return; } List<String> headerLines = requestContext.getHeaders().get(HttpHeaders.ACCEPT_ENCODING); if (headerLines == null) { return; } List<String> acceptedEncodings = parsedHeaders.getUnchecked(headerLines); for (Encoding encoding : Encoding.values()) { if (acceptedEncodings.contains(encoding.encoding)) { MultivaluedMap<String, Object> headers = responseContext.getHeaders(); headers.add(HttpHeaders.VARY, HttpHeaders.ACCEPT_ENCODING); headers.add(HttpHeaders.CONTENT_ENCODING, encoding.encoding); responseContext.setEntityStream(encoding.compressor.apply(responseContext.getEntityStream())); return; } } }
Source:
<code>public void testFindWorkingVersionHTMLPage() throws Exception{ String ext="."+Config.getStringProperty("VELOCITY_PAGE_EXTENSION"); Template template=new Template(); template.setTitle("TEST TEMPLATE VERSIONABLE"); template.setBody("<html><body> I'm mostly empty </body></html>"); <START> template=APILocator.getTemplateAPI().saveTemplate(template, host, user, false); <END> Folder folder = APILocator.getFolderAPI().createFolders("/testingVersionable", host, user, false); HTMLPage page=new HTMLPage(); page.setPageUrl("testpage"+ext); page.setFriendlyName("testpage"+ext); page.setTitle("testpage"+ext); page=APILocator.getHTMLPageAPI().saveHTMLPage(page, template, folder, user, false); Versionable verAPI = APILocator.getVersionableAPI().findWorkingVersion(page.getIdentifier(), user, false); assertEquals(verAPI.getTitle(),page.getTitle()); assertEquals(verAPI.getInode(),page.getInode()); APILocator.getHTMLPageAPI().delete(page, user, false); APILocator.getFolderAPI().delete(folder, user, false); APILocator.getTemplateAPI().delete(template, user, false); }</code><technical_language>lines for template creation replaced by: Template template = new TemplateDataGen().nextPersisted();</technical_language>

Target:
public void testFindWorkingVersionHTMLPage() throws Exception{ HTMLPage page = createHTMLPage(); Versionable verAPI = APILocator.getVersionableAPI().findWorkingVersion(page.getIdentifier(), user, false); assertEquals(verAPI.getTitle(),page.getTitle()); assertEquals(verAPI.getInode(),page.getInode()); Folder folder = APILocator.getHTMLPageAPI().getParentFolder(page); Template template = APILocator.getHTMLPageAPI().getTemplateForWorkingHTMLPage(page); APILocator.getHTMLPageAPI().delete(page, user, false); APILocator.getFolderAPI().delete(folder, user, false); APILocator.getTemplateAPI().delete(template, user, false); }
Source:
<code>private JsonResult getInstructorJoinStatus(String regkey) { InstructorAttributes instructor = logic.getInstructorForRegistrationKey(regkey); if (instructor == null) { return new JsonResult("No instructor with given registration key: " + regkey, HttpStatus.SC_NOT_FOUND); } String institute = getRequestParamValue(Const.ParamsNames.INSTRUCTOR_INSTITUTION); String mac = getRequestParamValue(Const.ParamsNames.INSTITUTION_MAC); if (institute != null && !StringHelper.isCorrectSignature(institute, mac)) { <START> return new JsonResult("Error in URL validation. Please re-check the URL.", HttpStatus.SC_BAD_REQUEST); <END> } return getJoinStatusResult(instructor.isRegistered()); }</code><technical_language>done manual testing ensure this is displayed correctly</technical_language>

Target:
private JsonResult getInstructorJoinStatus(String regkey) { InstructorAttributes instructor = logic.getInstructorForRegistrationKey(regkey); if (instructor == null) { return new JsonResult("No instructor with given registration key: " + regkey, HttpStatus.SC_NOT_FOUND); } return getJoinStatusResult(instructor.isRegistered()); }
Source:
<code>private Source getMockSource() throws UnsupportedQueryException { Source mockSource = mock(Source.class); <START> when(mockSource.getId()).thenReturn("1"); <END> when(mockSource.query(any(QueryRequest.class))).thenReturn(mockResponse); return mockSource; }</code><technical_language>Source ids supposed unique. CachingFederationStrategy care, accurate system is supposed behave. prefer mock normal behavior making ids unique scope of unit test</technical_language>

Target:
private Source getMockSource() throws UnsupportedQueryException { Source mockSource = mock(Source.class); when(mockSource.getId()).thenReturn(UUID.randomUUID().toString()); when(mockSource.query(any(QueryRequest.class))).thenReturn(mockResponse); return mockSource; }
Source:
<code>public List<TaskDTO> findAll(String sort, Integer offset, Integer size, Map filters) throws DataException { <START> <END> LoginForm login = (LoginForm) Helper.getManagedBeanValue("#{LoginForm}"); if (login == null) { return new ArrayList<>(); } BoolQueryBuilder subquery = new BoolQueryBuilder(); subquery.should(createSimpleQuery("processingUser", login.getMyBenutzer().getId(), true)); subquery.should(createSimpleQuery("users.id", login.getMyBenutzer().getId(), true)); for (UserGroup userGroup : login.getMyBenutzer().getUserGroups()) { subquery.should(createSimpleQuery("userGroups.id", userGroup.getId(), true)); } BoolQueryBuilder query = new BoolQueryBuilder(); query.must(subquery); query.must(createSimpleQuery("processingStatus", TaskStatus.LOCKED.getValue(), false)); query.must(createSimpleQuery("processingStatus", TaskStatus.DONE.getValue(), false)); AktuelleSchritteForm form = (AktuelleSchritteForm) Helper.getManagedBeanValue("#{AktuelleSchritteForm}"); if (form.getHideCorrectionTasks()) { query.must(createSimpleQuery("priority", 10, true)); } if (!form.getShowAutomaticTasks()) { query.must(createSimpleQuery("typeAutomatic", "false", true)); } return convertJSONObjectsToDTOs(searcher.findDocuments(query.toString(), sort, offset, size), false); }</code><technical_language>query is written times. build in private method called some get...Query method</technical_language>

Target:
public List<TaskDTO> findAll(String sort, Integer offset, Integer size, Map filters) throws DataException { LoginForm login = (LoginForm) Helper.getManagedBeanValue("#{LoginForm}"); if (login == null) { return new ArrayList<>(); } BoolQueryBuilder query = createUserTaskQuery(login); return convertJSONObjectsToDTOs(searcher.findDocuments(query.toString(), sort, offset, size), false); }
Source:
<code>public String toString() { <START> switch (this) { <END> case TIME: return "SCHEDULE"; case LOAD: return "LOAD"; case METRIC: return "METRIC"; case PROMETHEUS: return "PROMETHEUS"; default: throw new IllegalArgumentException(); } }</code><technical_language>is opinion convert .name() other case</technical_language>

Target:
public String toString() { switch (this) { case TIME: return "SCHEDULE"; default: return name(); } }
Source:
<code>public Attachment createAttachment(PersistableBusinessObject parent, String uploadedFileName, String mimeType, int fileSize, InputStream fileContents, String attachmentTypeCode) throws IOException { if(parent == null) { throw new IllegalArgumentException("invalid (null or uninitialized) document"); } else if(StringUtils.isBlank(uploadedFileName)) { throw new IllegalArgumentException("invalid (blank) fileName"); } else if(StringUtils.isBlank(mimeType)) { throw new IllegalArgumentException("invalid (blank) mimeType"); } else if(fileSize <= 0) { throw new IllegalArgumentException("invalid (non-positive) fileSize"); } else if(fileContents == null) { throw new IllegalArgumentException("invalid (null) inputStream"); } else { byte[] fileContentsAsByteArray = IOUtils.toByteArray(fileContents); InputStream fileContentsToScan = new ByteArrayInputStream(fileContentsAsByteArray); <START> if (!ScanResult.Status.PASSED.equals(antiVirusService.scan(fileContentsToScan).getStatus())) { <END> LOG.error("createAttachment, virus protection failure! uploadedFileName: " + uploadedFileName + " mimeType: " + mimeType + " attachmentTypeCode: " + attachmentTypeCode + " parent object: " + parent); throw new IllegalArgumentException("file contents failed virus scan"); } else { InputStream fileContentsForAttachment = new ByteArrayInputStream(fileContentsAsByteArray); return super.createAttachment(parent, uploadedFileName, mimeType, fileSize, fileContentsForAttachment, attachmentTypeCode); } } }</code><technical_language>of data returned ScanResult object logged well</technical_language>

Target:
public Attachment createAttachment(PersistableBusinessObject parent, String uploadedFileName, String mimeType, int fileSize, InputStream fileContents, String attachmentTypeCode) throws IOException { if(parent == null) { throw new IllegalArgumentException("invalid (null or uninitialized) document"); } else if(StringUtils.isBlank(uploadedFileName)) { throw new IllegalArgumentException("invalid (blank) fileName"); } else if(StringUtils.isBlank(mimeType)) { throw new IllegalArgumentException("invalid (blank) mimeType"); } else if(fileSize <= 0) { throw new IllegalArgumentException("invalid (non-positive) fileSize"); } else if(fileContents == null) { throw new IllegalArgumentException("invalid (null) inputStream"); } else { byte[] fileContentsAsByteArray = IOUtils.toByteArray(fileContents); InputStream fileContentsToScan = new ByteArrayInputStream(fileContentsAsByteArray); ScanResult virusScanResults = antiVirusService.scan(fileContentsToScan); if (!ScanResult.Status.PASSED.equals(virusScanResults.getStatus())) { LOG.error("createAttachment, virus protection failure! uploadedFileName: " + uploadedFileName + ", mimeType: " + mimeType + ", attachmentTypeCode: " + attachmentTypeCode + ", scan result: " + virusScanResults.getStatus() + ", parent object: " + parent); throw new IllegalArgumentException("file contents failed virus scan"); } else { InputStream fileContentsForAttachment = new ByteArrayInputStream(fileContentsAsByteArray); return super.createAttachment(parent, uploadedFileName, mimeType, fileSize, fileContentsForAttachment, attachmentTypeCode); } } }
Source:
<code>public LuceneAnalysisDefinitionTranslationMapBuilder(Class<D> targetClass) { <START> super(); <END> this.targetClass = targetClass; }</code><technical_language>super(); needed</technical_language>

Target:
public LuceneAnalysisDefinitionTranslationMapBuilder(Class<D> targetClass) { this.targetClass = targetClass; }
Source:
<code>public CRAMFileWriter(final OutputStream outputStream, final OutputStream indexOS, final boolean presorted, final ReferenceSource referenceSource, final SAMFileHeader samFileHeader, final String fileName) { if (outputStream == null) { throw new IllegalArgumentException("CRAMWriter output stream can not be null."); } if (referenceSource == null) { throw new IllegalArgumentException("A reference is required for CRAM writers"); } if (samFileHeader == null) { <START> throw new IllegalArgumentException("A valid SAMFileHeader is required for CRAM writers"); <END> } this.outputStream = outputStream; this.samFileHeader = samFileHeader; this.fileName = fileName; initCRAMWriter(indexOS, referenceSource, samFileHeader, presorted); }</code><technical_language>If Defaults.REFERENCE_FASTA is set, is remaining mechanism for propagating CRAMFileWriter? calling ReferenceSource.getDefaultCRAMReferenceSource()</technical_language>

Target:
public CRAMFileWriter(final OutputStream outputStream, final OutputStream indexOS, final boolean presorted, final ReferenceSource referenceSource, final SAMFileHeader samFileHeader, final String fileName) { if (outputStream == null) { throw new IllegalArgumentException("CRAMWriter output stream can not be null."); } if (referenceSource == null) { throw new IllegalArgumentException("A reference is required for CRAM writers"); } if (samFileHeader == null) { throw new IllegalArgumentException("A valid SAMFileHeader is required for CRAM writers"); } this.samFileHeader = samFileHeader; this.fileName = fileName; setSortOrder(samFileHeader.getSortOrder(), presorted); cramContainerStream = new CRAMContainerStreamWriter(outputStream, indexOS, referenceSource, samFileHeader, fileName); setHeader(samFileHeader); }
Source:
<code>public void savePinTypesListState(){ sizepinTypeTitleInputs = pinTypeTitleInputs.size(); sizeuploadMarker = uploadMarker.size(); <START> sizeparentCatElements = parentCatElements.size(); <END> PageObjectLogging.log("savePinTypesListState", "State of pin types list is saved", true); }</code><technical_language>variables start "size"</technical_language>

Target:
public void savePinTypesListState() { amountPinTypeTitleInputs = pinTypeTitleInputs.size(); amountUploadMarker = uploadMarker.size(); amountParentCatElements = parentCatElements.size(); PageObjectLogging.log("savePinTypesListState", "State of pin types list is saved", true); }
Source:
<code>FlatRow readRows( final ByteString rowKey, final ColumnFamily columnFamily, final ReadRowsRequest request, final Function<ByteString, Boolean> matchesColumn ) { final FlatRow.Builder builder = FlatRow.newBuilder().withRowKey(rowKey); storage .entrySet() .stream() .filter(e -> { final boolean matches = matchesColumn.apply(e.getKey()); final Optional<RowFilter> filter = request.getFilter(); <START> System.out.println(filter); <END> return matches; }) .map(column -> FlatRow.Cell .newBuilder() .withFamily(columnFamily.getName()) .withQualifier(column.getKey()) .withValue(column.getValue()) .build()) .forEach(builder::addCell); return builder.build(); }</code><technical_language>Rogue console output</technical_language>

Target:
FlatRow readRows( final ByteString rowKey, final ColumnFamily columnFamily, final ReadRowsRequest request, final Function<ByteString, Boolean> matchesColumn ) { final FlatRow.Builder builder = FlatRow.newBuilder().withRowKey(rowKey); storage .entrySet() .stream() .filter(e -> { final boolean matches = matchesColumn.apply(e.getKey()); final Optional<RowFilter> filter = request.getFilter(); return matches; }) .map(column -> FlatRow.Cell .newBuilder() .withFamily(columnFamily.getName()) .withQualifier(column.getKey()) .withValue(column.getValue()) .build()) .forEach(builder::addCell); return builder.build(); }
Source:
<code>public void removeItem(final DataType dataType) { cleanSubTypes(dataType.getUUID()); final Optional<Element> dataTypeRow = Optional.ofNullable(getDataTypeRow(dataType)); <START> dataTypeRow.ifPresent(Element::remove); <END> }</code><technical_language>this IE11 issues</technical_language>

Target:
public void removeItem(final DataType dataType) { cleanSubTypes(dataType.getUUID()); final Optional<Element> dataTypeRow = Optional.ofNullable(getDataTypeRow(dataType)); dataTypeRow.ifPresent(ElementHelper::remove); }
Source:
<code>public void resize (int width, int height) { boolean resize = currentScreenFBO.getHeight() != height || currentScreenFBO.getWidth() != width || nextScreenFBO.getHeight() != height || nextScreenFBO.getWidth() != width; <START> if (false) { <END> currentScreenFBO.dispose(); nextScreenFBO.dispose(); currentScreenFBO = new FrameBuffer(Pixmap.Format.RGBA8888, width, height, false); nextScreenFBO = new FrameBuffer(Pixmap.Format.RGBA8888, width, height, false); } if (screen != null) screen.resize(width, height); if (nextScreen != null) nextScreen.resize(width, height); }</code><technical_language>intentional if (false), I assume</technical_language>

Target:
public void resize (int width, int height) { if (screen != null) screen.resize(width, height); if (nextScreen != null) nextScreen.resize(width, height); }
Source:
<code>private void updateMetricData(Connection connection) throws SQLException { Statement statement = connection.createStatement(); statement.execute("select * from pg_stat_database where datname='connector';"); ResultSet resultSet = statement.getResultSet(); resultSet.next(); for (String key: integerDatabaseStatsMap.keySet() ) { integerDatabaseStatsMap.put(key, resultSet.getInt(key)); } for (String key: doubleDatabaseStatsMap.keySet() ) { doubleDatabaseStatsMap.put(key, resultSet.getDouble(key)); } <START> resultSet.close(); <END> statement.close(); }</code><technical_language>check managed resources explicitly closing in case of exception etc</technical_language>

Target:
private void updateMetricData(Connection connection) { try (Statement statement = connection.createStatement()) { statement.execute("select * from pg_stat_database where datname='connector';"); try (ResultSet resultSet = statement.getResultSet()) { resultSet.next(); for (String key : longDatabaseStatsMap.keySet()) { longDatabaseStatsMap.put(key, resultSet.getLong(key)); } for (String key : doubleDatabaseStatsMap.keySet()) { doubleDatabaseStatsMap.put(key, resultSet.getDouble(key)); } } statsHealthy = 1; } catch (SQLException e) { statsHealthy = 0; } }
Source:
<code>public void requestPersistence() { persistenceRequested = true; if (timer == null) { <START> timer = UserThread.runPeriodically(() -> { <END> persistNow(null); UserThread.execute(() -> timer = null); }, source.delayInSec, TimeUnit.SECONDS); } }</code><technical_language>runPeriodically() instead of runAfter()? effect write is intended happen periodically, lines not</technical_language>

Target:
public void requestPersistence() { persistenceRequested = true; if (timer == null) { timer = UserThread.runAfter(() -> { persistNow(null); UserThread.execute(() -> timer = null); }, source.delayInSec, TimeUnit.SECONDS); } }
Source:
<code>private void initNearCache() { NearCacheConfig nearCacheConfig = getContext().getClientConfig().getNearCacheConfig(name); if (nearCacheConfig != null) { NearCacheConfig copyNearCacheConfig = new NearCacheConfig(nearCacheConfig); <START> copyNearCacheConfig.setSerializeKeys(false); <END> nearCache = getContext().getNearCacheManager(getServiceName()).getOrCreateNearCache(name, copyNearCacheConfig); if (nearCacheConfig.isInvalidateOnChange()) { registerInvalidationListener(); } } }</code><technical_language>fail fast instead of forcing false</technical_language>

Target:
private void initNearCache() { NearCacheConfig nearCacheConfig = getContext().getClientConfig().getNearCacheConfig(name); if (nearCacheConfig != null) { if (nearCacheConfig.isSerializeKeys()) { throw new InvalidConfigurationException("ReplicatedMap doesn't support serializeKeys option of NearCacheConfig"); } nearCache = getContext().getNearCacheManager(getServiceName()).getOrCreateNearCache(name, nearCacheConfig); if (nearCacheConfig.isInvalidateOnChange()) { registerInvalidationListener(); } } }
Source:
<code>public ProtocolRead(String p_message) { m_message = p_message; <START> logger.debug("Instance created for message [" + p_message + "]"); <END> }</code><technical_language>parameterized logging instead of string concatenation</technical_language>

Target:
public ProtocolRead(String p_message) { m_message = p_message; logger.debug("Instance created for message [{}]", p_message); }
Source:
<code><START> protected void putForExternalReadInternal(K key, V value, Metadata metadata, ByRef.Boolean isCreatedRef) { <END> boolean hasListeners = this.hasListeners; getDataContainer().compute(key, (k, oldEntry, factory) -> { if (isNull(oldEntry)) { if (hasListeners) { cacheNotifier.notifyCacheEntryCreated(k, value, metadata, true, ImmutableContext.INSTANCE, null); } isCreatedRef.set(true); return factory.create(k, value, metadata); } else { return oldEntry; } }); if (hasListeners && isCreatedRef.get()) { cacheNotifier.notifyCacheEntryCreated(key, value, metadata, false, ImmutableContext.INSTANCE, null); } }</code><technical_language>I putForExternalReadInternal methods merged, of name changed</technical_language>

Target:
protected void putForExternalReadInternal(K key, V value, Metadata metadata, ByRef.Boolean isCreatedRef) { Objects.requireNonNull(key, NULL_KEYS_NOT_SUPPORTED); Objects.requireNonNull(value, NULL_VALUES_NOT_SUPPORTED); boolean hasListeners = this.hasListeners; getDataContainer().compute(key, (k, oldEntry, factory) -> { if (isNull(oldEntry)) { if (hasListeners) { cacheNotifier.notifyCacheEntryCreated(k, value, metadata, true, ImmutableContext.INSTANCE, null); } isCreatedRef.set(true); return factory.create(k, value, metadata); } else { return oldEntry; } }); if (hasListeners && isCreatedRef.get()) { cacheNotifier.notifyCacheEntryCreated(key, value, metadata, false, ImmutableContext.INSTANCE, null); } }
Source:
<code>private void handleEvent(final String type, final String payload, final String topic, final @Nullable String source) { final EventFactory eventFactory = typedEventFactories.get(type); if (eventFactory == null) { <START> logger.warn("Could not find an Event Factory for the event type '{}'.", type); <END> return; } final Set<EventSubscriber> eventSubscribers = getEventSubscribers(type); if (eventSubscribers.isEmpty()) { return; } final Event eshEvent = createESHEvent(eventFactory, type, payload, topic, source); if (eshEvent == null) { return; } dispatchESHEvent(eventSubscribers, eshEvent); }</code><technical_language>reduce this debug (as in current master)</technical_language>

Target:
private void handleEvent(final String type, final String payload, final String topic, final @Nullable String source) { final EventFactory eventFactory = typedEventFactories.get(type); if (eventFactory == null) { logger.debug("Could not find an Event Factory for the event type '{}'.", type); return; } final Set<EventSubscriber> eventSubscribers = getEventSubscribers(type); if (eventSubscribers.isEmpty()) { return; } final Event eshEvent = createESHEvent(eventFactory, type, payload, topic, source); if (eshEvent == null) { return; } dispatchESHEvent(eventSubscribers, eshEvent); }
Source:
<code>private String getLocaleInformation() { ObjectNode node = mapper.createObjectNode(); String displayedLocales = " "; for (String localeString: UnsupportedLocaleHelper.getLocalesKeys(backend, ConfigurationValues.UnsupportedDisplayedLocales)) { displayedLocales += localeString + ","; } node.put(ConfigurationValues.UnsupportedDisplayedLocales.name(), displayedLocales.substring(0, displayedLocales.length() - 1)); String unSupportedLocales = " "; for (String localeString: UnsupportedLocaleHelper.getLocalesKeys(backend, ConfigurationValues.UnsupportedLocalesFilter)) { unSupportedLocales += localeString + ","; } node.put(ConfigurationValues.UnsupportedLocalesFilter.name(), unSupportedLocales.substring(0, unSupportedLocales.length() - 1)); return node.toString(); <START> } <END></code><technical_language>I glad talked this... a do this manually modify explicit fields time. for this patch of course.</technical_language>

Target:
private String getLocaleInformation() { ObjectNode node = mapper.createObjectNode(); StringBuilder localeBuilder = new StringBuilder(); localeBuilder.append(' '); for (String localeString: UnsupportedLocaleHelper.getLocalesKeys(backend, ConfigurationValues.UnsupportedDisplayedLocales)) { localeBuilder.append(localeString); localeBuilder.append(','); } String displayedLocales = localeBuilder.toString(); node.put(ConfigurationValues.UnsupportedDisplayedLocales.name(), displayedLocales.substring(0, displayedLocales.length() - 1)); localeBuilder = new StringBuilder(); localeBuilder.append(' '); for (String localeString: UnsupportedLocaleHelper.getLocalesKeys(backend, ConfigurationValues.UnsupportedLocalesFilter)) { localeBuilder.append(localeString); localeBuilder.append(','); } String unSupportedLocales = localeBuilder.toString(); node.put(ConfigurationValues.UnsupportedLocalesFilter.name(), unSupportedLocales.substring(0, unSupportedLocales.length() - 1)); return node.toString(); }
Source:
<code>void close() { if (isOpen.compareAndSet(true, false)) { synchronized (chunkFillerSynchronizer) { if (isChunkFillerThreadAsleep) { <START> chunkFillerThreadSleepDisabled = true; <END> chunkFillerSynchronizer.notify(); } } try { chunkFillerThread.join(NonBlockingRouter.SHUTDOWN_WAIT_MS); } catch (InterruptedException e) { logger.error("Caught interrupted exception while waiting for chunkFillerThread to finish"); Thread.currentThread().interrupt(); } completePendingOperations(); } }</code><technical_language>need this new variable. checking isOpen enough ? (both variables carry piece of information)</technical_language>

Target:
void close() { if (isOpen.compareAndSet(true, false)) { synchronized (chunkFillerSynchronizer) { if (isChunkFillerThreadAsleep) { chunkFillerThreadMaySleep = false; chunkFillerSynchronizer.notify(); } } try { chunkFillerThread.join(NonBlockingRouter.SHUTDOWN_WAIT_MS); } catch (InterruptedException e) { logger.error("Caught interrupted exception while waiting for chunkFillerThread to finish"); Thread.currentThread().interrupt(); } completePendingOperations(); } }
Source:
<code>public String getConfigLoaderFactory() { <START> return get(CONFIG_LOADER_FACTORY); <END> }</code><technical_language>Is this optional config, is required? If is optional, please return Optional<String>, add a default value? If required, please throw a ConfigException</technical_language>

Target:
public Optional<String> getConfigLoaderFactory() { return Optional.ofNullable(get(CONFIG_LOADER_FACTORY)); }
Source:
<code>public synchronized static SSLContext buildContext(String algorithm, String keypath, String keypass, String keytype, String trustpath, String trustpass, String trusttype) { try { KeyManager[] kms = buildKeyManagers(keypath, keypass, keytype); TrustManager[] tms = buildTrustManagers(trustpath, trustpass, trusttype); SSLContext context = SSLContext.getInstance(algorithm); context.init(kms, tms, null); return context; <START> } catch (Exception e) { <END> throw new SecurityException(e.getMessage(), e); } }</code><technical_language>avoid big Exception catch detail exceptions handled this catch please</technical_language>

Target:
public synchronized static SSLContext buildContext(String algorithm, String keypath, String keypass, String keytype, String trustpath, String trustpass, String trusttype) throws UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, KeyManagementException { KeyManager[] kms = buildKeyManagers(keypath, keypass, keytype); TrustManager[] tms = buildTrustManagers(trustpath, trustpass, trusttype); SSLContext context = SSLContext.getInstance(algorithm); context.init(kms, tms, null); return context; }
Source:
<code>public void setUp() throws Exception { <START> BrickTestUtils.createProjectAndGetStartScript("PhiroMoveMotorBackwardBrickTest") <END> .addBrick(new PhiroMotorMoveBackwardBrick( PhiroMotorMoveBackwardBrick.Motor.MOTOR_RIGHT, SET_SPEED_INITIALLY)); brickPosition = 1; baseActivityTestRule.launchActivity(null); }</code><technical_language>for readability please initialize brick separately</technical_language>

Target:
public void setUp() { int setSpeed = -70; BrickTestUtils.createProjectAndGetStartScript("PhiroMoveMotorBackwardBrickTest") .addBrick(new PhiroMotorMoveBackwardBrick( PhiroMotorMoveBackwardBrick.Motor.MOTOR_RIGHT, setSpeed)); brickPosition = 1; baseActivityTestRule.launchActivity(null); }
Source:
<code>public Map<String, Object> getConfigSetting(String interpreterGroupId) { InterpreterSetting interpreterSetting = get(interpreterGroupId); if (null != interpreterSetting) { List<InterpreterInfo> interpreterInfos = interpreterSetting.getInterpreterInfos(); for (InterpreterInfo intpInfo : interpreterInfos) { if (intpInfo.isDefaultInterpreter() || (interpreterInfos.size() == 1)) { <START> if (intpInfo.getConfig() != null) { <END> return intpInfo.getConfig(); } } } } return new HashMap<String, Object>(); }</code><technical_language>merge L502 501</technical_language>

Target:
public Map<String, Object> getConfigSetting(String interpreterGroupId) { InterpreterSetting interpreterSetting = get(interpreterGroupId); if (null != interpreterSetting) { List<InterpreterInfo> interpreterInfos = interpreterSetting.getInterpreterInfos(); int infoSize = interpreterInfos.size(); for (InterpreterInfo intpInfo : interpreterInfos) { if ((intpInfo.isDefaultInterpreter() || (infoSize == 1)) && (intpInfo.getConfig() != null)) { return intpInfo.getConfig(); } } } return new HashMap<>(); }
Source:
<code>public void applyConfigChanges(int newDynamicUpdateInternal, int newDynamicSampleUpdateInterval, double newDynamicBadnessThreshold) { if (DatabaseDescriptor.isDaemonInitialized()) { if (dynamicUpdateInterval != newDynamicUpdateInternal || updateScoresScheduler == null) { <START> cancelAndWait(updateScoresScheduler, Math.max(1, dynamicUpdateInterval), TimeUnit.MILLISECONDS); <END> updateScoresScheduler = ScheduledExecutors.scheduledTasks.scheduleWithFixedDelay(this::updateScores, newDynamicUpdateInternal, newDynamicUpdateInternal, TimeUnit.MILLISECONDS); } if (dynamicSampleUpdateInterval != newDynamicSampleUpdateInterval || updateSamplesScheduler == null) { cancelAndWait(updateSamplesScheduler, Math.max(1, dynamicSampleUpdateInterval), TimeUnit.MILLISECONDS); if (newDynamicSampleUpdateInterval > 0) updateSamplesScheduler = ScheduledExecutors.scheduledTasks.scheduleWithFixedDelay(this::updateSamples, newDynamicSampleUpdateInterval, newDynamicSampleUpdateInterval, TimeUnit.MILLISECONDS); } } dynamicUpdateInterval = newDynamicUpdateInternal; dynamicSampleUpdateInterval = newDynamicSampleUpdateInterval; dynamicBadnessThreshold = newDynamicBadnessThreshold; if (dynamicSampleUpdateInterval > 0) probeRateLimiter.setRate(dynamicSampleUpdateInterval); }</code><technical_language>I termination I prefer block for 365 days. need block wait for complete (or a bug) in case cancel move on. In sense me</technical_language>

Target:
public void applyConfigChanges(int newDynamicUpdateInternal, int newDynamicSampleUpdateInterval, double newDynamicBadnessThreshold) { if (DatabaseDescriptor.isDaemonInitialized()) { if (dynamicUpdateInterval != newDynamicUpdateInternal || updateScoresScheduler == null) { ensureCancelled(updateScoresScheduler); updateScoresScheduler = ScheduledExecutors.scheduledTasks.scheduleWithFixedDelay(this::updateScores, newDynamicUpdateInternal, newDynamicUpdateInternal, TimeUnit.MILLISECONDS); } if (dynamicSampleUpdateInterval != newDynamicSampleUpdateInterval || updateSamplesScheduler == null) { ensureCancelled(updateSamplesScheduler); if (newDynamicSampleUpdateInterval > 0) updateSamplesScheduler = ScheduledExecutors.scheduledTasks.scheduleWithFixedDelay(this::updateSamples, newDynamicSampleUpdateInterval, newDynamicSampleUpdateInterval, TimeUnit.MILLISECONDS); } } dynamicUpdateInterval = newDynamicUpdateInternal; dynamicUpdateInterval = newDynamicUpdateInternal; dynamicSampleUpdateInterval = newDynamicSampleUpdateInterval; dynamicBadnessThreshold = newDynamicBadnessThreshold; if (dynamicSampleUpdateInterval > 0) setProbeRateLimiter(dynamicSampleUpdateInterval); }
Source:
<code>public BooleanParameter markRequired() { throw new UnsupportedOperationException( <START> "A boolean parameter must not be marked as required as it is inherently so. Use markNullable() to make the parameter optional"); <END> }</code><technical_language>suggestion "A boolean parameter marked required is inherently so. markNullable() parameter optional.");</technical_language>

Target:
public BooleanParameter markRequired() { throw new UnsupportedOperationException( "A boolean parameter must not be marked as required as it is inherently so. Use markNullable() to make the parameter optional."); }
Source:
<code>@Override public final boolean writeLog(FilePath workspace, OutputStream sink) throws IOException, InterruptedException { if (writeLogCs == null) { if (SYSTEM_DEFAULT_CHARSET.equals(charset)) { String cs = workspace.act(new TranscodingCharsetForSystemDefault()); writeLogCs = new AtomicReference<>(cs == null ? null : Charset.forName(cs)); } else { writeLogCs = new AtomicReference<>(transcodingCharset(charset)); } LOGGER.log(Level.FINE, "remote transcoding charset: {0}", writeLogCs); } FilePath log = getLogFile(workspace); OutputStream transcodedSink; if (writeLogCs.get() == null) { transcodedSink = sink; } else { CharsetDecoder decoder = writeLogCs.get().newDecoder().onMalformedInput(CodingErrorAction.REPLACE).onUnmappableCharacter(CodingErrorAction.REPLACE); transcodedSink = new WriterOutputStream(new OutputStreamWriter(sink, StandardCharsets.UTF_8), decoder, 1024, true); } CountingOutputStream cos = new CountingOutputStream(transcodedSink); try { log.act(new WriteLog(lastLocation, new RemoteOutputStream(cos))); <START> sink.flush(); <END> return cos.getByteCount() > 0; } finally { transcodedSink.flush(); long written = cos.getByteCount(); if (written > 0) { LOGGER.log(Level.FINE, "copied {0} bytes from {1}", new Object[] {written, log}); lastLocation += written; } } }</code><technical_language>this do z/OS support</technical_language>

Target:
@Override public final boolean writeLog(FilePath workspace, OutputStream sink) throws IOException, InterruptedException { if (writeLogCs == null) { if (SYSTEM_DEFAULT_CHARSET.equals(charset)) { String cs = workspace.act(new TranscodingCharsetForSystemDefault()); writeLogCs = new AtomicReference<>(cs == null ? null : Charset.forName(cs)); } else { writeLogCs = new AtomicReference<>(transcodingCharset(charset)); } LOGGER.log(Level.FINE, "remote transcoding charset: {0}", writeLogCs); } FilePath log = getLogFile(workspace); OutputStream transcodedSink; if (writeLogCs.get() == null) { transcodedSink = sink; } else { CharsetDecoder decoder = writeLogCs.get().newDecoder().onMalformedInput(CodingErrorAction.REPLACE).onUnmappableCharacter(CodingErrorAction.REPLACE); transcodedSink = new WriterOutputStream(new OutputStreamWriter(sink, StandardCharsets.UTF_8), decoder, 1024, true); } CountingOutputStream cos = new CountingOutputStream(transcodedSink); try { log.act(new WriteLog(lastLocation, new RemoteOutputStream(cos))); return cos.getByteCount() > 0; } finally { transcodedSink.flush(); long written = cos.getByteCount(); if (written > 0) { LOGGER.log(Level.FINE, "copied {0} bytes from {1}", new Object[] {written, log}); lastLocation += written; } } }
Source:
<code>@Override public void msync(long address, long byteCount, int flags) throws ErrnoException { <START> BlockGuard.getThreadPolicy().onWriteToDisk(); <END> os.msync(address, byteCount, flags); }</code><technical_language>this merits onWriteToDisk MS_SYNC flag is set. other checks added here, this is a bit of a gray area mapping a file writeable imply some sort of (possibly asynchronous) file writes</technical_language>

Target:
@Override public void msync(long address, long byteCount, int flags) throws ErrnoException { if ((flags & OsConstants.MS_SYNC) != 0) { BlockGuard.getThreadPolicy().onWriteToDisk(); } os.msync(address, byteCount, flags); }
Source:
<code>private void resetMerge() throws IOException { try { repo.writeMergeHeads(null); repo.writeMergeCommitMsg(null); <START> } catch (IOException e) { <END> throw e; } }</code><technical_language>unused try catch block</technical_language>

Target:
private void resetMerge() throws IOException { repo.writeMergeHeads(null); repo.writeMergeCommitMsg(null); }
Source:
<code>public StatisticsResource getStatisticsResource() { EntityIdResolver<Guid> resolver = new EntityIdResolver<Guid>() { @Override <START> public VmNetworkInterface lookupEntity(Guid id) <END> throws BackendFailureException { return collection.lookupEntity(guid); } }; NicStatisticalQuery query = new NicStatisticalQuery(resolver, newModel(id)); return inject(new BackendStatisticsResource<NIC, VmNetworkInterface>(entityType, guid, query)); }</code><technical_language>renamed guid arg in id, places is used? - i suggest revert this change</technical_language>

Target:
public StatisticsResource getStatisticsResource() { EntityIdResolver<Guid> resolver = new EntityIdResolver<Guid>() { @Override public VmNetworkInterface lookupEntity(Guid guid) throws BackendFailureException { return collection.lookupEntity(guid); } }; NicStatisticalQuery query = new NicStatisticalQuery(resolver, newModel(id)); return inject(new BackendStatisticsResource<NIC, VmNetworkInterface>(entityType, guid, query)); }
Source:
<code>private Observable<Integer> doFullTextSearchResultsCountObservable(final String searchTerm) { return Observable.fromIterable(WikipediaApp.getInstance().language().getAppLanguageCodes()) <START> .concatMap(langCode -> ServiceFactory.get(WikiSite.forLanguageCode(langCode)).fullTextSearch(searchTerm, LARGE_BATCH_SIZE, null, null)) <END> .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .map(response -> response.query() != null ? response.query().pages().size() : 0); }</code><technical_language>clever</technical_language>

Target:
private Observable<Integer> doFullTextSearchResultsCountObservable(final String searchTerm) { return Observable.fromIterable(WikipediaApp.getInstance().language().getAppLanguageCodes()) .concatMap(langCode -> ServiceFactory.get(WikiSite.forLanguageCode(langCode)).fullTextSearch(searchTerm, BATCH_SIZE, null, null)) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .map(response -> response.query() != null ? response.query().pages().size() : 0); }
Source:
<code><START> private SecurityDomain(Builder builder) { <END> this.realmMap = unmodifiableMap(builder.realms); this.defaultRealmName = builder.defaultRealmName; this.preRealmRewriter = builder.preRealmRewriter; this.realmMapper = builder.realmMapper; this.postRealmRewriter = builder.postRealmRewriter; anonymousAllowed = false; }</code><technical_language>This package-private is called nested class. a constructor is private is accessed a nested class, javac generates invisible package-private constructor anyway. Generally I private methods fields. else is public, protected, package-private</technical_language>

Target:
SecurityDomain(Builder builder) { this.realmMap = unmodifiableMap(builder.realms); this.defaultRealmName = builder.defaultRealmName; this.preRealmRewriter = builder.preRealmRewriter; this.realmMapper = builder.realmMapper; this.roleMapper = builder.roleMapper; this.postRealmRewriter = builder.postRealmRewriter; anonymousAllowed = false; }
Source:
<code>private boolean isRSA(ArrayInitializerTree config) { return config.arrayPairs().stream() .filter(pair -> { <START> if (!"private_key_type".equals(trimQuotes((LiteralTree) pair.key()))) { <END> return false; } if (pair.value().is(Kind.NAMESPACE_NAME)) { NamespaceNameTree value = (NamespaceNameTree) pair.value(); return "OPENSSL_KEYTYPE_RSA".equals(value.name().text()); } return false; }) .count() > 0; }</code><technical_language>This throws a ClassCastException pair.key() is a literal. a test for that. Moreover, pair.key() return null</technical_language>

Target:
private static boolean isRSA(ArrayInitializerTree config) { return config.arrayPairs().stream().anyMatch(pair -> { if (!hasKey(pair, "private_key_type")) { return false; } if (pair.value().is(Kind.NAMESPACE_NAME)) { NamespaceNameTree value = (NamespaceNameTree) pair.value(); return "OPENSSL_KEYTYPE_RSA".equals(value.name().text()); } return false; }); }
Source:
<code>public Type getType(String id) { Type type = types.get(id); if (type == null) { return null; <START> } else { <END> Map<String, SubType> allowedSubTypes = getCoreAllowedSubtypes(type); Type newType = type.clone(); newType.setAllowedSubTypes(allowedSubTypes); newType.setDeniedSubTypes(new String[0]); return newType; } }</code><technical_language>This is early exit, move else part unindented below</technical_language>

Target:
public Type getType(String id) { return types.get(id); }
Source:
<code>public void testFinishLocalSetupFullyInitialized() throws Exception { final Checker checker = new Checker(); final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); checker.setModuleClassLoader(contextClassLoader); final PackageObjectFactory factory = new PackageObjectFactory( new HashSet<>(), contextClassLoader); checker.setModuleFactory(factory); checker.setBasedir("testBaseDir"); checker.setLocaleLanguage("it"); checker.setLocaleCountry("IT"); checker.finishLocalSetup(); final Context context = Whitebox.getInternalState(checker, "childContext"); assertEquals("error", context.get("severity"), "Severity is set to unexpected value"); <START> assertEquals("testBaseDir", context.get("basedir"), "Basedir is set to unexpected value"); <END> final Field sLocale = LocalizedMessage.class.getDeclaredField("sLocale"); sLocale.setAccessible(true); final Locale locale = (Locale) sLocale.get(null); assertEquals(Locale.ITALY, locale, "Locale is set to unexpected value"); }</code><technical_language>need charset verification, this is pitest is complaining</technical_language>

Target:
public void testFinishLocalSetupFullyInitialized() throws Exception { final Checker checker = new Checker(); final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); checker.setModuleClassLoader(contextClassLoader); final PackageObjectFactory factory = new PackageObjectFactory( new HashSet<>(), contextClassLoader); checker.setModuleFactory(factory); checker.setBasedir("testBaseDir"); checker.setLocaleLanguage("it"); checker.setLocaleCountry("IT"); checker.finishLocalSetup(); final Context context = Whitebox.getInternalState(checker, "childContext"); final String encoding = StandardCharsets.UTF_8.name(); assertEquals(encoding, context.get("charset"), "Charset was different than expected"); assertEquals("error", context.get("severity"), "Severity is set to unexpected value"); assertEquals("testBaseDir", context.get("basedir"), "Basedir is set to unexpected value"); final Field sLocale = LocalizedMessage.class.getDeclaredField("sLocale"); sLocale.setAccessible(true); final Locale locale = (Locale) sLocale.get(null); assertEquals(Locale.ITALY, locale, "Locale is set to unexpected value"); }