auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public byte[] decompress(byte[] buf, CodecOptions options) throws FormatException { initialize(); byte[] uncompressed = service.decompress(buf); if (options.interleaved) { return uncompressed; } int bpp = options.bitsPerSample / 8; int pixels = options.width * options.height; int c = uncompressed.length / (pixels * bpp); if (c == 1) { return uncompressed; } byte[] deinterleaved = new byte[uncompressed.length]; for (int p=0; p<pixels; p++) { <START> for (int channel=0; channel<c; channel++) { <END> for (int b=0; b<bpp; b++) { int bb = options.littleEndian ? b : bpp - b - 1; deinterleaved[bpp * (channel * pixels + p) + bb] = uncompressed[bpp * (p * c + channel) + b]; } } } return deinterleaved; }</code><technical_language>a minor nitpick reading calculations initial thinking assume channel total c index, similar pixels bpp loops. wrong is readability nicer swap variables eg: for (int c=0; c<channels; c++) {</technical_language>

Target:
public byte[] decompress(byte[] buf, CodecOptions options) throws FormatException { initialize(); byte[] uncompressed = service.decompress(buf); if (options.interleaved) { return uncompressed; } int bpp = options.bitsPerSample / 8; int pixels = options.width * options.height; int channels = uncompressed.length / (pixels * bpp); if (channels == 1) { return uncompressed; } byte[] deinterleaved = new byte[uncompressed.length]; for (int p=0; p<pixels; p++) { for (int c=0; c<channels; c++) { for (int b=0; b<bpp; b++) { int bb = options.littleEndian ? b : bpp - b - 1; deinterleaved[bpp * (c * pixels + p) + bb] = uncompressed[bpp * (p * channels + c) + b]; } } } return deinterleaved; }
Source:
<code>private void loadCachedSettings() { Cursor localSettings = SiteSettingsTable.getSettings(mSite.getId()); if (localSettings != null && localSettings.getCount() > 0) { mSettings.isInLocalTable = true; Map<Integer, CategoryModel> cachedModels = SiteSettingsTable.getAllCategories(); mSettings.deserializeOptionsDatabaseCursor(localSettings, cachedModels); mSettings.language = languageIdToLanguageCode(Integer.toString(mSettings.languageId)); if (mSettings.language == null) { setLanguageCode(LanguageUtils.getPatchedCurrentDeviceLanguage(null)); } mRemoteSettings.language = mSettings.language; mRemoteSettings.languageId = mSettings.languageId; mRemoteSettings.optimizedImage = mSettings.optimizedImage; mRemoteSettings.maxImageWidth = mSettings.maxImageWidth; mRemoteSettings.imageQualitySetting = mSettings.imageQualitySetting; notifyUpdatedOnUiThread(null); } else { mSettings.isInLocalTable = false; mSettings.localTableId = mSite.getId(); setAddress(mSite.getUrl()); setUsername(mSite.getUsername()); setPassword(mSite.getPassword()); setTitle(mSite.getName()); } if (!SiteUtils.isAccessibleViaWPComAPI(mSite)) { setUsername(mSite.getUsername()); setPassword(mSite.getPassword()); } <START> localSettings.close(); <END> }</code><technical_language>for localSettings null here</technical_language>

Target:
private void loadCachedSettings() { Cursor localSettings = SiteSettingsTable.getSettings(mSite.getId()); if (localSettings != null && localSettings.getCount() > 0) { mSettings.isInLocalTable = true; Map<Integer, CategoryModel> cachedModels = SiteSettingsTable.getAllCategories(); mSettings.deserializeOptionsDatabaseCursor(localSettings, cachedModels); mSettings.language = languageIdToLanguageCode(Integer.toString(mSettings.languageId)); if (mSettings.language == null) { setLanguageCode(LanguageUtils.getPatchedCurrentDeviceLanguage(null)); } mRemoteSettings.language = mSettings.language; mRemoteSettings.languageId = mSettings.languageId; mRemoteSettings.optimizedImage = mSettings.optimizedImage; mRemoteSettings.maxImageWidth = mSettings.maxImageWidth; mRemoteSettings.imageQualitySetting = mSettings.imageQualitySetting; notifyUpdatedOnUiThread(null); } else { mSettings.isInLocalTable = false; mSettings.localTableId = mSite.getId(); setAddress(mSite.getUrl()); setUsername(mSite.getUsername()); setPassword(mSite.getPassword()); setTitle(mSite.getName()); } if (!SiteUtils.isAccessibleViaWPComAPI(mSite)) { setUsername(mSite.getUsername()); setPassword(mSite.getPassword()); } if (localSettings != null) { localSettings.close(); } }
Source:
<code>protected boolean canDoAction() { boolean toReturn = false; if (VdcActionType.RecoveryStoragePool.equals(getActionType()) && !IrsBrokerCommand.tryLockIrsProxyData(getStoragePool().getId())) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_POOL_DURING_RECONSTRUCT); } else { if (!IrsBrokerCommand.lockIrsProxyData(getStoragePool().getId())) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_POOL_NOT_EXIST); } } try { <START> toReturn = performChecks(); <END> } catch (Exception e) { toReturn = false; } finally { if (!toReturn) { IrsBrokerCommand.unLockIrsProxyData(getStoragePool().getId()); } } return toReturn; }</code><technical_language>instead of this toReturn business, not: if !performChecks() { throw ... } catch (Exception e) { IrsBrokerCommand... return false; } return true;</technical_language>

Target:
protected boolean canDoAction() { if (this.getActionType() == VdcActionType.RecoveryStoragePool || VdcActionType.ForceRemoveStorageDomain.equals(getParameters().getParentCommand())) { if (!IrsBrokerCommand.lockIrsProxyData(getStoragePool().getId())) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_POOL_NOT_EXIST); } } else { if (!IrsBrokerCommand.tryLockIrsProxyData(getStoragePool().getId())){ return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_POOL_DURING_RECONSTRUCT); } } boolean toReturn = false; try { toReturn = performCanDoActionChecks(); } finally { if (!toReturn) { IrsBrokerCommand.unLockIrsProxyData(getStoragePool().getId()); } } return toReturn; }
Source:
<code>private String generateSanitizedFilename(@Nullable String name) { String filename; if (StringUtil.isEmpty(name)) { filename = DEFAULT_SURVEY_FILE_NAME; } else { <START> filename = name.replaceAll(FILENAME_REGEX, FILENAME_REPLACEMENT); <END> int maxLength = Math.min(FILENAME_MAX_SIZE, filename.length()); filename = filename.substring(0, maxLength); } return filename; }</code><technical_language>thinking this I some errors I a form name spaces "/" e.g Form / slash Form with/back slash worked device. add another replaceAll() replace patterns Form_with___back_slash</technical_language>

