auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>final void setPluginConfigValues(Map<String, Map<String, String>> pluginConfigValues) { NativeMap<StringMap> configValues = NativeMap.create().cast(); for (Entry<String, Map<String, String>> e : pluginConfigValues.entrySet()) { StringMap values = StringMap.create(); configValues.put(e.getKey(), values); for (Entry<String, String> e2 : e.getValue().entrySet()) { values.put(e2.getKey(), e2.getValue()); } } <START> setPluginConfigValuesRaw(configValues); <END> }</code><technical_language>set map if non-empty</technical_language>

Target:
final void setPluginConfigValues(Map<String, Map<String, String>> pluginConfigValues) { if (!pluginConfigValues.isEmpty()) { NativeMap<StringMap> configValues = NativeMap.create().cast(); for (Entry<String, Map<String, String>> e : pluginConfigValues.entrySet()) { StringMap values = StringMap.create(); configValues.put(e.getKey(), values); for (Entry<String, String> e2 : e.getValue().entrySet()) { values.put(e2.getKey(), e2.getValue()); } } setPluginConfigValuesRaw(configValues); } }
Source:
<code>public void before() { postProcessorRegistry = new PostProcessorDescriptorRegistryImpl<String>(); postProcessorRegistry.put(CompareDiagramPostProcessor.class.getName(), new TestPostProcessor.TestPostProcessorDescriptor( <START> Pattern.compile("<LINK_0>\\d.\\d.\\d/notation"), null, new CompareDiagramPostProcessor(), 10)); <END> emfCompare = EMFCompare.builder().setPostProcessorRegistry(postProcessorRegistry).build(); }</code><technical_language>This a ranking of 30 in plugin.xml, in tests</technical_language>

Target:
public void before() { postProcessorRegistry = new PostProcessorDescriptorRegistryImpl<String>(); postProcessorRegistry.put(CompareDiagramPostProcessor.class.getName(), new TestPostProcessor.TestPostProcessorDescriptor( Pattern.compile("<LINK_0>\\d.\\d.\\d/notation"), null, new CompareDiagramPostProcessor(), 30)); emfCompare = EMFCompare.builder().setPostProcessorRegistry(postProcessorRegistry).build(); }
Source:
<code>private static String formatMessage(String msg, Object... args) { try { return String.format(msg, (Object[]) args); } <START> catch (IllegalFormatException | FormatterClosedException ignore) { } <END> return msg; }</code><technical_language>Locale.ENGLISH setup, exceptions handled. is this intentional</technical_language>

Target:
private static String formatMessage(String msg, Object... args) { try { return String.format(Locale.ENGLISH, msg, (Object[]) args); } catch (IllegalFormatException | FormatterClosedException ignore) { } return msg; }
Source:
<code>public void validateInputTask(PluginTask task) { task.setIncrementalColumn(Optional.of(INCREMENTAL_COLUMN)); task.setUidColumn(Optional.of(UID_COLUMN)); if (!task.getActivityTypeIds().isEmpty()) { List<String> invalidIds = new ArrayList<>(); for (String id : task.getActivityTypeIds()) { if (StringUtils.isBlank(id) || !StringUtils.isNumeric(StringUtils.trimToEmpty(id))) { invalidIds.add(id); } } if (!invalidIds.isEmpty()) { throw new ConfigException(MessageFormat.format("Invalid activity type id: [{0}]", StringUtils.join(invalidIds, ", "))); } try (MarketoRestClient restClient = createMarketoRestClient(task)) { MarketoService marketoService = new MarketoServiceImpl(restClient); Iterable<ObjectNode> nodes = marketoService.getActivityTypes(); if (nodes != null) { checkValidActivityTypeIds(nodes, task.getActivityTypeIds()); } <START> else { <END> } } } super.validateInputTask(task); }</code><technical_language>if do in else clause remove</technical_language>

Target:
public void validateInputTask(PluginTask task) { task.setIncrementalColumn(Optional.of(INCREMENTAL_COLUMN)); task.setUidColumn(Optional.of(UID_COLUMN)); if (!task.getActivityTypeIds().isEmpty()) { List<Integer> activityIds = checkValidActivityTypeIds(task); try (MarketoRestClient restClient = createMarketoRestClient(task)) { MarketoService marketoService = new MarketoServiceImpl(restClient); Iterable<ObjectNode> nodes = marketoService.getActivityTypes(); if (nodes != null) { checkValidActivityTypeIds(nodes, activityIds); } } task.setActTypeIds(activityIds); } else { task.setActTypeIds(new ArrayList<Integer>()); } super.validateInputTask(task); }
Source:
<code>public void testToJsonWithLengthLimitNonAscii() { JsonCodec<ImmutablePerson> jsonCodec = jsonCodec(ImmutablePerson.class); <START> ImmutablePerson person = new ImmutablePerson(Strings.repeat("\u0158\u015a", 500), false); <END> assertFalse(jsonCodec.toJsonWithLengthLimit(person, 0).isPresent()); assertFalse(jsonCodec.toJsonWithLengthLimit(person, 1000).isPresent()); assertFalse(jsonCodec.toJsonWithLengthLimit(person, 1035).isPresent()); assertTrue(jsonCodec.toJsonWithLengthLimit(person, 1036).isPresent()); }</code><technical_language>ImmutablePerson person = new ImmutablePerson(Strings.repeat("\u0158", 1000), false);</technical_language>

Target:
public void testToJsonWithLengthLimitNonAscii() { JsonCodec<ImmutablePerson> jsonCodec = jsonCodec(ImmutablePerson.class); ImmutablePerson person = new ImmutablePerson(Strings.repeat("\u0158", 1000), false); assertFalse(jsonCodec.toJsonWithLengthLimit(person, 0).isPresent()); assertFalse(jsonCodec.toJsonWithLengthLimit(person, 1000).isPresent()); assertFalse(jsonCodec.toJsonWithLengthLimit(person, 1035).isPresent()); assertTrue(jsonCodec.toJsonWithLengthLimit(person, 1036).isPresent()); }
Source:
<code>public String toString() { <START> return "BinlogPosition[" + file + ":" + offset + ":" + gtidStr + "]"; <END> }</code><technical_language>append if gtidStr is null</technical_language>

