auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void run() { MessageReceiver receiver = new MessageReceiver(mmHandler); <START> while (true) { END> try { mmReader.readAvailable(receiver); } catch (IOException e) { e.printStackTrace(); break; } catch (Throwable t) { t.printStackTrace(); break; } } stopWriteThread(); disconnect(); }</code><technical_language>Is a ticket add this later? happen this code pulled in</technical_language>

Target:
public void run() { MessageReceiver receiver = new MessageReceiver(this.handler); boolean running = true; while (running) { try { this.reader.readAvailable(receiver); } catch (IOException e) { e.printStackTrace(); } finally { running = false; stopWriteThread(); disconnect(); } } }
Source:
<code>public void shouldExecute() throws Exception { Assert.assertTrue(this.mocker.getComponentUnderTest().shouldExecute(new XWikiDBVersion(54689))); <START> Assert.assertTrue(this.mocker.getComponentUnderTest().shouldExecute(new XWikiDBVersion(54693))); <END> }</code><technical_language>numbers copy/pasted, change 71500 71510</technical_language>

Target:
public void shouldExecute() throws Exception { Assert.assertTrue(this.mocker.getComponentUnderTest().shouldExecute(new XWikiDBVersion(71500))); Assert.assertTrue(this.mocker.getComponentUnderTest().shouldExecute(new XWikiDBVersion(71510))); }
Source:
<code>public boolean isVolumeEmpty(String volume) throws IOException { String volumePrefix = getVolumeKey(volume + OM_KEY_PREFIX); <START> if (bucketTable instanceof TypedTable) { <END> Iterator<Map.Entry<CacheKey<String>, CacheValue<OmBucketInfo>>> iterator = ((TypedTable< String, OmBucketInfo>) bucketTable).cacheIterator(); while (iterator.hasNext()) { Map.Entry< CacheKey< String >, CacheValue< OmBucketInfo > > entry = iterator.next(); String key = entry.getKey().getKey(); OmBucketInfo omBucketInfo = entry.getValue().getValue(); if (key.startsWith(volumePrefix) && omBucketInfo != null) { return false; } } } try (TableIterator<String, ? extends KeyValue<String, OmBucketInfo>> bucketIter = bucketTable.iterator()) { KeyValue<String, OmBucketInfo> kv = bucketIter.seek(volumePrefix); if (kv != null && kv.getKey().startsWith(volumePrefix)) { return false; } } return true; }</code><technical_language>this check false</technical_language>