Target:
private String generateSanitizedFilename(@Nullable String name) { String filename; if (StringUtil.isEmpty(name)) { filename = DEFAULT_SURVEY_FILE_NAME; } else { filename = name.trim().replaceAll(FILENAME_REGEX, FILENAME_REPLACEMENT); int maxLength = Math.min(FILENAME_MAX_SIZE, filename.length()); filename = filename.substring(0, maxLength); filename = filename.replaceAll(EXCESS_UNDERSCORE, FILENAME_REPLACEMENT); } return filename; }
Source:
<code>public static <T extends Enum<T>> T getEnumStringPref(SharedPreferences prefs, String key, T defaultEnum) { String stringPref = prefs.getString(key, defaultEnum.name()); try { return Enum.valueOf(defaultEnum.getDeclaringClass(), stringPref); <START> } catch (Exception ex) { <END> Log.w(K9.LOG_TAG, "Unable to convert preference key [" + key + "] value [" + stringPref + "] to enum of type " + defaultEnum.getDeclaringClass(), ex); return defaultEnum; } }</code><technical_language>catch IllegalArgumentException</technical_language>

Target:
public static <T extends Enum<T>> T getEnumStringPref(SharedPreferences prefs, String key, T defaultEnum) { String stringPref = prefs.getString(key, defaultEnum.name()); if (null == stringPref) { return defaultEnum; } else { try { return Enum.valueOf(defaultEnum.getDeclaringClass(), stringPref); } catch (IllegalArgumentException ex) { Log.w(K9.LOG_TAG, "Unable to convert preference key [" + key + "] value [" + stringPref + "] to enum of type " + defaultEnum.getDeclaringClass(), ex); return defaultEnum; } } }
Source:
<code>default void generate(Random random, int chunkX, int chunkZ, World world, IChunkGenerator chunkGenerator, IChunkProvider chunkProvider) { <START> for (int y = 0; y <= Cube.SIZE; y++) { <END> CubePos pos = new CubePos(chunkX, y, chunkZ); CubicBiome biome = CubicBiome.getCubic(world.getBiome(pos.getCenterBlockPos())); generate((ICubicWorld) world, random, pos, biome); } }</code><technical_language>This 16 is unrelated cube size. This is vanilla chunk height. Populator pregenerate cubes default world generators do a job</technical_language>

Target:
default void generate(Random random, int chunkX, int chunkZ, World world, IChunkGenerator chunkGenerator, IChunkProvider chunkProvider) { for (int y = 0; y <= 16; y++) { CubePos pos = new CubePos(chunkX, y, chunkZ); CubicBiome biome = CubicBiome.getCubic(world.getBiome(pos.getCenterBlockPos())); generate((ICubicWorld) world, random, pos, biome); } }
Source:
<code>public static RcFileTester fullTestRcFileReader() { RcFileTester rcFileTester = new RcFileTester(); rcFileTester.structTestsEnabled = true; rcFileTester.mapTestsEnabled = true; rcFileTester.listTestsEnabled = true; rcFileTester.complexStructuralTestsEnabled = true; rcFileTester.readLastBatchOnlyEnabled = true; rcFileTester.formats = ImmutableSet.copyOf(Format.values()); <START> rcFileTester.compressions = ImmutableSet.of(NONE, ZLIB, BZIP2); <END> return rcFileTester; }</code><technical_language>leave LZ4 is a native Java compressor</technical_language>

Target:
public static RcFileTester fullTestRcFileReader() { RcFileTester rcFileTester = new RcFileTester(); rcFileTester.structTestsEnabled = true; rcFileTester.mapTestsEnabled = true; rcFileTester.listTestsEnabled = true; rcFileTester.complexStructuralTestsEnabled = true; rcFileTester.readLastBatchOnlyEnabled = true; rcFileTester.formats = ImmutableSet.copyOf(Format.values()); rcFileTester.compressions = ImmutableSet.of(NONE, LZ4, ZLIB, BZIP2); return rcFileTester; }
Source:
<code>public InputStream getInputStream() { <START> return null; <END> }</code><technical_language>suggesting creating Response input stream this simple return</technical_language>

Target:
public InputStream getInputStream() { return responseInputStream; }
Source:
<code>private void ensureSignatureBitmap() { if (mSignatureBitmap == null) { mSignatureBitmap = Bitmap.createBitmap(getWidth(), getHeight(), <START> Bitmap.Config.RGB_565 ); <END> mSignatureBitmapCanvas = new Canvas(mSignatureBitmap); } }</code><technical_language>this? In case generated bitmap alpha channel sacrifice transparency</technical_language>

Target:
private void ensureSignatureBitmap() { if (mSignatureBitmap == null) { Runtime runtime = Runtime.getRuntime(); int width = getWidth(); int height = getHeight(); long requiredMemory = width * height * 16; long memoryAvailable = (runtime.maxMemory() - runtime.totalMemory() + runtime.freeMemory()); if(requiredMemory > memoryAvailable){ runtime.gc(); try { Thread.sleep(100); } catch (InterruptedException e){ Log.e("SignaturePadError","Failed to sleep", e); } } mSignatureBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565); mSignatureBitmapCanvas = new Canvas(mSignatureBitmap); } }
Source:
<code>public void testAnnotationProcessor() throws Exception { Verifier verifier = getVerifier("TYCHO590annotationProcessing", false); <START> verifier.executeGoal("install"); <END> verifier.verifyErrorFreeLog(); }</code><technical_language>this fail "No tests executed!" error</technical_language>