Target:
public String toString() { return "BinlogPosition[" + (gtidSetStr == null ? file + ":" + offset : gtidSetStr) + "]"; }
Source:
<code>public void failNonTxnEnqueue() { CorfuQueue<String> corfuQueue = new CorfuQueue<>(getDefaultRuntime(), "test"); <START> Assertions.assertThatThrownBy(() -> corfuQueue.enqueue("c")) <END> .isInstanceOf(IllegalStateException.class) .hasMessage("must be called within a transaction!"); }</code><technical_language>a question: ok IllegalStateException? a more specific exception</technical_language>

Target:
public void failNonTxnEnqueue() { CorfuQueue<String> corfuQueue = new CorfuQueue<>(getDefaultRuntime(), "test"); assertThatThrownBy(() -> corfuQueue.enqueue("c")) .isInstanceOf(IllegalStateException.class) .hasMessage("must be called within a transaction!"); }
Source:
<code>public void store(String key, Object value) { File dir = new File(getMapStorePath()); if (new File(getPersistencePath()).canWrite()) { boolean created = dir.mkdirs(); if (created || dir.exists()) { LOGGER.trace("Entering: store - key: {}", key); try (OutputStream file = new FileOutputStream(getMapStorePath() + key + PERSISTED_FILE_SUFFIX); OutputStream buffer = new BufferedOutputStream(file); ObjectOutputStream output = new ObjectOutputStream(buffer)) { output.writeObject(value); } catch (IOException e) { <START> LOGGER.debug("IOException storing value in cache with key = " + key, e); <END> } } else { LOGGER.debug("Unable to create directory: {}", dir.getAbsolutePath()); } } }</code><technical_language>Failing write file system is pretty bad admin do consider logging higher debug L113</technical_language>

Target:
public void store(String key, Object value) { File dir = new File(getMapStorePath()); if (new File(getPersistencePath()).canWrite()) { boolean created = dir.mkdirs(); if (created || dir.exists()) { LOGGER.trace("Entering: store - key: {}", key); try (OutputStream file = new FileOutputStream(getPersistedFilePathForKey(key)); OutputStream buffer = new BufferedOutputStream(file); ObjectOutputStream output = new ObjectOutputStream(buffer)) { output.writeObject(value); } catch (IOException e) { LOGGER.debug("IOException storing value in cache with key = {}", key, e); LOGGER.warn( "Error storing value in cache with key [{}]. Turn logging to debug for more info.", key); } } else { LOGGER.debug("Unable to create directory: {}", dir.getAbsolutePath()); } } }
Source:
<code>public void closeThisNode(long endtime) { fRwl.writeLock().lock(); try { if (!fIntervals.isEmpty()) { if (endtime < fIntervals.get(fIntervals.size() - 1).getEndTime()) { <START> throw new IllegalArgumentException("Closing end time should be greater than the end time of the intervals of this node"); END> } } fNodeEnd = endtime; } finally { fRwl.writeLock().unlock(); } }</code><technical_language>s/greater than/greater equal In case node is closed reached maximum number of intervals, end time *equal* fIntervals.get(last). In other cases (closed reached max children, in branch close tree) greater too. (btw Iterables.getLast(fIntervals) now, is a bit more readable!)</technical_language>

Target:
public void closeThisNode(long endtime) { fRwl.writeLock().lock(); try { if (!fIntervals.isEmpty()) { if (endtime < Iterables.getLast(fIntervals).getEndTime()) { throw new IllegalArgumentException("Closing end time should be greater than or equal to the end time of the intervals of this node"); } } fNodeEnd = endtime; } finally { fRwl.writeLock().unlock(); } }
Source:
<code>public QueryBuilder make(EsHint hint, String fieldName, Object value) { MatchQueryBuilder matchQuery = QueryBuilders.matchQuery(fieldName, value); if (hint.analyzer != null) { <START> matchQuery.analyzer(hint.analyzer); <END> } return matchQuery; }</code><technical_language>need for null check</technical_language>

Target:
public QueryBuilder make(EsHint hint, String fieldName, Object value) { return QueryBuilders.matchQuery(fieldName, value).analyzer(hint.analyzer); }
Source:
<code><START> private void migratePartialDownloads(SqlDatabaseWrapper database, PartialDownloadMigrationExtractor partialDownloadMigrationExtractor, DownloadsPersistence downloadsPersistence) { <END> List<Migration> partialMigrations = partialDownloadMigrationExtractor.extractMigrations(); for (int i = 0; i < partialMigrations.size(); i++) { downloadsPersistence.startTransaction(); database.startTransaction(); Migration migration = partialMigrations.get(i); migrateV1DataToV2Database(downloadsPersistence, migration); deleteFrom(database, migration); downloadsPersistence.transactionSuccess(); downloadsPersistence.endTransaction(); database.setTransactionSuccessful(); database.endTransaction(); } }</code><technical_language>try write tests for first, pain points guide a more testable solution</technical_language>

Target:
private void migratePartialDownloads(SqlDatabaseWrapper database, PartialDownloadMigrationExtractor partialDownloadMigrationExtractor, DownloadsPersistence downloadsPersistence) { List<Migration> partialMigrations = partialDownloadMigrationExtractor.extractMigrations(); for (Migration partialMigration : partialMigrations) { downloadsPersistence.startTransaction(); database.startTransaction(); migrateV1DataToV2Database(downloadsPersistence, partialMigration); deleteFrom(database, partialMigration); downloadsPersistence.transactionSuccess(); downloadsPersistence.endTransaction(); database.setTransactionSuccessful(); database.endTransaction(); } Log.d(TAG, "partial migrations are all EXTRACTED, time is " + System.nanoTime()); }
Source:
<code>private static String toPathString(String moduleName) { <START> return moduleName.replace('.', '/') + '/' + moduleName + '/'; <END> }</code><technical_language>Method body be: return moduleName.replace('.', '/'); slash, this path is in combination "/module.xml" string</technical_language>

Target:
private static String toPathString(String moduleName) { return moduleName.replace('.', '/') + '/' + moduleName; }
Source:
<code>public int hashCode() { HashCodeBuilder hcBuilder = new HashCodeBuilder(); hcBuilder.append(releaseVer); return hcBuilder.toHashCode(); <START> } <END></code><technical_language>Nice, unnecessary -- HashCodeBuilder in this case is original code replaced (especially builder a prime value). leave this as-is for now</technical_language>