Target:
public boolean isVolumeEmpty(String volume) throws IOException { String volumePrefix = getVolumeKey(volume + OM_KEY_PREFIX); Iterator<Map.Entry<CacheKey<String>, CacheValue<OmBucketInfo>>> iterator = ((TypedTable< String, OmBucketInfo>) bucketTable).cacheIterator(); while (iterator.hasNext()) { Map.Entry< CacheKey< String >, CacheValue< OmBucketInfo > > entry = iterator.next(); String key = entry.getKey().getCacheKey(); OmBucketInfo omBucketInfo = entry.getValue().getCacheValue(); if (key.startsWith(volumePrefix) && omBucketInfo != null) { return false; } } try (TableIterator<String, ? extends KeyValue<String, OmBucketInfo>> bucketIter = bucketTable.iterator()) { KeyValue<String, OmBucketInfo> kv = bucketIter.seek(volumePrefix); if (kv != null && kv.getKey().startsWith(volumePrefix) && bucketTable.get(kv.getKey()) != null) { return false; } } return true; }
Source:
<code>private void backUpCompactionPolicyInfo(String dataDir, CompactionPolicySwitchInfo compactionPolicySwitchInfo) { if (dataDir != null && !dataDir.isEmpty()) { <START> File tempFile = new File(Paths.get(dataDir, COMPACT_POLICY_INFO_PATH).toString()); <END> try { tempFile.createNewFile(); objectMapper.defaultPrettyPrintingWriter().writeValue(tempFile, compactionPolicySwitchInfo); } catch (IOException e) { logger.error("Exception while store compaction policy info for local report. Output file path - {}", tempFile.getAbsolutePath(), e); } } }</code><technical_language>nit: I encourage create write data a temporary file rename temporary file COMPACT_POLICY_INFO_PATH file File tempFile = new File(dataDir, COMPACT_POLICY_INFO_PATH + ".temp"); if (!tempFile.exists()) { tempFile.createNewFile(); } objectMapper.defaultPrettyPrintingWriter().writeValue(tempFile, compactionPolicySwitchInfo); tempFile.renameTo(new File(dataDir, COMPACT_POLICY_INFO_PATH); reason a temporary file rename is POSIX guarantees file rename is atomic operation, file write. json file is pretty small file writing atomic, a good pattern follow</technical_language>

Target:
private void backUpCompactionPolicyInfo(String dataDir, CompactionPolicySwitchInfo compactionPolicySwitchInfo) { if (dataDir != null && !dataDir.isEmpty()) { File tempFile = new File(Paths.get(dataDir, COMPACT_POLICY_INFO_PATH + ".temp").toString()); try { tempFile.createNewFile(); objectMapper.defaultPrettyPrintingWriter().writeValue(tempFile, compactionPolicySwitchInfo); tempFile.renameTo(new File(Paths.get(dataDir, COMPACT_POLICY_INFO_PATH).toString())); } catch (IOException e) { logger.error("Exception while store compaction policy info for local report. Output file path - {}", tempFile.getAbsolutePath(), e); } } }
Source:
<code>protected DiskProfiles mapCollection(List<org.ovirt.engine.core.common.businessentities.profiles.DiskProfile> entities) { DiskProfiles collection = new DiskProfiles(); Map<Guid, List<Qos>> qosMap = new HashMap<>(); for (org.ovirt.engine.core.common.businessentities.profiles.DiskProfile entity : entities) { DiskProfile profile = populate(map(entity), entity); collection.getDiskProfiles().add(profile); if (entity.getQosId() != null) { List<Qos> qosList = qosMap.get(entity.getQosId()); <START> if (qosList == null) { <END> qosList = new ArrayList<>(); qosMap.put(entity.getQosId(), qosList); } qosList.add(profile.getQos()); } } handleQosDataCenterLinks(qosMap); for (DiskProfile diskProfile : collection.getDiskProfiles()) { addLinks(diskProfile); } return collection; }</code><technical_language>consider putIfAbsent</technical_language>

Target:
protected DiskProfiles mapCollection(List<org.ovirt.engine.core.common.businessentities.profiles.DiskProfile> entities) { DiskProfiles collection = new DiskProfiles(); Map<Guid, List<Qos>> qosMap = new HashMap<>(); for (org.ovirt.engine.core.common.businessentities.profiles.DiskProfile entity : entities) { DiskProfile profile = populate(map(entity), entity); collection.getDiskProfiles().add(profile); if (entity.getQosId() != null) { List<Qos> qosList = qosMap.computeIfAbsent(entity.getQosId(), id -> new ArrayList<>()); qosList.add(profile.getQos()); } } handleQosDataCenterLinks(qosMap); for (DiskProfile diskProfile : collection.getDiskProfiles()) { addLinks(diskProfile); } return collection; }
Source:
<code>public byte[] getBinary(int ordinal) { BytesColumnVector.Bytes byteArray = getByteArray(ordinal); if (byteArray.len == byteArray.data.length) { return byteArray.data; } else { byte[] ret = new byte[byteArray.len]; <START> System.arraycopy(byteArray.data, byteArray.offset, ret, 0, byteArray.len); <END> return ret; } }</code><technical_language>Arrays.copyOfRange</technical_language>

Target:
public byte[] getBinary(int ordinal) { BytesColumnVector.Bytes byteArray = getByteArray(ordinal); if (byteArray.len == byteArray.data.length) { return byteArray.data; } else { return Arrays.copyOfRange(byteArray.data, byteArray.offset, byteArray.len); } }
Source:
<code>public void testQueryNameDisplayable() { String test = "select * from employee e (where e.id <> 0 and e.name ='foo' and e.other != 'other'"; long start = System.currentTimeMillis(); for ( int looper = 0; looper < 500000; looper ++) { QueryName name = new QueryName(test); } long end = System.currentTimeMillis(); long duration = (end - start); <START> Assert.assertTrue("Duration of QueryName.displayable called in a 500000 loop must be lower than 3000 milliseconds, but was " + duration, duration < 3000); <END> }</code><technical_language>git grep TimeoutUtil wildfly repo shows usages, feel free get inspired too</technical_language>

Target:
public void testQueryNameDisplayable() { String test = "select * from employee e (where e.id <> 0 and e.name ='foo' and e.other != 'other'"; long start = System.currentTimeMillis(); for ( int looper = 0; looper < 500000; looper ++) { QueryName name = new QueryName(test); } long end = System.currentTimeMillis(); long duration = (end - start); Assert.assertTrue("Duration of QueryName.displayable called in a 500000 loop must be lower than 3000 milliseconds, but was " + duration, duration < TIMEOUT); }
Source:
<code>public void Export_SerializerConfig() { exporter.setTargetFolder(new File("target/gen7")); exporter.setSerializerConfig(new SimpleSerializerConfig(true, true, true, true, "")); <START> exporter.export(Cat.class.getPackage()); <END> }</code><technical_language>assertion here</technical_language>

Target:
public void Export_SerializerConfig() { exporter.setTargetFolder(new File("target/gen7")); exporter.setSerializerConfig(new SimpleSerializerConfig(true, true, true, true, "")); exporter.export(getClass().getPackage()); assertTrue(new File("target/gen7/com/querydsl/codegen/QExampleEmbeddable.java").exists()); assertTrue(new File("target/gen7/com/querydsl/codegen/QExampleEmbedded.java").exists()); assertTrue(new File("target/gen7/com/querydsl/codegen/QExampleEntity.java").exists()); assertTrue(new File("target/gen7/com/querydsl/codegen/QExampleEntityInterface.java").exists()); assertTrue(new File("target/gen7/com/querydsl/codegen/QExampleSupertype.java").exists()); assertTrue(new File("target/gen7/com/querydsl/codegen/sub/QExampleEntity2.java").exists()); }
Source:
<code>public DruidServerMetadata getMetadata(@Self DruidNode node, DruidServerConfig config) { return new DruidServerMetadata( node.getHost(), node.getHost(), config.getMaxSize(), <START> config.getType(), <END> config.getTier() ); }</code><technical_language>This hard-coded, configuration. a constructor parameter Module</technical_language>

Target:
public DruidServerMetadata getMetadata(@Self DruidNode node, DruidServerConfig config) { return new DruidServerMetadata( node.getHost(), node.getHost(), config.getMaxSize(), nodeType, config.getTier() ); }
Source:
<code>public void onConnected(Session session) { Log.d(TAG, "onConnected: Connected to session " + session.getSessionId()); CustomVideoCapturer capturer = new CustomVideoCapturer(MainActivity.this, Publisher.CameraCaptureResolution.MEDIUM, Publisher.CameraCaptureFrameRate.FPS_30); capturer.setCustomVideoCapturerDataSource(new CustomVideoCapturer.CustomVideoCapturerDataSource() { @Override public byte[] retrieveMetadata() { return getCurrentTimeStamp().getBytes(); } }); InvertedColorsVideoRenderer renderer = new InvertedColorsVideoRenderer(MainActivity.this); <START> renderer.setInvertedColorsVideoRendererMetadataListener(new InvertedColorsVideoRenderer.InvertedColorsVideoRendererMetadataListener() { <END> @Override public void onMetadataReady(byte[] metadata) { String timestamp = null; try { timestamp = new String(metadata, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } System.out.println(timestamp); } }); mPublisher = new Publisher.Builder(MainActivity.this) .name("publisher") .capturer(capturer) .renderer(renderer).build(); mPublisher.setPublisherListener(this); mPublisher.setStyle(BaseVideoRenderer.STYLE_VIDEO_SCALE, BaseVideoRenderer.STYLE_VIDEO_FILL); mPublisherViewContainer.addView(mPublisher.getView()); if (mPublisher.getView() instanceof GLSurfaceView) { ((GLSurfaceView)(mPublisher.getView())).setZOrderOnTop(true); } mSession.publish(mPublisher); }</code><technical_language>I current custom renderer is InvertedColorsVideoRenderer... feels a lot strange here. wdyt? thiking changing Custom-Video-Driver sample a CustomRenderer this Inverted too. This sample CustomRenderer (without inversion)</technical_language>

Target:
public void onConnected(Session session) { Log.d(TAG, "onConnected: Connected to session " + session.getSessionId()); CustomVideoCapturer capturer; capturer = new CustomVideoCapturer(MainActivity.this, Publisher.CameraCaptureResolution.MEDIUM, Publisher.CameraCaptureFrameRate.FPS_30); capturer.setCustomVideoCapturerDataSource(new CustomVideoCapturer.CustomVideoCapturerDataSource() { @Override public byte[] retrieveMetadata() { return getCurrentTimeStamp().getBytes(); } }); InvertedColorsVideoRenderer renderer = new InvertedColorsVideoRenderer(MainActivity.this); renderer.setInvertedColorsVideoRendererMetadataListener(new InvertedColorsVideoRenderer.InvertedColorsVideoRendererMetadataListener() { @Override public void onMetadataReady(byte[] metadata) { String timestamp = null; try { timestamp = new String(metadata, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } System.out.println(timestamp); } }); mPublisher = new Publisher.Builder(MainActivity.this) .name("publisher") .capturer(capturer) .renderer(renderer).build(); mPublisher.setPublisherListener(this); mPublisher.setStyle(BaseVideoRenderer.STYLE_VIDEO_SCALE, BaseVideoRenderer.STYLE_VIDEO_FILL); mPublisherViewContainer.addView(mPublisher.getView()); if (mPublisher.getView() instanceof GLSurfaceView) { ((GLSurfaceView)(mPublisher.getView())).setZOrderOnTop(true); } mSession.publish(mPublisher); }
Source:
<code>protected String doIt() throws Exception { final EDIExportStatus targetExportStatus = EDIExportStatus.ofCode(p_TargetExportStatus); <START> for (final ArchiveId logId : getSelectedDocOutboundLogIds()) <END> { ChangeEDI_ExportStatusHelper.C_DocOutbound_LogDoIt(targetExportStatus, logId); } return MSG_OK; }</code><technical_language>ArchiveId for C_Doc_OutBound_Log_ID. (note a dedicated AD_Archive table is *referenced* C_Doc_Outbound_Log_Line)</technical_language>

Target:
protected String doIt() throws Exception { final EDIExportStatus targetExportStatus = EDIExportStatus.ofCode(p_TargetExportStatus); for (final DocOutboundLogId logId : getSelectedDocOutboundLogIds()) { ChangeEDI_ExportStatusHelper.C_DocOutbound_LogDoIt(targetExportStatus, logId); } return MSG_OK; }
Source:
<code><START> public void testEquals() throws Exception { <END> Map<String, Object> map = new HashMap<>(); map.put("a", "aval"); map.put("b", "bval"); IotasEvent event1 = new IotasEventImpl(map); IotasEvent event2 = new IotasEventImpl(map, event1.getId()); assertEquals(event1, event2); }</code><technical_language>if writing test for equals, for consistency write test for hasCode() well</technical_language>

Target:
public void testEquals() throws Exception { Map<String, Object> map = new HashMap<>(); map.put("a", "aval"); map.put("b", "bval"); IotasEvent event1 = new IotasEventImpl(map, StringUtils.EMPTY); IotasEvent event2 = new IotasEventImpl(map, StringUtils.EMPTY, event1.getId()); assertEquals(event1, event2); }
Source:
<code>protected String getProbeSetName() { if (BAIT_SET_NAME != null) { return BAIT_SET_NAME; } if (BAIT_INTERVALS.size() == 1) { return CollectTargetedMetrics.renderProbeNameFromFilename(BAIT_INTERVALS.get(0)); } else { <START> throw new PicardException("Cannot infer BAIT_SET_NAME because there is not exactly one BAIT_INTERVALS provided."); <END> } }</code><technical_language>throwing exception punting? loop files render name1+name2+name3... friendlier</technical_language>

Target:
protected String getProbeSetName() { if (BAIT_SET_NAME != null) { return BAIT_SET_NAME; } else { final SortedSet<String> baitSetNames = new TreeSet<String>(); for (final File file : BAIT_INTERVALS) { baitSetNames.add(CollectTargetedMetrics.renderProbeNameFromFile(file)); } return StringUtil.join(".", baitSetNames); } }
Source:
<code>public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { <START> if (DisallowedDisguises.disabled) <END> { msg("Disguises are not enabled."); return true; } FUtil.adminAction(sender.getName(), "Undisguising all non-admins", true); plugin.ldb.undisguiseAll(false); return true; }</code><technical_language>this throw error LibsDisguises is enabled server? instead check if ldb.getLibsDisguisePlugin() is null not</technical_language>

Target:
public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { if (plugin.ldb.getLibsDisguisesPlugin() == null) { msg("libsDisguises is not enabled."); return true; } if (DisallowedDisguises.disabled) { msg("Disguises are not enabled."); return true; } FUtil.adminAction(sender.getName(), "Undisguising all non-admins", true); plugin.ldb.undisguiseAll(false); return true; }
Source:
<code>public Optional<GradleBuild> getGradleBuild(IProject project) { try { if (GradleProjectNature.isPresentOn(project)) { ProjectConfiguration projectConfiguration = CorePlugin.configurationManager().loadProjectConfiguration(project); BuildConfiguration buildConfig = projectConfiguration.getBuildConfiguration(); return Optional.<GradleBuild>of(new DefaultGradleBuild(buildConfig)); } else { return Optional.absent(); } } catch (RuntimeException e) { <START> CorePlugin.logger().debug("Cannot load configuration for project " + project.getName()); <END> return Optional.absent(); } }</code><technical_language>This encapsulated instead of spreading error handling in multiple places. E.g. tryLoad</technical_language>

Target:
public Optional<GradleBuild> getGradleBuild(IProject project) { if (GradleProjectNature.isPresentOn(project)) { ProjectConfiguration projectConfiguration = CorePlugin.configurationManager().tryLoadProjectConfiguration(project); if (projectConfiguration != null) { return Optional.<GradleBuild>of(new DefaultGradleBuild(projectConfiguration.getBuildConfiguration())); } else { return Optional.absent(); } } else { return Optional.absent(); } }
Source:
<code>public static String getParameterOrDefaultValue(ParameterCore key) { if (Objects.nonNull(key.getType())) { if (key.getType().equals(String.class)) { return getParameter(key.getName(), (String) key.getDefaultValue()); } throw new ConfigParameterException(key.getName(), "String"); } <START> throw new ConfigParameterException("Type of key is null"); <END> }</code><technical_language>I suggest output name of key is null this difficult fix it</technical_language>

Target:
public static String getParameterOrDefaultValue(ParameterCore key) { checkNotNullKeyType(key); if (key.getType().equals(String.class)) { return getParameter(key.getName(), (String) key.getDefaultValue()); } throw new ConfigParameterException(key.getName(), "String"); }
Source:
<code>private void beforeFirstRefreshTreatment(boolean isVdsUpOrGoingToMaintenance) { if (_vdsManager.getbeforeFirstRefresh()) { boolean flagsChanged = false; final AtomicBoolean processHardwareCapsNeededTemp = new AtomicBoolean(); _vdsManager.refreshCapabilities(processHardwareCapsNeededTemp, _vds); flagsChanged = processHardwareCapsNeededTemp.get(); _vdsManager.setbeforeFirstRefresh(false); refreshedCapabilities = true; _saveVdsDynamic = true; processHardwareCapsNeeded = (processHardwareCapsNeeded) ? processHardwareCapsNeeded : flagsChanged; } else if (isVdsUpOrGoingToMaintenance || _vds.getStatus() == VDSStatus.Error) { return; } <START> if (_vds.getStatus() != VDSStatus.Up) { <END> AuditLogableBase logable = new AuditLogableBase(_vds.getId()); logable.addCustomValue("VdsStatus", _vds.getStatus().toString()); auditLog(logable, AuditLogType.VDS_DETECTED); } }</code><technical_language>Martin, audit log added InitiVdsOnUp, ? this logging redundant</technical_language>

Target:
private void beforeFirstRefreshTreatment(boolean isVdsUpOrGoingToMaintenance) { if (_vdsManager.getbeforeFirstRefresh()) { boolean flagsChanged = false; final AtomicBoolean processHardwareCapsNeededTemp = new AtomicBoolean(); _vdsManager.refreshCapabilities(processHardwareCapsNeededTemp, _vds); flagsChanged = processHardwareCapsNeededTemp.get(); _vdsManager.setbeforeFirstRefresh(false); refreshedCapabilities = true; _saveVdsDynamic = true; processHardwareCapsNeeded = (processHardwareCapsNeeded) ? processHardwareCapsNeeded : flagsChanged; } else if (isVdsUpOrGoingToMaintenance || _vds.getStatus() == VDSStatus.Error) { return; } if (_vds.getStatus() != VDSStatus.Up) { AuditLogableBase logable = new AuditLogableBase(_vds.getId()); logable.addCustomValue("HostStatus", _vds.getStatus().toString()); auditLog(logable, AuditLogType.VDS_DETECTED); } }
Source:
<code>public boolean match(Double outputValue, Double correctValue) { try { double a = outputValue; double b = correctValue; if (Double.isNaN(a) && Double.isNaN(b)) { return true; <START> } else if (Double.isInfinite(a) && Double.isInfinite(b) && a * b < 0) { <END> return true; } else if (Math.abs(a - b) < COMPARISON_THRESHOLD * a) { return true; } return false; } catch(NumberFormatException e) { return false; } }</code><technical_language>infinite values comparable ==? I multiplication yield a positive number if signs equal (a * b > 0). yet, check signs more explicitly (I assume this works for pos/neg infinity): Math.signum(a) == Math.signum(b)</technical_language>

Target:
public boolean match(Double outputValue, Double correctValue) { try { double a = outputValue; double b = correctValue; if (a == b) { return true; } else if (Double.isNaN(a) && Double.isNaN(b)) { return true; } else if (Math.abs(a - b) < COMPARISON_THRESHOLD * b) { return true; } else { return false; } } catch(NumberFormatException e) { return false; } }
Source:
<code>public void testCorrect() throws Exception { final String expected = new String(Files.readAllBytes(Paths.get( <START> getPath("ExpectedSuppressionsStringPrinter.txt"))), <END> StandardCharsets.UTF_8).replaceAll("\\\\r\\\\n", "\\\\n"); final File input = new File(getPath("InputSuppressionsStringPrinter.java")); final String lineAndColumnNumber = "3:1"; final int tabWidth = 2; final String result = SuppressionsStringPrinter.printSuppressions(input, lineAndColumnNumber, tabWidth); Assert.assertEquals("Invalid xpath queries", expected, result); }</code><technical_language>put Expected file if is huge embedded. I do expected output huge. If some previous discussion .. please give a link review. If discussions before, please inline expected UT method</technical_language>

Target:
public void testCorrect() throws Exception { final String expected = "/CLASS_DEF[@text='InputSuppressionsStringPrinter']" + EOL + "/CLASS_DEF[@text='InputSuppressionsStringPrinter']/MODIFIERS" + EOL + "/CLASS_DEF[@text='InputSuppressionsStringPrinter']/MODIFIERS/LITERAL_PUBLIC" + EOL; final File input = new File(getPath("InputSuppressionsStringPrinter.java")); final String lineAndColumnNumber = "3:1"; final int tabWidth = 2; final String result = SuppressionsStringPrinter.printSuppressions(input, lineAndColumnNumber, tabWidth); Assert.assertEquals("Invalid xpath queries", expected, result); }
Source:
<code>Set<InetSocketAddress> maybeFilterLocalHosts(Set<InetSocketAddress> hosts) { <START> if (new Random().nextDouble() < config.localHostWeighting()) { <END> Set<InetSocketAddress> localFilteredHosts = Sets.intersection(localHosts, hosts); if (!localFilteredHosts.isEmpty()) { localHostsSelected.inc(); return localFilteredHosts; } } randomHostsSelected.inc(); return hosts; }</code><technical_language>this Random a field - need create a new for usage</technical_language>

Target:
Set<InetSocketAddress> maybeFilterLocalHosts(Set<InetSocketAddress> hosts) { if (random.nextDouble() < config.localHostWeighting()) { Set<InetSocketAddress> localFilteredHosts = Sets.intersection(localHosts, hosts); if (!localFilteredHosts.isEmpty()) { localHostsSelected.inc(); return localFilteredHosts; } } randomHostsSelected.inc(); return hosts; }
Source:
<code>public Schema apply(Schema originalSchema) throws SchemaSyncError { Schema newSchema = originalSchema.copy(); <START> Database database = findDatabase(newSchema, dbName, ifExists); <END> if ( database == null && !ifExists ) { throw new SchemaSyncError("Can't drop missing database: " + dbName); } newSchema.getDatabases().remove(database); return newSchema; }</code><technical_language>nitpic: interchanging usage of findDatabase SchemaChange Schema is confusing</technical_language>

Target:
public Schema apply(Schema originalSchema) throws SchemaSyncError { Schema newSchema = originalSchema.copy(); Database database = newSchema.findDatabase(dbName); if ( database == null ) { if ( ifExists ) { return newSchema; } else { throw new SchemaSyncError("Can't drop missing database: " + dbName); } } newSchema.getDatabases().remove(database); return newSchema; }
Source:
<code>public PagedFlux<SecretBase> listSecretVersions(String name) { return new PagedFlux<>(() -> listSecretVersionsFirstPage(name), <START> continuationToken -> listSecretsNextPage(continuationToken)); <END> }</code><technical_language>logging messages listSecretsNextPage consistent listSecretVersionsFirstPage</technical_language>

Target:
public PagedFlux<SecretBase> listSecretVersions(String name) { return new PagedFlux<>(() -> listSecretVersionsFirstPage(name), continuationToken -> listSecretVersionsNextPage(continuationToken)); }
Source:
<code>public void init(ComponentRegistry componentRegistry) { if (encodingClasses != null) { componentRegistry.wireDependencies(this); } <START> if (encodingClasses != null) { <END> componentRegistry.wireDependencies(this); } }</code><technical_language>wiring twice</technical_language>

Target:
public void init(ComponentRegistry componentRegistry) { if (encodingClasses != null) { componentRegistry.wireDependencies(this); } }
Source:
<code>public List<String> getAllTables(String dbname) throws MetaException, IOException { try { return getHive().getAllTables(dbname); } catch (TException e) { mHive = newHiveClient(); <START> return getHive().getAllTables(dbname); <END> } }</code><technical_language>instead of calling twice, a retry loop</technical_language>

Target:
public List<String> getAllTables(String dbname) throws TException, MetaException, IOException { return retryCall("getAllTables", () -> getHive().getAllTables(dbname)); }
Source:
<code>public void validate(GlobalConfiguration globalConfig) { Attribute<String> location = attributes.attribute(LOCATION); if (location.isNull() && !globalConfig.globalState().enabled()) { Log.CONFIG.storeLocationRequired(); <START> } <END> super.validate(globalConfig); }</code><technical_language>remove this error thrown startup PersistenceUtil#getLocation</technical_language>

Target:
public void validate(GlobalConfiguration globalConfig) { Attribute<String> location = attributes.attribute(LOCATION); if (location.isNull() && !globalConfig.globalState().enabled()) { throw Log.CONFIG.storeLocationRequired(); } super.validate(globalConfig); }
Source:
<code>public void run() { try { listener = new ServerSocket(port); while (true) { socket = listener.accept(); <START> outStr = new DataOutputStream(socket.getOutputStream()); <END> while (socket.getInputStream() .read() != -1) { testRunSession = new TestRunSessionAndPort(launch, project); outStr.writeInt(testRunSession.getPort()); } } } catch (SocketException se) { logger.logInfo("Connection to tester terminated", se); } catch (IOException e) { logger.logError("Error communicating to the tester", e); } close(); }</code><technical_language>out of this loop is throwing exception? poor flow control</technical_language>

Target:
public void run() { try { while (true) { socket = listener.accept(); outStr = new DataOutputStream(socket.getOutputStream()); while (socket.getInputStream() .read() != -1) { testRunSession = new TestRunSessionAndPort(launch, project); outStr.writeInt(testRunSession.getPort()); } } } catch (SocketException se) { logger.logInfo("Connection to tester terminated", se); } catch (IOException e) { logger.logError("Error communicating to the tester", e); } close(); }
Source:
<code>protected List<Object> getModelChildren() { <START> ArrayList<Object> <END> elements = new ArrayList<>(); elements.add(new InstanceName(getModel())); elements.addAll(getModel().getInterface().getAllInterfaceElements()); return elements; }</code><technical_language>List<Object></technical_language>

Target:
protected List<Object> getModelChildren() { List<Object> elements = new ArrayList<>(); elements.add(new InstanceName(getModel())); elements.addAll(getModel().getInterface().getAllInterfaceElements()); return elements; }
Source:
<code>public FormattingModel createModel(@NotNull PsiElement element, @NotNull CodeStyleSettings settings) { <START> if (settings.getIndentOptions() != null) { <END> settings.getIndentOptions().USE_TAB_CHARACTER = true; settings.getIndentOptions().SMART_TABS = false; } Block block = new GoFormattingBlock(element.getNode(), null, Indent.getNoneIndent(), null, settings, createSpacingBuilder(settings)); return FormattingModelProvider.createFormattingModelForPsiFile(element.getContainingFile(), block, settings); }</code><technical_language>GoLanguageCodeStyleSettingsProvider for setting default values</technical_language>

Target:
public FormattingModel createModel(@NotNull PsiElement element, @NotNull CodeStyleSettings settings) { Block block = new GoFormattingBlock(element.getNode(), null, Indent.getNoneIndent(), null, settings, createSpacingBuilder(settings)); return FormattingModelProvider.createFormattingModelForPsiFile(element.getContainingFile(), block, settings); }
Source:
<code>public int openDocument(ParcelFileDescriptor source) throws RemoteException { synchronized (mLock) { <START> while(mRenderer <END> != null) { try { mLock.wait(); } catch (InterruptedException e) { } } try { throwIfOpened(); if (DEBUG) { Log.i(LOG_TAG, "openDocument()"); } mEditor = new PdfEditor(source); return mEditor.getPageCount(); } catch (IOException | IllegalStateException e) { IoUtils.closeQuietly(source); Log.e(LOG_TAG, "Cannot open file", e); throw new RemoteException(e.toString()); } } }</code><technical_language>minor code style nit: missing a space '(' in line 87</technical_language>

Target:
public int openDocument(ParcelFileDescriptor source) throws RemoteException { synchronized (mLock) { while (mRenderer != null) { try { mLock.wait(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } try { throwIfOpened(); if (DEBUG) { Log.i(LOG_TAG, "openDocument()"); } mEditor = new PdfEditor(source); return mEditor.getPageCount(); } catch (IOException | IllegalStateException e) { IoUtils.closeQuietly(source); Log.e(LOG_TAG, "Cannot open file", e); throw new RemoteException(e.toString()); } } }
Source:
<code><START> public static MessageType getMessageType(String line) { <END> for (MessageType msgType : MessageType.values()) { if (line.startsWith(msgType.getMessageIndicator())) { return msgType; } } return null; }</code><technical_language>this MessageType getMessageType is more duplicate of message.getType() is this needed</technical_language>

Target:
private static MessageType getMessageType(String line) { for (MessageType msgType : MessageType.values()) { if (line.startsWith(msgType.name() + SEPARATOR)) { return msgType; } } return null; }
Source:
<code>public void testReconfigure() throws InterruptedException { RepositoryCache.register(db); assertTrue(RepositoryCache.isCached(db)); db.close(); assertTrue(RepositoryCache.isCached(db)); RepositoryCacheConfig config = new RepositoryCacheConfig(); config.setExpireAfter(1); config.setCleanupDelay(1); config.install(); <START> int t = 1; for (int i = 0; i <= 10; i++) { Thread.sleep(t); if (!RepositoryCache.isCached(db)) { return; } t = t * 2; } <END> fail("Repository should have been evicted from cache"); }</code><technical_language>instead for (int i = 0; i <= 10; i++) { Thread.sleep(1 << i); if (!RepositoryCache.isCached(db)) { return; } }</technical_language>

Target:
public void testReconfigure() throws InterruptedException { RepositoryCache.register(db); assertTrue(RepositoryCache.isCached(db)); db.close(); assertTrue(RepositoryCache.isCached(db)); RepositoryCacheConfig config = new RepositoryCacheConfig(); config.setExpireAfter(1); config.setCleanupDelay(1); config.install(); for (int i = 0; i <= 10; i++) { Thread.sleep(1 << i); if (!RepositoryCache.isCached(db)) { return; } } fail("Repository should have been evicted from cache"); }
Source:
<code>public String deleteExtensionMetadata(final String extensionName) throws StoreAccessException{ ExtensionType extensionType = AbstractExtension.isExtensionTrusted(extensionName) ? ExtensionType.TRUSTED : ExtensionType.CUSTOM; if (extensionType.toString().equalsIgnoreCase(ExtensionType.TRUSTED.toString())){ <START> throw new StoreAccessException(new Exception(extensionName + " is trusted cannot be deleted.")); <END> } if (metaStore.checkIfExtensionExists(extensionName)) { metaStore.deleteExtensionMetadata(extensionName); return "Deleted entry for:" + extensionName; }else { return "Extension:" + extensionName + " is not registered with falcon."; } }</code><technical_language>need create new Exception. create StoreAccessException</technical_language>

Target:
public String deleteExtensionMetadata(final String extensionName) throws ValidationException{ ExtensionType extensionType = AbstractExtension.isExtensionTrusted(extensionName) ? ExtensionType.TRUSTED : ExtensionType.CUSTOM; if (extensionType.equals(ExtensionType.TRUSTED)){ throw new ValidationException(extensionName + " is trusted cannot be deleted."); } if (metaStore.checkIfExtensionExists(extensionName)) { metaStore.deleteExtensionMetadata(extensionName); return "Deleted extension:" + extensionName; }else { return "Extension:" + extensionName + " is not registered with Falcon."; } }
Source:
<code>public void visitNode(Tree tree) { if (!hasSemantic()) { return; } <START> if (tree.is(SYNCHRONIZED_STATEMENT)) { <END> SynchronizedStatementTree synchronizedTree = (SynchronizedStatementTree) tree; if (synchronizedTree.expression().is(METHOD_INVOCATION)) { MethodInvocationTree synchronizedExpr = (MethodInvocationTree) synchronizedTree.expression(); if (GET_CLASS_MATCHER.matches(synchronizedExpr) && !isEnclosingClassFinal(synchronizedExpr.methodSelect())) { reportIssue(synchronizedExpr, "Synchronize on the static class name instead."); } } } }</code><technical_language>need for if</technical_language>

Target:
public void visitNode(Tree tree) { if (!hasSemantic()) { return; } SynchronizedStatementTree synchronizedTree = (SynchronizedStatementTree) tree; if (synchronizedTree.expression().is(METHOD_INVOCATION)) { MethodInvocationTree synchronizedExpr = (MethodInvocationTree) synchronizedTree.expression(); if (GET_CLASS_MATCHER.matches(synchronizedExpr) && !isEnclosingClassFinal(synchronizedExpr.methodSelect())) { reportIssue(synchronizedExpr, "Synchronize on the static class name instead."); } } }
Source:
<code>private void assertIndexMatchesVals(IndexedFloats indexed, float[] vals) { Assert.assertEquals(vals.length, indexed.size()); int[] indices = new int[vals.length]; for (int i = 0; i < indexed.size(); ++i) { Assert.assertEquals(vals[i], indexed.get(i), DELTA); indices[i] = i; } <START> IntArrays.shuffle(indices, new Random()); <END> final int limit = Math.min(indexed.size(), 1000); for (int i = 0; i < limit; ++i) { int k = indices[i]; Assert.assertEquals(vals[k], indexed.get(k), DELTA); } }</code><technical_language>ThreadLocalRandom.current(), other places</technical_language>

Target:
private void assertIndexMatchesVals(IndexedFloats indexed, float[] vals) { Assert.assertEquals(vals.length, indexed.size()); int[] indices = new int[vals.length]; for (int i = 0; i < indexed.size(); ++i) { Assert.assertEquals(vals[i], indexed.get(i), DELTA); indices[i] = i; } IntArrays.shuffle(indices, ThreadLocalRandom.current()); final int limit = Math.min(indexed.size(), 1000); for (int i = 0; i < limit; ++i) { int k = indices[i]; Assert.assertEquals(vals[k], indexed.get(k), DELTA); } }
Source:
<code>public void addParam(String key, String value) { if (parameters.containsKey(key)) { <START> throw new IllegalArgumentException(); <END> } if (hasParameterBefore) { builder.append("&"); } else { hasParameterBefore = true; } try { builder.append(key).append("=").append(URLEncoder.encode(value, "UTF-8")); } catch (UnsupportedEncodingException e) { throw rethrow(e); } parameters.put(key, value); }</code><technical_language>please add a proper exception message</technical_language>

Target:
public void addParam(String key, String value) { if (parameters.containsKey(key)) { throw new IllegalArgumentException("Parameter " + key + " is already added"); } if (hasParameterBefore) { builder.append("&"); } else { hasParameterBefore = true; } try { builder.append(key).append("=").append(URLEncoder.encode(value, "UTF-8")); } catch (UnsupportedEncodingException e) { throw rethrow(e); } parameters.put(key, value); }
Source:
<code>public void resumeFormEntry() { <START> saveResult = new MutableLiveData<>(null); <END> }</code><technical_language>In head this needs saveResult.setValue(null) instead. saving multiple times work for observations in onCreate of Activity/Fragment observing a LiveData value. reading this wrong! verify a test for ViewModel: java @Test public void resumeFormEntry_clearsSaveResult() { LiveData<FormSaveViewModel.SaveResult> saveResult = viewModel.getSavedResult(); viewModel.saveForm(Uri.parse("file://form"), true, "", false); viewModel.resumeFormEntry(); assertThat(saveResult.getValue(), equalTo(null)); }</technical_language>

Target:
public void resumeFormEntry() { saveResult.setValue(null); }
Source:
<code>private SortedPositionLinks(PositionLinks positionLinks, int[][] sortedPositionLinks, List<JoinFilterFunction> searchFunctions) { this.positionLinks = requireNonNull(positionLinks, "positionLinks is null"); this.sortedPositionLinks = requireNonNull(sortedPositionLinks, "sortedPositionLinks is null"); this.sizeInBytes = INSTANCE_SIZE + positionLinks.getSizeInBytes() + sizeOfPositionLinks(sortedPositionLinks); checkState(!searchFunctions.isEmpty(), "Using sortedPositionLinks with no search functions"); <START> this.searchFunctions = requireNonNull(searchFunctions, "searchFunctions is null"); <END> }</code><technical_language>rNN is ineffective, NPE preceding line</technical_language>

Target:
private SortedPositionLinks(PositionLinks positionLinks, int[][] sortedPositionLinks, List<JoinFilterFunction> searchFunctions) { this.positionLinks = requireNonNull(positionLinks, "positionLinks is null"); this.sortedPositionLinks = requireNonNull(sortedPositionLinks, "sortedPositionLinks is null"); this.sizeInBytes = INSTANCE_SIZE + positionLinks.getSizeInBytes() + sizeOfPositionLinks(sortedPositionLinks); requireNonNull(searchFunctions, "searchFunctions is null"); checkState(!searchFunctions.isEmpty(), "Using sortedPositionLinks with no search functions"); this.searchFunctions = searchFunctions.stream().toArray(JoinFilterFunction[]::new); }
Source:
<code>public void dropIndex(final String schemaName, String idxName, boolean ifExists) throws IgniteCheckedException{ String sql = H2Utils.indexDropSql(schemaName, idxName, ifExists); <START> GridH2Table tbl = dataTableForIndex(schemaName, idxName); <END> tbl.setRemoveIndexOnDestroy(true); connMgr.executeStatement(schemaName, sql); }</code><technical_language>assert tbl != null</technical_language>

Target:
public void dropIndex(final String schemaName, String idxName, boolean ifExists) throws IgniteCheckedException{ String sql = H2Utils.indexDropSql(schemaName, idxName, ifExists); GridH2Table tbl = dataTableForIndex(schemaName, idxName); assert tbl != null; tbl.setRemoveIndexOnDestroy(true); connMgr.executeStatement(schemaName, sql); }
Source:
<code>public Repo<Master> call(long tid, Master master) throws Exception { VolumeChooserEnvironment chooserEnv = new VolumeChooserEnvironment(tableInfo.tableId); <START> String baseDir = master.getFileSystem().choose(chooserEnv, ServerConstants.getBaseUris()) <END> + Constants.HDFS_TABLES_DIR + Path.SEPARATOR + tableInfo.tableId; tableInfo.dir = baseDir + Constants.DEFAULT_TABLET_LOCATION; if (tableInfo.initialSplitSize > 0) { createTableDirectoriesInfo(master, baseDir); } return new CreateDir(tableInfo); }</code><technical_language>this, I if volume chooser called for tablet. sure, need investigate. I this. a follow issue</technical_language>

Target:
public Repo<Master> call(long tid, Master master) throws Exception { VolumeChooserEnvironment chooserEnv = new VolumeChooserEnvironment(tableInfo.tableId); String baseDir = master.getFileSystem().choose(chooserEnv, ServerConstants.getBaseUris()) + Constants.HDFS_TABLES_DIR + Path.SEPARATOR + tableInfo.tableId; tableInfo.defaultTabletDir = baseDir + Constants.DEFAULT_TABLET_LOCATION; if (tableInfo.initialSplitSize > 0) { createTableDirectoriesInfo(master, baseDir); } return new CreateDir(tableInfo); }
Source:
<code>public boolean apply(Game game, Ability source) { Player controller = game.getPlayer(source.getControllerId()); <START> Player opponent = game.getPlayer(this.getTargetPointer().getFirst(game, source)); <END> if (opponent != null) { int xValue = opponent.getHand().size() - controller.getHand().size(); if (xValue > 0) { opponent.loseLife(xValue, game, false); } return true; } return false; }</code><technical_language>add a check controller != null</technical_language>

Target:
public boolean apply(Game game, Ability source) { Player controller = game.getPlayer(source.getControllerId()); Player opponent = game.getPlayer(this.getTargetPointer().getFirst(game, source)); if (controller != null && opponent != null) { int xValue = opponent.getHand().size() - controller.getHand().size(); if (xValue > 0) { opponent.loseLife(xValue, game, false); } return true; } return false; }
Source:
<code>public static double[] rgbToHSL(RGB rgb) { double r = rgb.red / <START> 255.D; <END> double g = rgb.green / 255.D; double b = rgb.blue / 255.D; double max = Math.max(Math.max(r, g), b); double min = Math.min(Math.min(r, g), b); double[] hsl = new double[] { 0, 0, (max + min) / 2 }; if (max != min) { double delta = max - min; if (hsl[2] <= 0.5) { hsl[1] = (delta / (max + min)); } else { hsl[1] = (delta / (2.0 - (max + min))); } if (r == max) { hsl[0] = (g - b) / delta; } else if (g == max) { hsl[0] = 2.0 + ((b - r) / delta); } else if (b == max) { hsl[0] = 4.0 + ((r - g) / delta); } hsl[0] *= 60.0; if (hsl[0] < 0.0) { hsl[0] += 360.0; } } return hsl; }</code><technical_language>extract a a constant MaxRGBValue</technical_language>

Target:
public static double[] rgbToHSL(RGB rgb) { double r = rgb.red / MAX_RGB_VALUE; double g = rgb.green / MAX_RGB_VALUE; double b = rgb.blue / MAX_RGB_VALUE; double max = Math.max(Math.max(r, g), b); double min = Math.min(Math.min(r, g), b); double[] hsl = new double[] { 0, 0, (max + min) / 2 }; if (max != min) { double delta = max - min; if (hsl[2] <= 0.5) { hsl[1] = (delta / (max + min)); } else { hsl[1] = (delta / (2.0 - (max + min))); } if (r == max) { hsl[0] = (g - b) / delta; } else if (g == max) { hsl[0] = 2.0 + ((b - r) / delta); } else if (b == max) { hsl[0] = 4.0 + ((r - g) / delta); } hsl[0] *= 60.0; if (hsl[0] < 0.0) { hsl[0] += 360.0; } } return hsl; }
Source:
<code>public static String appendIfNotEmpty(final String str, final String suffix) { <START> return isEmpty(str) ? EMPTY : str + defaultString(suffix); <END> }</code><technical_language>suggestion return isEmpty(str) ? str : str + defaultString(suffix);</technical_language>

Target:
public static String appendIfNotEmpty(final String str, final String suffix) { if (isEmpty(suffix) || isEmpty(str)) { return str; } return str + suffix; }
Source:
<code>protected PatternBasedElementProcessor newProcessor() { return new PatternBasedElementProcessor() { @Override public void emit() { Attributes attributes = new Attributes(); SpanType span = SpanType.SPAN; String cssClass = group(1); if (cssClass != null && !cssClass.isEmpty()) { attributes.setCssClass(cssClass); } else { <START> span = SpanType.HIGHLIGHT; <END> } getBuilder().beginSpan(span, attributes); getBuilder().characters(group(2)); getBuilder().endSpan(); } }; }</code><technical_language>highlight default? Is normal behaviour for AsciiDoc</technical_language>

Target:
protected PatternBasedElementProcessor newProcessor() { return new PatternBasedElementProcessor() { @Override public void emit() { Attributes attributes = new Attributes(); SpanType span = SpanType.SPAN; String cssClass = group(1); if (cssClass != null && !cssClass.isEmpty()) { attributes.setCssClass(cssClass); } else { span = SpanType.MARK; } getBuilder().beginSpan(span, attributes); getBuilder().characters(group(2)); getBuilder().endSpan(); } }; }
Source:
<code><START> private boolean isAffectedBy(IResourceDelta delta) { <END> if (delta.getKind() != IResourceDelta.CHANGED) return true; int flags = delta.getFlags(); if (flags != 0 && flags != IResourceDelta.MARKERS) return true; IResourceDelta[] children = delta.getAffectedChildren(); for (IResourceDelta child : children) { if (isAffectedBy(child)) return true; } return false; }</code><technical_language>Please consider reimplementing this <LINK_0> Please curly braces</technical_language>

Target:
private boolean isAffectedBy(IResourceDelta delta) { boolean[] result = new boolean[] { false }; try { delta.accept(d -> { if (result[0]) { return false; } if (d.getKind() != IResourceDelta.CHANGED) { result[0] = true; return false; } int flags = d.getFlags(); if (flags != 0 && flags != IResourceDelta.MARKERS) { result[0] = true; return false; } return true; }); } catch (CoreException e) { } return result[0]; }
Source:
<code>public String any() { <START> String[] relationships = new String[] {"direct", "extended", "in_law", "spouse", <END> "parent", "sibling"}; int idx = faker.random().nextInt(relationships.length); String methodName = relationships[idx]; try { Method m = Relationships.class.getMethod(methodName); Relationships relInstance = new Relationships(faker); return (String)m.invoke(relInstance); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } return null; }</code><technical_language>get a list of declaredMethods exclude any? instead defining list of method names</technical_language>

Target:
public String any() { Method currentMethod = Relationships.class.getClass().getEnclosingMethod(); try { Method[] methods = Relationships.class.getDeclaredMethods(); methods = ArrayUtils.removeElement(methods, currentMethod); int indx = faker.random().nextInt(methods.length); Method runMethod = methods[indx]; Relationships relationships = new Relationships(faker); return (String)runMethod.invoke(relationships); } catch (SecurityException e) { throw new RuntimeException("SecurityException: " + e.getMessage()); } catch (IllegalArgumentException e) { throw new RuntimeException("IllegalArgumentException: " + e.getMessage()); } catch (IllegalAccessException e) { throw new RuntimeException("IllegalAccessException: " + e.getMessage()); } catch (InvocationTargetException e) { throw new RuntimeException("InvocationTargetException: " + e.getMessage()); } }
Source:
<code>public boolean isVerbose() { Logger log = Logger.getLogger("com.google.devtools.j2objc"); return log != null && log.getLevel() != null && log.getLevel().equals(Level.FINEST); <START> } <END></code><technical_language>easier test for null is reverse equals, constant non-null: return log != null && Level.FINEST.equals(log.getLevel());</technical_language>

Target:
public boolean isVerbose() { Logger log = Logger.getLogger("com.google.devtools.j2objc"); return log != null && Level.FINEST.equals(log.getLevel()); }