Target:
public void testAnnotationProcessor() throws Exception { Verifier verifier = getVerifier("TYCHO590annotationProcessing", false); verifier.executeGoal("install"); verifier.verifyErrorFreeLog(); File annotatedProjectTargetDir = new File(verifier.getBasedir(), "annotated-project/target"); File generatedSource = new File(annotatedProjectTargetDir, "generated-sources/annotations/tycho590/processed/Processor.java"); assertTrue(generatedSource.isFile()); File classFile = new File(annotatedProjectTargetDir, "classes/tycho590/processed/Processor.class"); assertTrue(classFile.isFile()); }
Source:
<code>public void testRemoveValueEqualStoreEntryCacheAccessExceptionEqualCacheWriterEntry() throws Exception { final MockStore realStore = new MockStore(Collections.singletonMap("key", "value")); this.store = spy(realStore); doThrow(new CacheAccessException("")).when(this.store).computeIfPresent(eq("key"), getAnyBiFunction()); final MockCacheWriter realCache = new MockCacheWriter(Collections.singletonMap("key", "value")); this.cacheWriter = spy(realCache); final Ehcache<String, String> ehcache = this.getEhcache(this.cacheWriter); assertFalse(ehcache.remove("key", "value")); verify(this.store).computeIfPresent(eq("key"), getAnyBiFunction()); verify(this.spiedResilienceStrategy) .removeFailure(eq("key"), eq("value"), any(CacheAccessException.class), eq(false)); <START> assertThat(realCache.getEntries().containsKey("key"), is(true)); END> validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.RemoveOutcome.FAILURE)); }</code><technical_language>is depend resilience strategy ... hard say. I drop operation result assertion though</technical_language>

Target:
public void testRemoveValueEqualStoreEntryCacheAccessExceptionEqualCacheWriterEntry() throws Exception { final FakeStore fakeStore = new FakeStore(Collections.singletonMap("key", "value")); this.store = spy(fakeStore); doThrow(new CacheAccessException("")).when(this.store).computeIfPresent(eq("key"), getAnyBiFunction()); final FakeCacheWriter fakeWriter = new FakeCacheWriter(Collections.singletonMap("key", "value")); this.cacheWriter = spy(fakeWriter); final Ehcache<String, String> ehcache = this.getEhcache(this.cacheWriter); ehcache.remove("key", "value"); verify(this.store).computeIfPresent(eq("key"), getAnyBiFunction()); verify(this.spiedResilienceStrategy) .removeFailure(eq("key"), eq("value"), any(CacheAccessException.class), eq(false)); assertThat(fakeWriter.getEntryMap().containsKey("key"), is(true)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.RemoveOutcome.FAILURE)); }
Source:
<code>private static CalculationTaskConfig createTaskConfig( int rowIndex, int columnIndex, CalculationTarget target, Column column) { PricingRules pricingRules = column.getPricingRules(); <START> Optional<ConfiguredFunctionGroup> functionGroup = pricingRules.functionGroup(target, column.getMeasure(target)); <END> FunctionConfig<?> functionConfig = functionGroup .map(group -> functionConfig(group, target, column)) .orElse(FunctionConfig.defaultFunction()); Map<String, Object> functionArguments = functionGroup .map(ConfiguredFunctionGroup::getArguments) .orElse(ImmutableMap.of()); MarketDataMappings marketDataMappings = column.getMarketDataRules().mappings(target) .orElse(NoMatchingRuleMappings.INSTANCE); return CalculationTaskConfig.of( target, rowIndex, columnIndex, functionConfig, functionArguments, marketDataMappings, column.getReportingRules()); }</code><technical_language>Clearer assign column.getMeasure(target) a local variable leave pricing rules inlined</technical_language>

Target:
private static CalculationTaskConfig createTaskConfig( int rowIndex, int columnIndex, CalculationTarget target, Column column) { PricingRules pricingRules = column.getPricingRules(); Measure measure = column.getMeasure(target); Optional<ConfiguredFunctionGroup> functionGroup = pricingRules.functionGroup(target, measure); FunctionConfig<?> functionConfig = functionGroup .map(group -> functionConfig(group, target, column)) .orElse(FunctionConfig.missing()); Map<String, Object> functionArguments = functionGroup .map(ConfiguredFunctionGroup::getArguments) .orElse(ImmutableMap.of()); MarketDataMappings marketDataMappings = column.getMarketDataRules().mappings(target) .orElse(NoMatchingRuleMappings.INSTANCE); return CalculationTaskConfig.of( target, rowIndex, columnIndex, functionConfig, functionArguments, marketDataMappings, column.getReportingRules()); }
Source:
<code>private boolean isISOCompatible( File iso, RpmVersion ovirtHostOsVersion ) { boolean ret = false; log.debugFormat("Check if ISO compatible: {0}", iso); for (OVirtNodeInfo.Entry info : OVirtNodeInfo.getInstance().get()) { if (info.path.equals(iso.getParentFile())) { try { Matcher matcher = info.isoPattern.matcher( <START> iso.getCanonicalPath().substring(iso.getCanonicalPath().lastIndexOf("/")+1) <END> ); if (matcher.find()) { String rpmLike = matcher.group(1).replaceAll("-", "."); log.debugFormat("ISO version: {0} {1} {2}", iso, rpmLike, ovirtHostOsVersion); RpmVersion isoVersion = new RpmVersion(rpmLike, "", true); if (VdsHandler.isIsoVersionCompatibleForUpgrade(ovirtHostOsVersion, isoVersion)) { log.debugFormat("ISO compatible: {0}", iso); ret = true; break; } } } catch (IOException e) { log.errorFormat( "Cannot get canonical path to {0} with error {1}", iso.getName(), ExceptionUtils.getMessage(e) ); } } } return ret; }</code><technical_language>if need file name.. be: getCanonicalFile().getName() please avoid parsing</technical_language>