Target:
public int hashCode() { return this.releaseVer != null ? this.releaseVer.hashCode() : 0; }
Source:
<code>public void connect() throws IOException { if (connected) return; try (final InputStream in = getJarFileURL().openConnection().getInputStream()) { <START> jarFile = AccessController.doPrivileged( <END> new PrivilegedExceptionAction<JarFile>() { public JarFile run() throws IOException { Path tmpFile = Files.createTempFile("jar_cache", null); try { Files.copy(in, tmpFile, StandardCopyOption.REPLACE_EXISTING); JarFile jarFile = new JarFile(tmpFile.toFile(), true, JarFile.OPEN_READ); tmpFile.toFile().deleteOnExit(); return jarFile; } catch (Throwable thr) { try { Files.delete(tmpFile); } catch (IOException ioe) { thr.addSuppressed(ioe); } throw thr; } finally { in.close(); } } }); connected = true; } catch (PrivilegedActionException pae) { throw (IOException) pae.getException(); } }</code><technical_language>add if (!getJarFileURL().openConnection() instanceof JarURLConnection) avoid copiing of file if necessary</technical_language>

Target:
public void connect() throws IOException { if (connected) { return; } try (final InputStream in = getJarFileURL().openConnection().getInputStream()) { jarFile = AccessController.doPrivileged( new PrivilegedExceptionAction<JarFile>() { public JarFile run() throws IOException { Path tmpFile = Files.createTempFile("jar_cache", null); try { Files.copy(in, tmpFile, StandardCopyOption.REPLACE_EXISTING); JarFile jarFile = new JarFile(tmpFile.toFile(), true, JarFile.OPEN_READ); tmpFile.toFile().deleteOnExit(); return jarFile; } catch (Throwable thr) { try { Files.delete(tmpFile); } catch (IOException ioe) { thr.addSuppressed(ioe); } throw thr; } finally { in.close(); } } }); connected = true; } catch (PrivilegedActionException pae) { throw (IOException) pae.getException(); } }
Source:
<code>public OrganizationType getOrganization(String exchangeName, String hcid) throws ExchangeManagerException { refreshExchangeCacheIfRequired(); String hcidWithoutPrefix = HomeCommunityMap.formatHomeCommunityId(hcid); String hcidWithPrefix = HomeCommunityMap.getHomeCommunityIdWithPrefix(hcid); if (StringUtils.isEmpty(hcidWithoutPrefix) || StringUtils.isEmpty(hcidWithPrefix)) { return null; } Map<String, OrganizationType> map = null; if (StringUtils.isNotEmpty(exchangeName)) { map = exCache.get(exchangeName); } else if (StringUtils.isNotEmpty(exInfo.getDefaultExchange())) { <START> map = exCache.get(exInfo.getDefaultExchange()); <END> } else { if (null != getCache().values()) { map = extractHcidOrganizationMap(); } } if (null != map) { return map.get(hcidWithPrefix) != null ? map.get(hcidWithPrefix) : map.get(hcidWithoutPrefix); } else { return null; } }</code><technical_language>getDefaultExchange() exInfo.getDefaultExchange()</technical_language>

Target:
public OrganizationType getOrganization(String exchangeName, String hcid) throws ExchangeManagerException { refreshExchangeCacheIfRequired(); String hcidWithoutPrefix = HomeCommunityMap.formatHomeCommunityId(hcid); String hcidWithPrefix = HomeCommunityMap.getHomeCommunityIdWithPrefix(hcid); if (StringUtils.isEmpty(hcidWithoutPrefix) || StringUtils.isEmpty(hcidWithPrefix)) { return null; } Map<String, OrganizationType> map = null; if (StringUtils.isNotEmpty(exchangeName)) { map = exCache.get(exchangeName); } else if (StringUtils.isNotEmpty(getDefaultExchange())) { map = exCache.get(getDefaultExchange()); } else { if (null != getCache().values()) { map = extractHcidOrganizationMap(); } } if (null != map) { return map.get(hcidWithPrefix) != null ? map.get(hcidWithPrefix) : map.get(hcidWithoutPrefix); } else { return null; } }
Source:
<code>public void invalidate() { mActionMode.invalidate(); <START> if (mMenu != null) { mMenu.invalidate(); } <END> }</code><technical_language>brackets put invalidate line</technical_language>

Target:
public void invalidate() { mActionMode.invalidate(); if (mMenu != null) mMenu.invalidate(); }
Source:
<code>public String submitECLandGetResults(String ecl, String targetcluster, int resultLimit, int maxwait) throws Exception { String results = null; initEclDirectClient(); try { results = eclDirectClient.submitECLandGetResults(ecl, targetcluster, resultLimit, maxwait); } catch (Exception e) { <START> System.out.println("Error submiting ECL: " + e.getLocalizedMessage()); <END> throw e; } return results; }</code><technical_language>"submitting"</technical_language>

Target:
public String submitECLandGetResults(String ecl, String targetcluster, int resultLimit, int maxwait) throws Exception { String results = null; initEclDirectClient(); try { results = eclDirectClient.submitECLandGetResults(ecl, targetcluster, resultLimit, maxwait); } catch (Exception e) { Utils.println(System.err, "Error submitting ECL: " + e.getLocalizedMessage(), false, verbosemode); throw e; } return results; }
Source:
<code>public boolean supportsReloading() { <START> return supportsReloading; <END> }</code><technical_language>I a potential problem user override supportsReloading this constructor: public DefaultDriverConfigLoader(Supplier<Config> configSupplier, boolean supportsReloading) { this method final prevent overriding</technical_language>

Target:
public final boolean supportsReloading() { return supportsReloading; }
Source:
<code>private org.kie.dmn.model.api.DRGElement stunnerToDMN(final Node<?, ?> node, final Consumer<ComponentWidths> componentWidthsConsumer) { if (node.getContent() instanceof View<?>) { View<?> view = (View<?>) node.getContent(); if (view.getDefinition() instanceof InputData) { return inputDataConverter.dmnFromNode((Node<View<InputData>, ?>) node, componentWidthsConsumer); } else if (view.getDefinition() instanceof Decision) { return decisionConverter.dmnFromNode((Node<View<Decision>, ?>) node, componentWidthsConsumer); } else if (view.getDefinition() instanceof BusinessKnowledgeModel) { return bkmConverter.dmnFromNode((Node<View<BusinessKnowledgeModel>, ?>) node, componentWidthsConsumer); } else if (view.getDefinition() instanceof KnowledgeSource) { return knowledgeSourceConverter.dmnFromNode((Node<View<KnowledgeSource>, ?>) node, componentWidthsConsumer); } else if (view.getDefinition() instanceof DecisionService) { return decisionServiceConverter.dmnFromNode((Node<View<DecisionService>, ?>) node, componentWidthsConsumer); } else { <START> throw new UnsupportedOperationException("TODO"); END> } } throw new RuntimeException("wrong diagram structure to marshall"); }</code><technical_language>question TODO</technical_language>

Target:
private org.kie.dmn.model.api.DRGElement stunnerToDMN(final Node<?, ?> node, final Consumer<ComponentWidths> componentWidthsConsumer) { if (node.getContent() instanceof View<?>) { final View<?> view = (View<?>) node.getContent(); if (view.getDefinition() instanceof InputData) { return inputDataConverter.dmnFromNode((Node<View<InputData>, ?>) node, componentWidthsConsumer); } else if (view.getDefinition() instanceof Decision) { return decisionConverter.dmnFromNode((Node<View<Decision>, ?>) node, componentWidthsConsumer); } else if (view.getDefinition() instanceof BusinessKnowledgeModel) { return bkmConverter.dmnFromNode((Node<View<BusinessKnowledgeModel>, ?>) node, componentWidthsConsumer); } else if (view.getDefinition() instanceof KnowledgeSource) { return knowledgeSourceConverter.dmnFromNode((Node<View<KnowledgeSource>, ?>) node, componentWidthsConsumer); } else if (view.getDefinition() instanceof DecisionService) { return decisionServiceConverter.dmnFromNode((Node<View<DecisionService>, ?>) node, componentWidthsConsumer); } else { throw new UnsupportedOperationException("Unsupported node type detected."); } } throw new RuntimeException("wrong diagram structure to marshall"); }
Source:
<code>private Message runCommand(OMRequest request, long trxLogIndex) { OMResponse response = handler.handle(request); <START> if (response.getSuccess()) { <END> lastAppliedIndex = trxLogIndex; } return OMRatisHelper.convertResponseToMessage(response); }</code><technical_language>checked getSuccess here, considered lastAppliedIndex. cases bucket creation failed for existing bucket, success set false. transaction request is successfully completed. This considered applied right?(Even mutate om DB, transaction request completed)</technical_language>

Target:
private Message runCommand(OMRequest request, long trxLogIndex) { OMResponse response = handler.handle(request); lastAppliedIndex = trxLogIndex; return OMRatisHelper.convertResponseToMessage(response); }
Source:
<code>private void textChanged() { patternFilter.setPattern(filterText.getText()); getTableViewer().refresh(); Set<Object> checkedItems = getCheckedItems(); for (Object <START> object : <END> checkedItems) { getTableViewer().setChecked(object, true); } }</code><technical_language>rename 'checkedItem'</technical_language>

Target:
private void textChanged() { patternFilter.setPattern(filterText.getText()); getTableViewer().refresh(); for (Object checkedItem : getCheckedItems()) { getTableViewer().setChecked(checkedItem, true); } }
Source:
<code>public void test_roundtrip_tlen_preserved() throws IOException { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final ReferenceSource source = new ReferenceSource(new File(SAM_TOOLS_TEST_DIR, "cram_tlen.fasta")); final List<SAMRecord> records = new ArrayList<>(); try (SamReader reader = SamReaderFactory.make().open(new File(SAM_TOOLS_TEST_DIR, "cram_tlen_reads.sorted.sam"))) { <START> try (CRAMFileWriter writer = new CRAMFileWriter(baos, source, reader.getFileHeader(), "test.cram")) { <END> for (final SAMRecord record : reader) { writer.addAlignment(record); records.add(record); } } } try (CRAMFileReader cramReader = new CRAMFileReader(new ByteArrayInputStream(baos.toByteArray()), (File) null, source, ValidationStringency.STRICT)) { final SAMRecordIterator iterator = cramReader.getIterator(); int i = 0; while (iterator.hasNext()) { final SAMRecord record1 = iterator.next(); final SAMRecord record2 = records.get(i++); Assert.assertEquals(record1.getInferredInsertSize(), record2.getInferredInsertSize(), record1.getReadName()); Assert.assertEquals(record1, record2, record1.getReadName()); } Assert.assertEquals(records.size(), i); } }</code><technical_language>merge 1 try statement 2 resources is cleaner</technical_language>

Target:
public void test_roundtrip_tlen_preserved() throws IOException { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final ReferenceSource source = new ReferenceSource(new File(SAM_TOOLS_TEST_DIR, "cram_tlen.fasta")); final List<SAMRecord> records = new ArrayList<>(); try (SamReader reader = SamReaderFactory.make().open(new File(SAM_TOOLS_TEST_DIR, "cram_tlen_reads.sorted.sam")); CRAMFileWriter writer = new CRAMFileWriter(baos, source, reader.getFileHeader(), "test.cram")) { for (final SAMRecord record : reader) { writer.addAlignment(record); records.add(record); } } try (CRAMFileReader cramReader = new CRAMFileReader(new ByteArrayInputStream(baos.toByteArray()), (File) null, source, ValidationStringency.STRICT)) { final SAMRecordIterator iterator = cramReader.getIterator(); int i = 0; while (iterator.hasNext()) { final SAMRecord record1 = iterator.next(); final SAMRecord record2 = records.get(i++); Assert.assertEquals(record1.getInferredInsertSize(), record2.getInferredInsertSize(), record1.getReadName()); Assert.assertEquals(record1, record2, record1.getReadName()); } Assert.assertEquals(records.size(), i); } }
Source:
<code>public int compareUnsortedEncodedKeyComponents(@Nullable Double lhs, @Nullable Double rhs) { <START> return Double.compare(DimensionHandlerUtils.convertObjectToDouble(lhs), DimensionHandlerUtils.convertObjectToDouble(rhs)); <END> }</code><technical_language>IMO extract a method shorter more specific name "nullToZero()", accepts @Nullable Double, Object. for type safety simplicity, compareUnsortedEncodedKeyComponents() similar methods called often. similar Guava's nullToEmpty()</technical_language>

Target:
public int compareUnsortedEncodedKeyComponents(@Nullable Double lhs, @Nullable Double rhs) { return Double.compare(DimensionHandlerUtils.nullToZero(lhs), DimensionHandlerUtils.nullToZero(rhs)); }
Source:
<code>public synchronized void store(@NotNull String serverId, @NotNull KieServerState kieServerState) { if (!retrieveKieServerId(kieServerState).equals(serverId)) { throw new IllegalArgumentException("Invalid KieServerId: Id does not match with KieServerState."); } processKieServerStateByOpenShift(client -> { DeploymentConfig dc = client.deploymentConfigs().withName(serverId).get(); ConfigMap cm = client.configMaps().withName(serverId).get(); String stateXML = xs.toXML(kieServerState); if (Boolean.parseBoolean(kieServerState.getConfiguration() .getConfigItemValue(KieServerConstants.KIE_SERVER_STATE_IMMUTABLE, "false"))) { createNewKieServerStateCM(kieServerState, serverId, client); <START> return null; <END> } else if (isServerStateUpdateAllowed(cm, kieServerState)) { cm.setData(Collections.singletonMap(CFG_MAP_DATA_KEY, stateXML)); } else { return null; } ObjectMeta md = cm.getMetadata(); Map<String, String> ann = md.getAnnotations() == null ? new ConcurrentHashMap<>() : md.getAnnotations(); md.setAnnotations(ann); ann.put(STATE_CHANGE_TIMESTAMP, ZonedDateTime.now().format(DateTimeFormatter.ISO_INSTANT)); if (isKieServerReady()) { if (isKieServerRuntime() && !isDCStable(dc)) { logger.warn("Updating KieServerState is not supported if there are in-progress DeploymentConfig activities."); } else { ann.put(ROLLOUT_REQUIRED, "true"); client.configMaps().createOrReplace(cm); } } return null; }); }</code><technical_language>this for immutable Kie server a new CM is created/overridden rollout is triggered, for other cases data is updated rollout is triggered, for case - CM IMMUTABLE labels container deploying undeploying is done in IMMUTABLE CM - is done? Do I understand this correctly</technical_language>

Target:
public synchronized void store(@NotNull String serverId, @NotNull KieServerState kieServerState) { if (!retrieveKieServerId(kieServerState).equals(serverId)) { throw new IllegalArgumentException("Invalid KieServerId: Id does not match with KieServerState."); } processKieServerStateByOpenShift(client -> { DeploymentConfig dc = client.deploymentConfigs().withName(serverId).get(); ConfigMap cm = client.configMaps().withName(serverId).get(); if (Boolean.parseBoolean(kieServerState.getConfiguration() .getConfigItemValue(KIE_SERVER_STATE_IMMUTABLE, Boolean.FALSE.toString()))) { if (Boolean.parseBoolean(System.getProperty(KIE_SERVER_STATE_IMMUTABLE_INIT, Boolean.FALSE.toString()))) { createNewKieServerStateCM(kieServerState, serverId, client); } else { logger.debug("Overwrite immutable KieServer, id:{}, state is not allow.", serverId); } } else if (isServerStateUpdateAllowed(dc, cm, kieServerState)) { ObjectMeta md = cm.getMetadata(); Map<String, String> ann = md.getAnnotations() == null ? new ConcurrentHashMap<>() : md.getAnnotations(); md.setAnnotations(ann); ann.put(STATE_CHANGE_TIMESTAMP, ZonedDateTime.now().format(DateTimeFormatter.ISO_INSTANT)); ann.put(ROLLOUT_REQUIRED, "true"); cm.setData(Collections.singletonMap(CFG_MAP_DATA_KEY, xs.toXML(kieServerState))); client.configMaps().createOrReplace(cm); } return null; }); }
Source:
<code>private void createAndCheckCluster(String compressorOption) { try (Cluster cluster = <START> ClusterUtils.newCluster(ccmRule, compressorOption, "request.timeout = 30 seconds")) { <END> Session session = cluster.connect(schemaClusterRule.keyspace()); ResultSet rs = session.execute( SimpleStatement.newInstance( "INSERT INTO test (k, t, i, f) VALUES (?, ?, ?, ?)", "key", "foo", 42, 24.03f)); assertThat(rs.iterator().hasNext()).isFalse(); ResultSet rs1 = session.execute("SELECT * FROM test WHERE k = 'key'"); assertThat(rs1.iterator().hasNext()).isTrue(); Row row = rs1.iterator().next(); assertThat(rs1.iterator().hasNext()).isFalse(); assertThat(row.getString("k")).isEqualTo("key"); assertThat(row.getString("t")).isEqualTo("foo"); assertThat(row.getInt("i")).isEqualTo(42); assertThat(row.getFloat("f")).isEqualTo(24.03f, offset(0.1f)); } }</code><technical_language>request.timeout needed right? more needed for making schema changes I thought</technical_language>

Target:
private void createAndCheckCluster(String compressorOption) { try (Cluster cluster = ClusterUtils.newCluster(ccmRule, compressorOption)) { Session session = cluster.connect(schemaClusterRule.keyspace()); ResultSet rs = session.execute( SimpleStatement.newInstance( "INSERT INTO test (k, t, i, f) VALUES (?, ?, ?, ?)", "key", "foo", 42, 24.03f)); assertThat(rs.iterator().hasNext()).isFalse(); ResultSet rs1 = session.execute("SELECT * FROM test WHERE k = 'key'"); assertThat(rs1.iterator().hasNext()).isTrue(); Row row = rs1.iterator().next(); assertThat(rs1.iterator().hasNext()).isFalse(); assertThat(row.getString("k")).isEqualTo("key"); assertThat(row.getString("t")).isEqualTo("foo"); assertThat(row.getInt("i")).isEqualTo(42); assertThat(row.getFloat("f")).isEqualTo(24.03f, offset(0.1f)); } }
Source:
<code>public void verifyAppearsOn(String articleName) { <START> PageObjectLogging.log("Verify correct article title", "title correct", appearsListing.getText().equals(articleName)); <END> }</code><technical_language>verification logging method? stick rule. I discuss this approach introducing</technical_language>

Target:
public void verifyAppearsOn(String articleName) { Assertion.assertTrue(appearsListing.getText().equals(articleName)); }
Source:
<code>public static OzoneAcl convertOzoneAcl(OzoneAclInfo aclInfo) { ACLIdentityType aclType; switch (aclInfo.getType()) { case USER: aclType = ACLIdentityType.USER; break; case GROUP: aclType = ACLIdentityType.GROUP; break; case WORLD: aclType = ACLIdentityType.WORLD; break; case ANONYMOUS: aclType = ACLIdentityType.ANONYMOUS; break; case CLIENT_IP: aclType = ACLIdentityType.CLIENT_IP; break; default: throw new IllegalArgumentException("ACL type is not recognized"); } <START> BitSet aclRights = new BitSet(aclInfo.getRightsList().size()); <END> aclInfo.getRightsList().parallelStream().forEach(a -> aclRights.set(ACLType.valueOf(a.name()).ordinal())); return new OzoneAcl(aclType, aclInfo.getName(), aclRights); }</code><technical_language>this set BitSet size *aclInfo.getRightsList().size()*</technical_language>

Target:
public static OzoneAcl convertOzoneAcl(OzoneAclInfo aclInfo) { ACLIdentityType aclType; switch (aclInfo.getType()) { case USER: aclType = ACLIdentityType.USER; break; case GROUP: aclType = ACLIdentityType.GROUP; break; case WORLD: aclType = ACLIdentityType.WORLD; break; case ANONYMOUS: aclType = ACLIdentityType.ANONYMOUS; break; case CLIENT_IP: aclType = ACLIdentityType.CLIENT_IP; break; default: throw new IllegalArgumentException("ACL type is not recognized"); } BitSet aclRights = new BitSet(ACLType.getNoOfAcls()); aclInfo.getRightsList().stream().forEach(a -> aclRights.set(ACLType.valueOf(a.name()).ordinal())); return new OzoneAcl(aclType, aclInfo.getName(), aclRights); }
Source:
<code>public List<DriverRecord> write(final List<DriverRecord> records) throws ConnectionException { if (isBusy.get()) { throw new ConnectionException(message.errorDriverBusy()); } if (this.client == null) { this.connect(); } for (final DriverRecord record : records) { OpcUaRequestInfo requestInfo = OpcUaRequestInfo.extract(record); if (requestInfo == null) { continue; } final TypedValue<?> value = record.getValue(); final NodeId nodeId = new NodeId(requestInfo.nodeNamespaceIndex, requestInfo.nodeId); final VariableNode node = this.client.getAddressSpace().createVariableNode(nodeId); final DataValue newValue = new DataValue(new Variant(value.getValue())); try { logger.debug("writing: to ns={};s={}..", value, requestInfo.nodeNamespaceIndex, requestInfo.nodeId); checkStatus(runSafe(node.writeValue(newValue))); record.setDriverStatus(new DriverStatus(WRITE_SUCCESSFUL)); <START> logger.debug("write successful"); <END> } catch (final Exception e) { record.setDriverStatus(new DriverStatus(WRITE_FAILURE, message.writeFailed(), e)); logger.warn(message.writeFailed(), e); } record.setTimestamp(System.currentTimeMillis()); } return Collections.unmodifiableList(records); }</code><technical_language>this string literal in localization resource</technical_language>

Target:
public List<DriverRecord> write(final List<DriverRecord> records) throws ConnectionException { if (isBusy.get()) { throw new ConnectionException(message.errorDriverBusy()); } if (this.client == null) { this.connect(); } for (final DriverRecord record : records) { OpcUaRequestInfo.extract(record).ifPresent((requestInfo) -> { final TypedValue<?> value = record.getValue(); final NodeId nodeId = new NodeId(requestInfo.nodeNamespaceIndex, requestInfo.nodeId); final VariableNode node = this.client.getAddressSpace().createVariableNode(nodeId); final DataValue newValue = new DataValue(new Variant(value.getValue())); try { logger.debug("writing: to ns={};s={}..", value, requestInfo.nodeNamespaceIndex, requestInfo.nodeId); checkStatus(runSafe(node.writeValue(newValue))); record.setDriverStatus(new DriverStatus(WRITE_SUCCESSFUL)); logger.debug("write successful"); } catch (final Exception e) { record.setDriverStatus(new DriverStatus(WRITE_FAILURE, message.writeFailed(), e)); logger.warn(message.writeFailed(), e); } record.setTimestamp(System.currentTimeMillis()); }); } return Collections.unmodifiableList(records); }
Source:
<code>public boolean friendlyFireCheck(Entity shooter, IGame game, Coords position, boolean includeMobileUnits) { if(friendlyFireCheckResults.containsKey(position)) { return friendlyFireCheckResults.get(position); } Building building = game.getBoard().getBuildingAt(position); if (building == null) { friendlyFireCheckResults.put(position, false); return false; } <START> for(Entity entity : game.getEntitiesVector(position, true)) { if(!entity.isEnemyOf(shooter) && (includeMobileUnits || (entity.getWalkMP(true, false) == 0))) { <END> friendlyFireCheckResults.put(position, true); return true; } } friendlyFireCheckResults.put(position, false); return false; }</code><technical_language>suggestion for (Entity entity : game.getEntitiesVector(position, true)) { if (!entity.isEnemyOf(shooter) && (includeMobileUnits || (entity.getWalkMP(true, false) == 0))) {</technical_language>

Target:
private boolean friendlyFireCheck(Entity shooter, IGame game, Coords position, boolean includeMobileUnits) { if (friendlyFireCheckResults.containsKey(position)) { return friendlyFireCheckResults.get(position); } Building building = game.getBoard().getBuildingAt(position); if (building == null) { friendlyFireCheckResults.put(position, false); return false; } for (Entity entity : game.getEntitiesVector(position, true)) { if (!entity.isEnemyOf(shooter) && (includeMobileUnits || (entity.getWalkMP(true, false) == 0))) { friendlyFireCheckResults.put(position, true); return true; } } friendlyFireCheckResults.put(position, false); return false; }
Source:
<code>protected boolean shouldAttemptLookup(CacheEntry e) { <START> return e == null || (e.isNull() || e.getValue() == null) && !e.skipRemoteGet(); <END> }</code><technical_language>I suggest change name of skipRemoteGet() skipFetch(). Also, change name of internal flag setter :)</technical_language>

Target:
protected boolean shouldAttemptLookup(CacheEntry e) { return e == null || (e.isNull() || e.getValue() == null) && !e.skipLookup(); }
Source:
<code>protected <START> boolean checkKeyIntent( <END> int authUid, Intent intent) throws SecurityException { long bid = Binder.clearCallingIdentity(); try { PackageManager pm = mContext.getPackageManager(); ResolveInfo resolveInfo = pm.resolveActivityAsUser(intent, 0, mAccounts.userId); if (resolveInfo == null) { return false; } ActivityInfo targetActivityInfo = resolveInfo.activityInfo; int targetUid = targetActivityInfo.applicationInfo.uid; if (!isExportedSystemActivity(targetActivityInfo) && (PackageManager.SIGNATURE_MATCH != pm.checkSignatures(authUid, targetUid))) { String pkgName = targetActivityInfo.packageName; String activityName = targetActivityInfo.name; String tmpl = "KEY_INTENT resolved to an Activity (%s) in a package (%s) that " + "does not share a signature with the supplying authenticator (%s)."; throw new SecurityException( String.format(tmpl, activityName, pkgName, mAccountType)); } return true; } catch (SecurityException se) { return false; } finally { Binder.restoreCallingIdentity(bid); } }</code><technical_language>change require return checked throwing exception</technical_language>

Target:
protected boolean checkKeyIntent(int authUid, Intent intent) { long bid = Binder.clearCallingIdentity(); try { PackageManager pm = mContext.getPackageManager(); ResolveInfo resolveInfo = pm.resolveActivityAsUser(intent, 0, mAccounts.userId); if (resolveInfo == null) { return false; } ActivityInfo targetActivityInfo = resolveInfo.activityInfo; int targetUid = targetActivityInfo.applicationInfo.uid; if (!isExportedSystemActivity(targetActivityInfo) && (PackageManager.SIGNATURE_MATCH != pm.checkSignatures(authUid, targetUid))) { String pkgName = targetActivityInfo.packageName; String activityName = targetActivityInfo.name; String tmpl = "KEY_INTENT resolved to an Activity (%s) in a package (%s) that " + "does not share a signature with the supplying authenticator (%s)."; Log.e(TAG, String.format(tmpl, activityName, pkgName, mAccountType)); return false; } return true; } finally { Binder.restoreCallingIdentity(bid); } }
Source:
<code>private static boolean isExtended(ClassTree classTree) { List<IdentifierTree> usages = classTree.symbol().usages(); return usages.stream().anyMatch(usage -> { Tree parent = usage.parent(); <START> return parent != null && parent.is(Kind.CLASS); <END> }); }</code><technical_language>This work if fully qualified name is in extend clause. class Foo extends my.pack.age.AbstractClass I more for a subvisitor for type of extend clause anonymous constructor</technical_language>

Target:
private static boolean isExtended(ClassTree classTree) { IsExtendedVisitor isExtendedVisitor = new IsExtendedVisitor(classTree.symbol().type()); classTree.accept(isExtendedVisitor); return isExtendedVisitor.isExtended; }
Source:
<code>protected void validateRespPayloadAndExchangeType( List<IkePayload> respPayloads, @ExchangeType int exchangeType) throws InvalidSyntaxException { if (exchangeType != EXCHANGE_TYPE_INFORMATIONAL) { throw new InvalidSyntaxException( "Unexpected exchange type in Delete Child response: " + exchangeType); } for (IkePayload payload : respPayloads) { handlePayload: switch (payload.payloadType) { case PAYLOAD_TYPE_DELETE: <START> break; <END> case PAYLOAD_TYPE_NOTIFY: IkeNotifyPayload notify = (IkeNotifyPayload) payload; if (!notify.isErrorNotify()) { logw( "Unexpected or unknown status notification in Delete Child" + " response: " + notify.notifyType); break handlePayload; } throw new UnsupportedOperationException( "Cannot handle error notifications in a Delete Child response"); default: throw new InvalidSyntaxException( "Unexpected payload found in Delete Child response: " + payload.payloadType); } } }</code><technical_language>Suggest adding "break handlePayload"</technical_language>

Target:
protected void validateRespPayloadAndExchangeType( List<IkePayload> respPayloads, @ExchangeType int exchangeType) throws InvalidSyntaxException { if (exchangeType != EXCHANGE_TYPE_INFORMATIONAL) { throw new InvalidSyntaxException( "Unexpected exchange type in Delete Child response: " + exchangeType); } for (IkePayload payload : respPayloads) { handlePayload: switch (payload.payloadType) { case PAYLOAD_TYPE_DELETE: break handlePayload; case PAYLOAD_TYPE_NOTIFY: IkeNotifyPayload notify = (IkeNotifyPayload) payload; if (!notify.isErrorNotify()) { logw( "Unexpected or unknown status notification in Delete Child" + " response: " + notify.notifyType); break handlePayload; } throw new UnsupportedOperationException( "Cannot handle error notifications in a Delete Child response"); default: throw new InvalidSyntaxException( "Unexpected payload found in Delete Child response: " + payload.payloadType); } } }
Source:
<code>protected PathRef getExistingUserWorkspace(CoreSession session, PathRef rootref, NuxeoPrincipal principal, String username) { UserManager userManager = Framework.getService(UserManager.class); if (principal == null) { principal = userManager.getPrincipal(username); <START> } <END> PathRef freeRef = null; for (String name : getCandidateUserWorkspaceNames(username)) { PathRef ref = new PathRef(rootref, name); if (session.exists(ref) && principal != null && session.hasPermission(principal, ref, SecurityConstants.EVERYTHING)) { return ref; } @SuppressWarnings("boxing") boolean exists = CoreInstance.doPrivileged(session, (CoreSession s) -> s.exists(ref)); if (!exists && freeRef == null) { freeRef = ref; } } if (freeRef != null) { PathRef ref = freeRef; String path = CoreInstance.doPrivileged(session, s -> { DocumentModel uwsModel = doCreateUserWorkspace(session, ref, username); return s.getOrCreateDocument(uwsModel, doc -> initCreateUserWorkspace(s, doc, username)) .getPathAsString(); }); return new PathRef(path); } throw new DocumentSecurityException(username); }</code><technical_language>replaced by: if (principal == null) { principal = Framework.getService(UserManager.class).getPrincipal(username); }</technical_language>

Target:
protected PathRef getExistingUserWorkspace(CoreSession session, PathRef rootref, NuxeoPrincipal principal, String username) { if (principal == null) { principal = Framework.getService(UserManager.class).getPrincipal(username); } PathRef freeRef = null; for (String name : getCandidateUserWorkspaceNames(username)) { PathRef ref = new PathRef(rootref, name); if (session.exists(ref) && principal != null && session.hasPermission(principal, ref, SecurityConstants.EVERYTHING)) { return ref; } @SuppressWarnings("boxing") boolean exists = CoreInstance.doPrivileged(session, (CoreSession s) -> s.exists(ref)); if (!exists && freeRef == null) { freeRef = ref; } } if (freeRef != null) { PathRef ref = freeRef; String path = CoreInstance.doPrivileged(session, s -> { DocumentModel uwsModel = doCreateUserWorkspace(session, ref, username); return s.getOrCreateDocument(uwsModel, doc -> initCreateUserWorkspace(s, doc, username)) .getPathAsString(); }); return new PathRef(path); } throw new DocumentSecurityException(username); }
Source:
<code>public void finish() { Intent intent = new Intent(); Bundle bundle = new Bundle(); String string; <START> if (mType == DELETED) { <END> string = getString(R.string.delete_announcement); } else if (mType == EDITED) { string = getString(R.string.edit_announcement); } else { string = null; } bundle.putString(string, NetworkUtils.writeAsString(this, mAnnouncement)); bundle.putInt(getString(R.string.announcement_type), mType); intent.putExtras(bundle); setResult(Activity.RESULT_OK, intent); super.finish(); }</code><technical_language>pls switch</technical_language>

Target:
public void finish() { Intent intent = new Intent(); Bundle bundle = new Bundle(); String string; switch (mType) { case ORIGINAL: string = null; break; default: string = getString(R.string.change_announcement); } bundle.putString(string, NetworkUtils.writeAsString(this, mAnnouncement)); bundle.putInt(getString(R.string.announcement_type), mType); intent.putExtras(bundle); setResult(Activity.RESULT_OK, intent); super.finish(); }
Source:
<code>private List<Long> getConsecutiveSkipsCount(final Long accountId, final int tzOffsetMillis) { final List<Long> skippedIds = new ArrayList<>(); final DateTime today = DateTime.now(DateTimeZone.UTC).plusMillis(tzOffsetMillis).withTimeAtStartOfDay(); final List<Response> responses = this.questionResponseDAO.getLastFewResponses(accountId, this.checkSkipsNum); for (final Response response : responses) { if (response.skip == null && response.askTime.isEqual(today)) { continue; } Boolean skip = null; if (response.skip != null) { if (response.skip.isPresent()) { <START> skip = response.skip.get(); <END> } } if (skip != null && !skip) { break; } skippedIds.add(response.accountQuestionId); } return skippedIds; }</code><technical_language>this in this PR</technical_language>

Target:
private List<Long> getConsecutiveSkipsCount(final Long accountId, final int tzOffsetMillis) { final List<Long> skippedIds = new ArrayList<>(); final DateTime today = DateTime.now(DateTimeZone.UTC).plusMillis(tzOffsetMillis).withTimeAtStartOfDay(); final List<Response> responses = this.questionResponseDAO.getLastFewResponses(accountId, this.checkSkipsNum); for (final Response response : responses) { if (response.skip == null && response.askTime.isEqual(today)) { continue; } Boolean skip = null; if (response.skip != null) { skip = response.skip.get(); } if (skip != null && !skip) { break; } skippedIds.add(response.accountQuestionId); } return skippedIds; }
Source:
<code>protected void setUp() throws Exception { super.setUp(); configurationManager.getConfiguration(). addPackageConfig("foo", new PackageConfig.Builder("foo").namespace("/namespace").build()); view = new ServletRedirectResult(); container.inject(view); responseMock = new Mock(HttpServletResponse.class); requestMock = new Mock(HttpServletRequest.class); requestMock.matchAndReturn("getContextPath", "/context"); ResultConfig resultConfig = new ResultConfig.Builder("", "").build(); Map<String, ResultConfig> results = new HashMap<>(); results.put("myResult", resultConfig); ActionConfig actionConfig = new ActionConfig.Builder("", "", "") .addResultConfigs(results).build(); ActionContext ac = ActionContext.getContext(); ac.setServletRequest((HttpServletRequest) requestMock.proxy()); ac.setServletResponse((HttpServletResponse) responseMock.proxy()); MockActionInvocation ai = new MockActionInvocation(); ai.setInvocationContext(ac); ai.setResultCode("myResult"); <START> ai.setInvocationContext(ac); <END> ActionProxy mockActionProxy = createNiceMock(ActionProxy.class); ai.setProxy(mockActionProxy); expect(mockActionProxy.getConfig()).andReturn(actionConfig).anyTimes(); replay(mockActionProxy); ai.setStack(ActionContext.getContext().getValueStack()); this.ai = ai; }</code><technical_language>Is setting invocation context intentional in test (logic in previous version)</technical_language>

Target:
protected void setUp() throws Exception { super.setUp(); configurationManager.getConfiguration(). addPackageConfig("foo", new PackageConfig.Builder("foo").namespace("/namespace").build()); view = new ServletRedirectResult(); container.inject(view); responseMock = new Mock(HttpServletResponse.class); requestMock = new Mock(HttpServletRequest.class); requestMock.matchAndReturn("getContextPath", "/context"); ResultConfig resultConfig = new ResultConfig.Builder("", "").build(); Map<String, ResultConfig> results = new HashMap<>(); results.put("myResult", resultConfig); ActionConfig actionConfig = new ActionConfig.Builder("", "", "") .addResultConfigs(results).build(); ActionContext ac = ActionContext.getContext(); ac.withServletRequest((HttpServletRequest) requestMock.proxy()); ac.withServletResponse((HttpServletResponse) responseMock.proxy()); MockActionInvocation ai = new MockActionInvocation(); ai.setInvocationContext(ac); ai.setResultCode("myResult"); ActionProxy mockActionProxy = createNiceMock(ActionProxy.class); ai.setProxy(mockActionProxy); expect(mockActionProxy.getConfig()).andReturn(actionConfig).anyTimes(); replay(mockActionProxy); ai.setStack(ActionContext.getContext().getValueStack()); this.ai = ai; }