Target:
private boolean isISOCompatible( File iso, RpmVersion ovirtHostOsVersion ) { boolean ret = false; log.debugFormat("Check if ISO compatible: {0}", iso); for (OVirtNodeInfo.Entry info : OVirtNodeInfo.getInstance().get()) { if (info.path.equals(iso.getParentFile())) { try { Matcher matcher = info.isoPattern.matcher( iso.getCanonicalFile().getName() ); if (matcher.find()) { String rpmLike = matcher.group(1).replaceAll("-", "."); log.debugFormat("ISO version: {0} {1} {2}", iso, rpmLike, ovirtHostOsVersion); RpmVersion isoVersion = new RpmVersion(rpmLike, "", true); if (VdsHandler.isIsoVersionCompatibleForUpgrade(ovirtHostOsVersion, isoVersion)) { log.debugFormat("ISO compatible: {0}", iso); ret = true; break; } } } catch (IOException e) { log.errorFormat( "Cannot get canonical path to {0} with error {1}", iso.getName(), ExceptionUtils.getMessage(e) ); } } } return ret; }
Source:
<code>private Either<Acknowledge, Throwable> submitNoOpInvokableTask( AllocationID allocationId, TestingJobMasterGateway jobMasterGateway, TaskExecutorGateway tmGateway) throws IOException { final TaskDeploymentDescriptor tdd = TaskDeploymentDescriptorBuilder .newBuilder(jobId, NoOpInvokable.class) .setAllocationId(allocationId) .build(); try { return Either.Left(tmGateway.submitTask(tdd, jobMasterGateway.getFencingToken(), timeout).join()); } catch (CompletionException e) { <START> return Either.Right(e.getCause()); <END> } }</code><technical_language>bubble up, possibly enriching it? assertThrows for checking exception</technical_language>

Target:
private void submitNoOpInvokableTask( AllocationID allocationId, TestingJobMasterGateway jobMasterGateway, TaskExecutorGateway tmGateway) throws IOException { final TaskDeploymentDescriptor tdd = TaskDeploymentDescriptorBuilder .newBuilder(jobId, NoOpInvokable.class) .setAllocationId(allocationId) .build(); tmGateway.submitTask(tdd, jobMasterGateway.getFencingToken(), timeout).join(); }
Source:
<code>public boolean process(final ZigBeeApi zigbeeApi, final String[] args) { if (args.length != 2) { return false; } final Device device = getDeviceByIndexOrEndpointId(zigbeeApi, args[1]); if (device == null) { return false; } print("Network Address : " + device.getNetworkAddress()); print("Extended Address : " + device.getIeeeAddress()); print("Endpoint Address : " + device.getEndPointAddress()); print("Device Profile : " + ZigBeeApiConstants.getProfileName(device.getProfileId())+ String.format(" (0x%04X)", device.getProfileId())); print("Device Category : " + ZigBeeApiConstants.getCategoryDeviceName(device.getProfileId(), device.getDeviceTypeId())); print("Device Type : " + device.getDeviceType() + String.format(" (0x%04X)", device.getDeviceTypeId())); print("Device Version : " + device.getDeviceVersion()); print("Implementation : " + device.getClass().getName()); print("Input Clusters : "); <START> showClusters(device, true); <END> print("Output Clusters : "); showClusters(device, false); return true; }</code><technical_language>If change this, a implementation pass in cluster list (ie input output clusters) a true/false</technical_language>

Target:
public boolean process(final ZigBeeApi zigbeeApi, final String[] args) { if (args.length != 2) { return false; } final Device device = getDeviceByIndexOrEndpointId(zigbeeApi, args[1]); if (device == null) { return false; } print("Network Address : " + device.getNetworkAddress()); print("Extended Address : " + device.getIeeeAddress()); print("Endpoint Address : " + device.getEndPointAddress()); print("Device Profile : " + ZigBeeApiConstants.getProfileName(device.getProfileId())+ String.format(" (0x%04X)", device.getProfileId())); print("Device Category : " + ZigBeeApiConstants.getCategoryDeviceName(device.getProfileId(), device.getDeviceTypeId())); print("Device Type : " + device.getDeviceType() + String.format(" (0x%04X)", device.getDeviceTypeId())); print("Device Version : " + device.getDeviceVersion()); print("Implementation : " + device.getClass().getName()); print("Input Clusters : "); showClusters(device, device.getInputClusters()); print("Output Clusters : "); showClusters(device, device.getOutputClusters()); return true; }
Source:
<code>public int mapTagsPosition(int position) { if (this.tagsPositionMap != null) { if (position < this.tagsPositionMap.length) { return this.tagsPositionMap[position]; <START> } else { <END> return this.tags.length(); } } else { if (position < this.tags.length()) { return position; } else { return this.tags.length(); } } }</code><technical_language>need for else if return in previous if</technical_language>

Target:
public int mapTagsPosition(int position) { if (this.tagsPositionMap != null) { if (position < this.tagsPositionMap.length) { return this.tagsPositionMap[position]; } return this.tags.length(); } else { if (position < this.tags.length()) { return position; } return this.tags.length(); } }
Source:
<code>public void actionPerformed(ActionEvent e) { String content = etc.getEditorContent(); File file = etc.getCurrentFile(); if (file == null) file = FileChooserService.getSelectedFile("tex", "TeX files", DialogType.SAVE, true); <START> file = SaveConfirmDialog.confirmFileSave(JOptionPane.NO_OPTION, file, etc.getCurrentFile()); <END> if (file != null) { FileService.writeToFile(file.getAbsolutePath(), content); LOGGER.log("Saving file " + file.getAbsolutePath()); etc.setCurrentFile(file); } }</code><technical_language>I call "getSelectedFile" additionaly "confirmFileSave". a method merges logic of above? named "getFileWithConfirmation"</technical_language>

Target:
public void actionPerformed(ActionEvent e) { String content = etc.getEditorContent(); File file = FileChooserService.getFileWithConfirmation(etc.getCurrentFile(), "tex", "TeX files", DialogType.SAVE, true); if (file != null) { FileService.writeToFile(file.getAbsolutePath(), content); LOGGER.log("Saving file " + file.getAbsolutePath()); etc.setCurrentFile(file); } }
Source:
<code>public CassandraTemplate(Session session, CassandraConverter converter) { setSession(session); <START> setConverter(converter == null ? getDefaultCassandraConverter() : converter); <END> }</code><technical_language>a big deal, I generally a positive perspective (i.e. innocent proven guilty ;-), as... setConverter(converter != null ? converter : getDefaultCassandraConverter());</technical_language>

Target:
public CassandraTemplate(Session session, CassandraConverter converter) { setSession(session); setConverter(converter != null ? converter : getDefaultCassandraConverter()); }
Source:
<code>protected Object createSchemaDefaultValue(Type type, Field field, Schema fieldSchema) { Object defaultValue; if (defaultGenerated) { defaultValue = getOrCreateDefaultValue(type, field); if (defaultValue != null) { <START> return defaultValue; <END> } } AvroDefault defaultAnnotation = field.getAnnotation(AvroDefault.class); defaultValue = (defaultAnnotation == null) ? null : Schema.parseJsonToObject(defaultAnnotation.value()); if (defaultValue == null && fieldSchema.getType() == Schema.Type.UNION) { Schema defaultType = fieldSchema.getTypes().get(0); if (defaultType.getType() == Schema.Type.NULL) { defaultValue = JsonProperties.NULL_VALUE; } } return defaultValue; }</code><technical_language>instead return deepCopy(fieldSchema, defaultValue)</technical_language>

Target:
protected Object createSchemaDefaultValue(Type type, Field field, Schema fieldSchema) { Object defaultValue; if (defaultGenerated) { defaultValue = getOrCreateDefaultValue(type, field); if (defaultValue != null) { return deepCopy(fieldSchema, defaultValue); } } AvroDefault defaultAnnotation = field.getAnnotation(AvroDefault.class); defaultValue = (defaultAnnotation == null) ? null : Schema.parseJsonToObject(defaultAnnotation.value()); if (defaultValue == null && fieldSchema.getType() == Schema.Type.UNION) { Schema defaultType = fieldSchema.getTypes().get(0); if (defaultType.getType() == Schema.Type.NULL) { defaultValue = JsonProperties.NULL_VALUE; } } return defaultValue; }
Source:
<code>public void countDistinctByFirstname() { Person p = new Person(); p.setId("2020"); p.setFirstname("Sachin"); p.setLastname("Tendulkar"); this.personMap.put("1001", p); this.personMap.put("1002", p); <START> final Long distinctPersons = this.personRepository.countDistinctByFirstname("Sachin"); <END> assertThat( distinctPersons, equalTo(1L)); this.personMap.remove("1001"); this.personMap.remove("1002"); }</code><technical_language>good a test case proving a duplicate(here in other cases, for sanity): suggestion final Long persons = this.personRepository.countByFirstname("Sachin"); assertThat(persons, equalTo(2L)); final Long distinctPersons = this.personRepository.countDistinctByFirstname("Sachin");</technical_language>

Target:
public void countDistinctByFirstname() { Person p = new Person(); p.setId("2020"); p.setFirstname("Sachin"); p.setLastname("Tendulkar"); this.personMap.put("1001", p); this.personMap.put("1002", p); final Long persons = this.personRepository.countByFirstname("Sachin"); assertThat( persons, equalTo(2L)); final Long distinctPersons = this.personRepository.countDistinctByFirstname("Sachin"); assertThat( distinctPersons, equalTo(1L)); this.personMap.remove("1001"); this.personMap.remove("1002"); }
Source:
<code>void onGenerate(Consumer<AutomationConfiguration> callback) { <START> generateScriptButton.addActionListener(__ -> callback.accept(automationConfiguration)); <END> }</code><technical_language>Remove automationConfiguration member of this class create a new AutomationConfiguration object action listener current of UI fields</technical_language>

Target:
void onGenerate(Consumer<AutomationConfiguration> callback) { generateScriptButton.addActionListener(__ -> { AutomationConfiguration automationConfiguration = new AutomationConfiguration( Optional.ofNullable(Paths.get(scriptDirField.getText())), exportConfiguration ); callback.accept(automationConfiguration); }); }
Source:
<code>public static Object normalizeType(Object value, ConfigDescriptionParameter configDescriptionParameter) { if (configDescriptionParameter != null) { Normalizer normalizer = NormalizerFactory.getNormalizer(configDescriptionParameter); return normalizer.normalize(value); } else if (value == null || value instanceof Boolean || value instanceof String || value instanceof BigDecimal) { return value; } else if (value instanceof Number) { return new BigDecimal(value.toString()); } else if (value instanceof Collection) { <START> return normalizeCollection((List) value); <END> } throw new IllegalArgumentException( "Invalid type '{" + value.getClass().getCanonicalName() + "}' of configuration value!"); }</code><technical_language>If check for Collection work collection interface (and create a new list) instead of rely collection a list this place (if is case, instanceof List</technical_language>

Target:
public static Object normalizeType(Object value, ConfigDescriptionParameter configDescriptionParameter) { if (configDescriptionParameter != null) { Normalizer normalizer = NormalizerFactory.getNormalizer(configDescriptionParameter); return normalizer.normalize(value); } else if (value == null || value instanceof Boolean || value instanceof String || value instanceof BigDecimal) { return value; } else if (value instanceof Number) { return new BigDecimal(value.toString()); } else if (value instanceof Collection) { return normalizeCollection((Collection) value); } throw new IllegalArgumentException( "Invalid type '{" + value.getClass().getCanonicalName() + "}' of configuration value!"); }
Source:
<code>PendingReadOp(LedgerHandle lh, ScheduledExecutorService scheduler, long startEntryId, long endEntryId, boolean isRecoveryRead) { this.seq = new ArrayList<>((int) ((endEntryId + 1) - startEntryId)); this.future = new CompletableFuture<>(); this.lh = lh; this.startEntryId = startEntryId; this.endEntryId = endEntryId; this.scheduler = scheduler; this.isRecoveryRead = isRecoveryRead; numPendingEntries = endEntryId - startEntryId + 1; maxMissedReadsAllowed = getLedgerMetadata().getWriteQuorumSize() - getLedgerMetadata().getAckQuorumSize(); heardFromHosts = new HashSet<>(); heardFromHostsBitSet = new BitSet(getLedgerMetadata().getEnsembleSize()); readOpLogger = lh.bk.getReadOpLogger(); <START> speculativeReadCounter = lh.bk.speculativeReadCounter; <END> }</code><technical_language>a getter, simplifies mocking</technical_language>

Target:
PendingReadOp(LedgerHandle lh, ScheduledExecutorService scheduler, long startEntryId, long endEntryId, boolean isRecoveryRead) { this.seq = new ArrayList<>((int) ((endEntryId + 1) - startEntryId)); this.future = new CompletableFuture<>(); this.lh = lh; this.startEntryId = startEntryId; this.endEntryId = endEntryId; this.scheduler = scheduler; this.isRecoveryRead = isRecoveryRead; numPendingEntries = endEntryId - startEntryId + 1; maxMissedReadsAllowed = getLedgerMetadata().getWriteQuorumSize() - getLedgerMetadata().getAckQuorumSize(); heardFromHosts = new HashSet<>(); heardFromHostsBitSet = new BitSet(getLedgerMetadata().getEnsembleSize()); readOpLogger = lh.bk.getReadOpLogger(); speculativeReadCounter = lh.bk.getSpeculativeReadCounter(); }
Source:
<code>public JobHandle scheduleJob(Job job, JobContext ctx, Trigger trigger) { Date date = trigger.hasNextFireTime(); if ( date != null ) { <START> String jobname = QuartzNameHelper.getJobName(ctx); if (activeTimer.containsKey(jobname)) { return activeTimer.get(jobname); } <END> GlobalJDKJobHandle jobHandle = new GlobalJDKJobHandle( idCounter.getAndIncrement() ); TimerJobInstance jobInstance = globalTimerService. getTimerJobFactoryManager().createTimerJobInstance( job, ctx, trigger, jobHandle, (InternalSchedulerService) globalTimerService ); jobHandle.setTimerJobInstance( (TimerJobInstance) jobInstance ); interceptor.internalSchedule( (TimerJobInstance) jobInstance ); if (jobname != null) { activeTimer.put(jobname, jobHandle); } return jobHandle; } else { return null; } }</code><technical_language>This replacement is before, return activeTime if ctx is instance of ProcessJobContext (missing this condition for block, evaluated helper class), wdyt</technical_language>

Target:
public JobHandle scheduleJob(Job job, JobContext ctx, Trigger trigger) { long id = idCounter.getAndIncrement(); Date date = trigger.hasNextFireTime(); if ( date != null ) { String jobname = JobNameHelper.getJobName(ctx, id); if (activeTimer.containsKey(jobname)) { return activeTimer.get(jobname); } GlobalJDKJobHandle jobHandle = new GlobalJDKJobHandle( id); TimerJobInstance jobInstance = globalTimerService. getTimerJobFactoryManager().createTimerJobInstance( job, ctx, trigger, jobHandle, (InternalSchedulerService) globalTimerService ); jobHandle.setTimerJobInstance( (TimerJobInstance) jobInstance ); interceptor.internalSchedule( (TimerJobInstance) jobInstance ); activeTimer.put(jobname, jobHandle); return jobHandle; } else { return null; } }
Source:
<code>public synchronized void close() { logger.trace("Closing connection to broker '{}'", getName()); try { isConnecting = false; if (reconnectStrategy != null) { <START> reconnectStrategy.connectionEstablished(); <END> } if (isConnected()) { client.disconnect(); client = null; } } catch (org.eclipse.paho.client.mqttv3.MqttException e) { logger.info("Error closing connection to broker", e); } for (final MqttConnectionObserver connectionObserver : connectionObservers) { connectionObserver.connectionStateChanged(MqttConnectionState.DISCONNECTED, null); } }</code><technical_language>do consider a reconnect strategy implementation handles "close" "connectionEstablished" way? IMHO reconnect strategy closed leave implementation if act methods</technical_language>

Target:
public synchronized void close() { logger.trace("Closing the MQTT broker connection '{}'", getName()); isConnecting = false; if (reconnectStrategy != null) { reconnectStrategy.close(); } try { if (isConnected()) { client.disconnect(); client = null; } } catch (org.eclipse.paho.client.mqttv3.MqttException e) { logger.info("Error closing connection to broker", e); } for (final MqttConnectionObserver connectionObserver : connectionObservers) { connectionObserver.connectionStateChanged(MqttConnectionState.DISCONNECTED, null); } }
Source:
<code>private void setupWalletBestBlockListener() { bsqWalletService.addNewBestBlockListener(btcBlock -> { if (!daoStateService.isParseBlockChainComplete()) return; if (checkForBlockReceivedTimer != null) { checkForBlockReceivedTimer.stop(); } int btcWalletHeight = btcBlock.getHeight(); <START> log.error("New block at height from bsqWalletService", btcWalletHeight); <END> checkForBlockReceivedTimer = UserThread.runAfter(() -> { int daoChainHeight = daoStateService.getChainHeight(); if (daoChainHeight < btcWalletHeight) { log.warn("We did not receive a block from the network seconds after we saw the new block in BicoinJ. " + "We request from our seed nodes missing blocks from block height {}.", CHECK_FOR_BLOCK_RECEIVED_DELAY_SEC, daoChainHeight + 1); liteNodeNetworkService.requestBlocks(daoChainHeight + 1); } }, CHECK_FOR_BLOCK_RECEIVED_DELAY_SEC, TimeUnit.MILLISECONDS); }); }</code><technical_language>error log level</technical_language>

Target:
private void setupWalletBestBlockListener() { walletsSetup.downloadPercentageProperty().removeListener(blockDownloadListener); bsqWalletService.addNewBestBlockListener(blockFromWallet -> { if (!daoStateService.isParseBlockChainComplete()) return; if (checkForBlockReceivedTimer != null) { checkForBlockReceivedTimer.stop(); } int walletBlockHeight = blockFromWallet.getHeight(); log.info("New block at height from bsqWalletService", walletBlockHeight); checkForBlockReceivedTimer = UserThread.runAfter(() -> { int daoChainHeight = daoStateService.getChainHeight(); if (daoChainHeight < walletBlockHeight) { log.warn("We did not receive a block from the network seconds after we saw the new block in BitcoinJ. " + "We request from our seed nodes missing blocks from block height {}.", CHECK_FOR_BLOCK_RECEIVED_DELAY_SEC, daoChainHeight + 1); liteNodeNetworkService.requestBlocks(daoChainHeight + 1); } }, CHECK_FOR_BLOCK_RECEIVED_DELAY_SEC); }); }
Source:
<code>public void visitLiteralType(VisitableXmlElement<LiteralType> visitable) { JAXBElement<LiteralType> element = visitable.getElement(); <START> LOGGER.debug(element.getName().getLocalPart()); <END> List<Serializable> values = element.getValue().getContent(); if (values == null || values.isEmpty()) { LOGGER.debug("No values found on literal type"); return; } values.forEach(v -> LOGGER.debug((String) v)); builder.setValue(values.get(0).toString()); }</code><technical_language>is this log statement for, exactly? a trace</technical_language>

Target:
public void visitLiteralType(VisitableXmlElement<LiteralType> visitable) { JAXBElement<LiteralType> element = visitable.getElement(); traceLocalPart(element.getName().getLocalPart()); List<Serializable> values = element.getValue().getContent(); if (values == null || values.isEmpty()) { LOGGER.debug("No values found on literal type"); return; } if (LOGGER.isTraceEnabled()) { values.forEach(this::traceValue); } builder.setValue(values.get(0).toString()); }
Source:
<code>public Optional<PlanNode> apply(PlanNode node, Lookup lookup, PlanNodeIdAllocator idAllocator, SymbolAllocator symbolAllocator, Session session) { ProjectNode parent = (ProjectNode) node; PlanNode child = lookup.resolve(parent.getSource()); if (!(child instanceof JoinNode)) { return Optional.empty(); } JoinNode joinNode = (JoinNode) child; if (joinNode.isCrossJoin()) { return Optional.empty(); } Optional<Set<Symbol>> dependencies = pruneInputs(child.getOutputSymbols(), parent.getAssignments().getExpressions()); if (!dependencies.isPresent()) { return Optional.empty(); } return Optional.of( parent.replaceChildren(ImmutableList.of( new JoinNode( joinNode.getId(), joinNode.getType(), joinNode.getLeft(), joinNode.getRight(), joinNode.getCriteria(), <START> filter(joinNode.getOutputSymbols(), dependencies.get()::contains), <END> joinNode.getFilter(), joinNode.getLeftHashSymbol(), joinNode.getRightHashSymbol(), joinNode.getDistributionType())))); }</code><technical_language>Great</technical_language>

Target:
public Optional<PlanNode> apply(PlanNode node, Lookup lookup, PlanNodeIdAllocator idAllocator, SymbolAllocator symbolAllocator, Session session) { ProjectNode parent = (ProjectNode) node; PlanNode child = lookup.resolve(parent.getSource()); if (!(child instanceof JoinNode)) { return Optional.empty(); } JoinNode joinNode = (JoinNode) child; if (joinNode.isCrossJoin()) { return Optional.empty(); } Optional<Set<Symbol>> dependencies = pruneInputs(child.getOutputSymbols(), parent.getAssignments().getExpressions()); if (!dependencies.isPresent()) { return Optional.empty(); } return Optional.of( parent.replaceChildren(ImmutableList.of( new JoinNode( joinNode.getId(), joinNode.getType(), joinNode.getLeft(), joinNode.getRight(), joinNode.getCriteria(), filteredCopy(joinNode.getOutputSymbols(), dependencies.get()::contains), joinNode.getFilter(), joinNode.getLeftHashSymbol(), joinNode.getRightHashSymbol(), joinNode.getDistributionType())))); }
Source:
<code>public void testFileURLWithPropertiesUpdatedDynamically() throws IOException, InterruptedException { File file = new File("src/test/resources/test.properties"); populateFile(file, "test.host=12312,123213", "test.host1=132,12"); <START> Thread.sleep(1 * 31000); <END> DynamicURLConfiguration config = new DynamicURLConfiguration(); Assert.assertEquals(5, config.getInt("com.netflix.config.samples.SampleApp.SampleBean.numSeeds")); Thread.sleep(1 * 31000); CopyOnWriteArrayList writeList = new CopyOnWriteArrayList(); writeList.add("12312"); writeList.add("123213"); Assert.assertEquals(writeList, config.getProperty("test.host")); }</code><technical_language>@vanithadevig else good me. I improve is reduce sleep time. This add more 1 minute build time. I this myself, I this work, DynamicURLConfiguration config = new DynamicURLConfiguration(0, 1, false, new URLConfigurationSource().getConfigUrls()) instead of default constructor. This way, do Thread.sleep(2000). goes. that, I merge. This good</technical_language>

Target:
public void testFileURLWithPropertiesUpdatedDynamically() throws IOException, InterruptedException { File file = new File("src/test/resources/test.properties"); populateFile(file, "test.host=12312,123213", "test.host1=13212"); AbstractConfiguration.setDefaultListDelimiter(','); DynamicURLConfiguration config = new DynamicURLConfiguration(0, 500, false, file.toURI().toString()); Thread.sleep(1000); Assert.assertEquals(13212, config.getInt("test.host1")); Thread.sleep(1000); populateFile(file, "test.host=12312,123213", "test.host1=13212"); populateFile(file, "test.host=12312,123213", "test.host1=13212"); CopyOnWriteArrayList writeList = new CopyOnWriteArrayList(); writeList.add("12312"); writeList.add("123213"); config.setProperty("sample.domain", "google,yahoo"); Assert.assertEquals(writeList, config.getProperty("test.host")); }
Source:
<code>public void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_OK) { switch (requestCode) { case REQUEST_CHOOSE_ACCOUNT: <START> selectedAccountUuid = data.getStringExtra(ChooseAccount.EXTRA_ACCOUNT_UUID); <END> unreadFolder.setSummary(getString(R.string.unread_widget_folder_summary)); if (SearchAccount.UNIFIED_INBOX.equals(selectedAccountUuid) || SearchAccount.ALL_MESSAGES.equals(selectedAccountUuid)) { unreadAccount.setSummary(selectedAccountUuid); unreadFolderEnabled.setEnabled(false); unreadFolder.setEnabled(false); selectedFolderName = null; } else { Account selectedAccount = Preferences.getPreferences(this).getAccount(selectedAccountUuid); unreadAccount.setSummary(selectedAccount.getName()); unreadFolderEnabled.setEnabled(true); unreadFolder.setEnabled(true); } break; case REQUEST_CHOOSE_FOLDER: selectedFolderName = data.getStringExtra(ChooseFolder.EXTRA_NEW_FOLDER); unreadFolder.setSummary(selectedFolderName); break; } } super.onActivityResult(requestCode, resultCode, data); }</code><technical_language>move this stuff a private helper function - kind of long</technical_language>

Target:
public void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_OK) { switch (requestCode) { case REQUEST_CHOOSE_ACCOUNT: handleChooseAccount(data.getStringExtra(ChooseAccount.EXTRA_ACCOUNT_UUID)); break; case REQUEST_CHOOSE_FOLDER: handleChooseFolder(data.getStringExtra(ChooseFolder.EXTRA_NEW_FOLDER)); break; } } super.onActivityResult(requestCode, resultCode, data); }
Source:
<code>public static boolean runSingleJob(Jobby job, HadoopDruidIndexerConfig config) { String hadoopJobId = job.submitAndGetHadoopJobId(); <START> ObjectMapper objectMapper = new ObjectMapper(); <END> String hadoopJobIdFileName = config.getHadoopJobIdFileName(); if (hadoopJobIdFileName != null) { try { objectMapper.writeValue(new OutputStreamWriter( new FileOutputStream(new File(hadoopJobIdFileName)), StandardCharsets.UTF_8), hadoopJobId); log.info("MR job id: %s is written to the file: %s", hadoopJobId, hadoopJobIdFileName); } catch (IOException e) { log.error(e, "Error writing job id: %s to the file: %s.", hadoopJobId, hadoopJobIdFileName); } } boolean succeeded = job.run(); if (!config.getSchema().getTuningConfig().isLeaveIntermediate()) { if (succeeded || config.getSchema().getTuningConfig().isCleanupOnFailure()) { Path workingPath = config.makeIntermediatePath(); log.info("Deleting path[%s]", workingPath); try { Configuration conf = injectSystemProperties(new Configuration()); config.addJobProperties(conf); workingPath.getFileSystem(conf).delete(workingPath, true); } catch (IOException e) { log.error(e, "Failed to cleanup path[%s]", workingPath); } } } return succeeded; }</code><technical_language>Please HadoopDruidIndexerConfig.JSON_MAPPER instead</technical_language>

Target:
public static boolean runSingleJob(Jobby job, HadoopDruidIndexerConfig config) { boolean succeeded = job.run(); if (!config.getSchema().getTuningConfig().isLeaveIntermediate()) { if (succeeded || config.getSchema().getTuningConfig().isCleanupOnFailure()) { Path workingPath = config.makeIntermediatePath(); log.info("Deleting path[%s]", workingPath); try { Configuration conf = injectSystemProperties(new Configuration()); config.addJobProperties(conf); workingPath.getFileSystem(conf).delete(workingPath, true); } catch (IOException e) { log.error(e, "Failed to cleanup path[%s]", workingPath); } } } return succeeded; }
Source:
<code>public void initialize() { if (preferencesService.getPreferences().getForgedAlliance().getInstallationPath() == null) { preferenceUpdateListener = preferences -> { <START> if (!initialized && preferencesService.getPreferences().getForgedAlliance().getInstallationPath() != null) { <END> initialized = true; Platform.runLater(this::init); } }; preferencesService.addUpdateListener(new WeakReference<>(preferenceUpdateListener)); } else { init(); } }</code><technical_language>this check is game replay services? imo. removing this removing installation setting play</technical_language>

Target:
public void initialize() { initSpawnCountSpinner(); initMapSizeSpinner(); initWaterSlider(); initPlateauSlider(); initMountainSlider(); initRampSlider(); }
Source:
<code>public Map<String, Object> toMap() { <START> Map<String, Object> map = new HashMap<>(); <END> if (incrementingOffset != null) map.put(INCREMENTING_FIELD, incrementingOffset); if (timestampOffset != null) { map.put(TIMESTAMP_FIELD, timestampOffset.getTime()); map.put(TIMESTAMP_NANOS_FIELD, timestampOffset.getNanos()); } return map; }</code><technical_language>Minor: initialCapacity constructor arg 3</technical_language>

Target:
public Map<String, Object> toMap() { Map<String, Object> map = new HashMap<>(3); if (incrementingOffset != null) map.put(INCREMENTING_FIELD, incrementingOffset); if (timestampOffset != null) { map.put(TIMESTAMP_FIELD, timestampOffset.getTime()); map.put(TIMESTAMP_NANOS_FIELD, timestampOffset.getNanos()); } return map; }
Source:
<code>public int getOrder() { <START> return 0; <END> }</code><technical_language>In this case order configurable for of event emitting listerners. This done a Spring Boot property i.e. spring.cloud.task.events.<batch event listener>.order=<order#> . For example: spring.cloud.task.events.job-execution.order=<order#></technical_language>

Target:
public int getOrder() { return this.order; }
Source:
<code>public String toString() { <START> return mSequences.toString(); <END> }</code><technical_language>this return class name + hashcode of array? is more useful return md5? case for this</technical_language>

Target:
public String toString() { return "SAMSequenceDictionary:( sequences:"+ size()+ " length:"+ getReferenceLength()+" "+ " md5:"+md5()+")"; }
Source:
<code>public void error(CSSParseException exception) { <START> LOG.debug("CSS parser error: " + exception.getMessage()); <END> }</code><technical_language>LOG.debug("CSS parser error: {}", exception.getMessage());</technical_language>

Target:
public void error(CSSParseException exception) { LOG.debug("CSS parser error: {}", exception.getMessage()); }
Source:
<code>public boolean destroyNetworkRulesForVM(final Connect conn, final String vmName) { if (!_canBridgeFirewall) { return false; } String vif = null; final List<InterfaceDef> intfs = getInterfaces(conn, vmName); if (intfs.size() > 0) { final InterfaceDef intf = intfs.get(0); vif = intf.getDevName(); } <START> final Script cmd = new Script(_securityGroupPath, _timeout.getMillis(), s_logger); <END> cmd.add("destroy_network_rules_for_vm"); cmd.add("--vmname", vmName); if (vif != null) { cmd.add("--vif", vif); } final String result = cmd.execute(); if (result != null) { return false; } return true; }</code><technical_language>Please consider adding overridden version of Script(String, int, Logger) constructor accepts Duration encapsulate this type conversion</technical_language>

Target:
public boolean destroyNetworkRulesForVM(final Connect conn, final String vmName) { if (!_canBridgeFirewall) { return false; } String vif = null; final List<InterfaceDef> intfs = getInterfaces(conn, vmName); if (intfs.size() > 0) { final InterfaceDef intf = intfs.get(0); vif = intf.getDevName(); } final Script cmd = new Script(_securityGroupPath, _timeout, s_logger); cmd.add("destroy_network_rules_for_vm"); cmd.add("--vmname", vmName); if (vif != null) { cmd.add("--vif", vif); } final String result = cmd.execute(); if (result != null) { return false; } return true; }