auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void startDuckTimer() { if (this.duckTimer != null) { cancelDuckTimer(); } this.duckTimer = new Timer(); this.duckTimer.schedule(new TimerTask() { @Override public void run() { if (LogUtil.isLogAvailable()) { <START> Log.d(TAG, "Duck timer executed...something's wrong. Resetting audio focus and unducking volumne.."); <END> } hasFocus = false; requestAudio(); unduck(); } }, DUCK_TIMER_DELAY); }</code><technical_language>unducking _volume_</technical_language>

Target:
private void startDuckTimer() { if (this.duckTimer != null) { cancelDuckTimer(); } this.duckTimer = new Timer(); this.duckTimer.schedule(new TimerTask() { @Override public void run() { if (LogUtil.isLogAvailable()) { Log.d(TAG, "Duck timer executed...something's wrong. Resetting audio focus and unducking volume.."); } hasFocus = false; requestAudio(); unduck(); } }, DUCK_TIMER_DELAY_MS); }
Source:
<code>public void before() throws Exception { final String userHome = System.getProperty("user.home"); final String propertiesFilename = userHome + "/metamodel-integrationtest-configuration.properties"; final File file = new File(propertiesFilename); Assume.assumeTrue(file.exists()); final Properties props = new Properties(); props.load(new FileReader(file)); final String accessKey = props.getProperty("dynamodb.accessKey"); final String secretKey = props.getProperty("dynamodb.secretKey"); Assume.assumeNotNull(accessKey, secretKey); final AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey); final AWSCredentialsProvider credentialsProvider = new AWSStaticCredentialsProvider(credentials); <START> client = AmazonDynamoDBClientBuilder.standard().withRegion(Regions.US_WEST_2).withCredentials( <END> credentialsProvider).build(); }</code><technical_language>Region configurable</technical_language>

Target:
public void before() throws Exception { final String userHome = System.getProperty("user.home"); final String propertiesFilename = userHome + "/metamodel-integrationtest-configuration.properties"; final File file = new File(propertiesFilename); Assume.assumeTrue(file.exists()); final Properties props = new Properties(); props.load(new FileReader(file)); final String accessKey = props.getProperty("dynamodb.accessKey"); final String secretKey = props.getProperty("dynamodb.secretKey"); Assume.assumeNotNull(accessKey, secretKey); final Regions region = Regions.fromName(props.getProperty("dynamodb.region", Regions.DEFAULT_REGION.getName())); final AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey); final AWSCredentialsProvider credentialsProvider = new AWSStaticCredentialsProvider(credentials); client = AmazonDynamoDBClientBuilder.standard().withRegion(region).withCredentials(credentialsProvider).build(); }
Source:
<code>public Dirichlet(final Dirichlet prior, final double[] counts) { Utils.nonNull(counts); Arrays.stream(counts).forEach(c -> ParamUtils.isPositive(c, "Counts must be positive.")); <START> if (counts.length != prior.size()) { <END> throw new IllegalArgumentException("Counts and prior must have same length."); } alpha = IntStream.range(0, prior.size()).mapToDouble(n -> prior.alpha[n] + counts[n]).toArray(); }</code><technical_language>Utils.validateArg</technical_language>

Target:
public Dirichlet(final Dirichlet prior, final double[] counts) { Utils.nonNull(prior, "prior can't be null"); Utils.nonNull(counts, "counts can't be null"); Arrays.stream(counts).forEach(c -> ParamUtils.isPositive(c, "Counts must be positive.")); Utils.validateArg(counts.length == prior.size(), "Counts and prior must have same length."); alpha = IntStream.range(0, prior.size()).mapToDouble(n -> prior.alpha[n] + counts[n]).toArray(); }
Source:
<code>static AwsDates fromDateHeader(String date) { DateFormat dateFormat = new SimpleDateFormat(X_AMZ_DATE_FORMAT); dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); try { Date inputDate = new SimpleDateFormat(CUSTOM_DATE_FORMAT).parse(date); String xAmzDate = dateFormat.format(inputDate); return new AwsDates(date, xAmzDate, xAmzDate.substring(0, 8)); } catch (ParseException e) { <START> throw new IllegalArgumentException("Invalid date provided: " + date, e); <END> } }</code><technical_language>this a runtime exception; bubble ParseException</technical_language>

Target:
static AwsDates fromDateHeader(String date) throws ParseException { DateFormat dateFormat = new SimpleDateFormat(X_AMZ_DATE_FORMAT); dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); Date inputDate = new SimpleDateFormat(CUSTOM_DATE_FORMAT).parse(date); String xAmzDate = dateFormat.format(inputDate); return new AwsDates(xAmzDate, date); }
Source:
<code>public void testGetResourceInformationIfMethodAbsent() { final ResourceInformationReflector resourceInformationReflector = new ResourceInformationReflector(ResourceWithoutMethod.class.getName(), ResourceInfoWithMethod.class.getName()); final ResourceWithMethod resourceWithMethod = new ResourceWithMethod(); resourceWithMethod.setResourceInformation(RESOURCE_NAME, ResourceInfoWithMethod.newInstance(RESOURCE_NAME, RESOURCE_VALUE)); final Map<String, Long> externalResources = resourceInformationReflector.getExternalResourcesUnSafe(resourceWithMethod); <START> assertThat(externalResources.size(), is(0)); <END> }</code><technical_language>suggestion assertThat(externalResources, empty());</technical_language>

Target:
public void testGetResourceInformationIfMethodAbsent() { final ResourceInformationReflector resourceInformationReflector = new ResourceInformationReflector(ResourceWithoutMethod.class.getName(), ResourceInfoWithMethod.class.getName()); final ResourceWithMethod resourceWithMethod = new ResourceWithMethod(); resourceWithMethod.setResourceInformation(RESOURCE_NAME, ResourceInfoWithMethod.newInstance(RESOURCE_NAME, RESOURCE_VALUE)); final Map<String, Long> externalResources = resourceInformationReflector.getExternalResourcesUnSafe(resourceWithMethod); assertThat(externalResources.entrySet(), is(empty())); }
Source:
<code>private void drawLine(final double startX, final double startY, final double endX, final double endY) { <START> Circle head = new Circle(HEAD_RADIUS, Color.RED); <END> Circle tail = new Circle(HEAD_RADIUS, Color.GREEN); line.setStartX(startX); line.setStartY(startY); line.setEndX(endX); line.setEndY(endY); head.setCenterX(line.getStartX()); head.setCenterY(line.getStartY()); tail.setCenterX(line.getEndX()); tail.setCenterY(line.getEndY()); this.getChildren().addAll(line, head, tail); }</code><technical_language>colors constants</technical_language>

Target:
private void drawLine(final double startX, final double startY, final double endX, final double endY) { Circle head = new Circle(HEAD_RADIUS); Circle tail = new Circle(HEAD_RADIUS); head.getStyleClass().add("edgeHead"); tail.getStyleClass().add("edgeTail"); line.setStartX(startX); line.setStartY(startY); line.setEndX(endX); line.setEndY(endY); head.setCenterX(line.getStartX()); head.setCenterY(line.getStartY()); tail.setCenterX(line.getEndX()); tail.setCenterY(line.getEndY()); this.getChildren().addAll(line, head, tail); }
Source:
<code>public void run() { while (!isInterrupted()) { _sleepForPollPeriod(); if (!isInterrupted() && _isMonitoringServiceEnabled()) { try { _pushCounters(); } catch (Throwable t) { <START> _logger.error("Error occured while pushing monitor counters for {}. Reason: {}", HOSTNAME, t.getMessage()); <END> } } } }</code><technical_language>A suggestion catch exceptions register UncaughtExceptionHandler catch uncaught exceptions(Errors in this case capturing exceptions). I confident catching a Throwable letting thread continue execution. say</technical_language>

Target:
public void run() { while (!isInterrupted()) { _sleepForPollPeriod(); if (!isInterrupted() && _isMonitoringServiceEnabled()) { try { _pushCounters(); } catch (Exception ex) { _logger.error("Error occured while pushing monitor counters for {}. Reason: {}", HOSTNAME, ex.getMessage()); } } } }
Source:
<code>public void runEnhancementsFileObject() throws Exception { <START> FileObject fileObj = repositoryObjectFactory.createFileObject(PIDs.get(UUID_TEST), null); <END> fileObj.addOriginalFile(makeContentUri(BINARY_CONTENT), "file.png", "image/png", null, null); MvcResult result = mvc.perform(post("/runEnhancements") .contentType(MediaType.APPLICATION_JSON) .content("{\"force\":false,\"pids\":[\"" + UUID_TEST + "\"]}") .accept(MediaType.APPLICATION_JSON)) .andExpect(status().is2xxSuccessful()) .andReturn(); assertResponseSuccess(result); verify(jmsTemplate).send(any(MessageCreator.class)); }</code><technical_language>If call createFileObject(null) a PID for worry collisions test runs. get pid calling fileObj.getPid(). This allow remove hard coded pids too</technical_language>

Target:
public void runEnhancementsFileObject() throws Exception { FileObject fileObj = repositoryObjectFactory.createFileObject(null); PID filePid = fileObj.getPid(); fileObj.addOriginalFile(makeContentUri(BINARY_CONTENT), "file.png", "image/png", null, null); setResultMetadataObject(filePid); MvcResult result = mvc.perform(post("/runEnhancements") .contentType(MediaType.APPLICATION_JSON) .content("{\"force\":false,\"pids\":[\"" + filePid.getId() + "\"]}") .accept(MediaType.APPLICATION_JSON)) .andExpect(status().is2xxSuccessful()) .andReturn(); assertResponseSuccess(result); verify(messageSender).sendMessage(docCaptor.capture()); Document msgDoc = docCaptor.getValue(); assertMessageValues(msgDoc, fileObj.getOriginalFile().getPid(), "image/png"); }
Source:
<code>public JobsRunner pull(TransferForms forms, BriefcasePreferences appPreferences, BriefcasePreferences localPreferences) { return JobsRunner.launchAsync(forms.map(form -> run(jobStatus -> transferODKToBriefcase( appPreferences.getBriefcaseDir().orElseThrow(BriefcaseException::new), <START> new TerminationFuture(), <END> TransferForms.of(form) )))).onComplete(() -> EventBus.publish(new PullEvent.PullComplete())); }</code><technical_language>old/legacy This change in TransferFromODK eventually replaced a new implementation</technical_language>

Target:
public JobsRunner pull(TransferForms forms, BriefcasePreferences appPreferences, BriefcasePreferences localPreferences) { return JobsRunner.launchAsync(forms.map(form -> run(jobStatus -> transferODKToBriefcase( appPreferences.getBriefcaseDir().orElseThrow(BriefcaseException::new), path.toFile(), new TerminationFuture(), TransferForms.of(form) )))).onComplete(() -> EventBus.publish(new PullEvent.PullComplete())); }
Source:
<code>private void removeUnnecessaryAdvancedPrefs(PreferenceScreen screen) { PreferenceCategory plugins = (PreferenceCategory) screen.findPreference("category_plugins"); if (!CompatHelper.hasKanaAndEmojiKeys()) { CheckBoxPreference emojiScrolling = (CheckBoxPreference) screen.findPreference("scrolling_buttons"); if (emojiScrolling != null && plugins != null) { plugins.removePreference(emojiScrolling); } } if (!CompatHelper.hasScrollKeys() && !CompatHelper.hasKanaAndEmojiKeys()) { CheckBoxPreference doubleScrolling = (CheckBoxPreference) screen.findPreference("double_scrolling"); if (doubleScrolling != null && plugins != null) { plugins.removePreference(doubleScrolling); } } PreferenceCategory workarounds = (PreferenceCategory) screen.findPreference("category_workarounds"); if (workarounds != null) { CheckBoxPreference fixHebrewText = (CheckBoxPreference) screen.findPreference("fixHebrewText"); CompatHelper.removeHiddenPreferences(this.getApplicationContext()); <START> workarounds.removePreference(fixHebrewText); <END> } }</code><technical_language>remove this preference entirely</technical_language>

Target:
private void removeUnnecessaryAdvancedPrefs(PreferenceScreen screen) { PreferenceCategory plugins = (PreferenceCategory) screen.findPreference("category_plugins"); if (!CompatHelper.hasKanaAndEmojiKeys()) { CheckBoxPreference emojiScrolling = (CheckBoxPreference) screen.findPreference("scrolling_buttons"); if (emojiScrolling != null && plugins != null) { plugins.removePreference(emojiScrolling); } } if (!CompatHelper.hasScrollKeys() && !CompatHelper.hasKanaAndEmojiKeys()) { CheckBoxPreference doubleScrolling = (CheckBoxPreference) screen.findPreference("double_scrolling"); if (doubleScrolling != null && plugins != null) { plugins.removePreference(doubleScrolling); } } }
Source:
<code>public void setSelectQuery(String selectQuery) { <START> this.selectQuery = selectQuery; <END> }</code><technical_language>Assert.hasText(selectQuery, "'selectQuery' specified."); here: this component SELECT</technical_language>

Target:
public final void setSelectQuery(String selectQuery) { Assert.hasText(selectQuery, "'selectQuery' must be specified."); this.selectQuery = selectQuery; }
Source:
<code>private void provisionDefaultPlugins( List<ComponentImpl> components, FileContentProvider contentProvider) throws DevfileException { Map<String, String> missingPluginsIdToRef = new HashMap<>(defaultPluginsToRefs); for (ComponentImpl t : components) { if (PLUGIN_COMPONENT_TYPE.equals(t.getType())) { String pluginPublisherAndName = getPluginPublisherAndName(t, contentProvider); missingPluginsIdToRef.remove(pluginPublisherAndName); } } <START> for (String pluginRef : missingPluginsIdToRef.values()) { ExtendedPluginFQN fqn; ComponentImpl component; try { fqn = pluginFQNParser.parsePluginFQN(pluginRef); } catch (InfrastructureException e) { throw new DevfileException(e.getMessage(), e); } if (isNullOrEmpty(fqn.getReference())) { component = new ComponentImpl(PLUGIN_COMPONENT_TYPE, pluginRef); } else { try { fqn = pluginFQNParser.evaluateFqn(pluginRef, contentProvider); component = new ComponentImpl(PLUGIN_COMPONENT_TYPE, pluginRef); } catch (InfrastructureException e) { throw new DevfileException(e.getMessage(), e); } if (!isNullOrEmpty(fqn.getId())) { component.setId(fqn.getId()); } if (!isNullOrEmpty(fqn.getReference())) { component.setReference(fqn.getReference()); } } components.add(component); } <END> }</code><technical_language>extract this in a separate method(s) + provide test coverage for this method + doc. logic is straight-forward for atm</technical_language>

Target:
private void provisionDefaultPlugins( List<ComponentImpl> components, FileContentProvider contentProvider) throws DevfileException { Map<String, String> missingPluginsIdToRef = new HashMap<>(defaultPluginsToRefs); removeAlreadyAddedPlugins(components, contentProvider, missingPluginsIdToRef); try { addMissingPlugins(components, contentProvider, missingPluginsIdToRef); } catch (InfrastructureException e) { throw new DevfileException(e.getMessage(), e); } }
Source:
<code>public Integer saveRule(Rule rule) throws InvalidRuleException { return runInTransaction((status) -> { final Group group = classificationGroupDao.findByName(Groups.USER_DEFINED); ruleValidator.validate(rule); groupValidator.validate(group, rule); group.addRule(rule); final Integer ruleId = classificationRuleDao.save(rule); <START> updateRulePositionsAndReloadEngine(RulePrioritizationUtil.sortRulePositions(group)); <END> return ruleId; }); }</code><technical_language>sorting part of updateRulePositionsAndReloadEngine method</technical_language>

Target:
public Integer saveRule(Rule rule) throws InvalidRuleException { return runInTransaction((status) -> { final Group group = classificationGroupDao.findByName(Groups.USER_DEFINED); ruleValidator.validate(rule); groupValidator.validate(group, rule); group.addRule(rule); final Integer ruleId = classificationRuleDao.save(rule); updateRulePositionsAndReloadEngine(RulePositionUtil.sortRulePositions(rule)); return ruleId; }); }
Source:
<code>public List<VdcBllMessages> validate() { Set<String> ifaceNames = new HashSet<String>(); Map<String, VdsNetworkInterface> bonds = new HashMap<String, VdsNetworkInterface>(); Map<String, List<VdsNetworkInterface>> bondSlaves = new HashMap<String, List<VdsNetworkInterface>>(); Map<String, network> networks = new HashMap<String, network>(); for (VdsNetworkInterface iface : params.getInterfaces()) { String name = iface.getName(); String networkName = iface.getNetworkName(); String bondName = iface.getBondName(); if (ifaceNames.contains(name)) { violations.add(VdcBllMessages.NETWORK_INTERFACE_NAME_ALREADY_IN_USE); continue; } else { ifaceNames.add(name); } if (isBond(iface)) { <START> <END> if (iface.getVlanId() == null) { extractBond(bonds, iface, name); } else if (!getExistingIfaces().containsKey(NetworkUtils.StripVlan(name))) { violations.add(VdcBllMessages.NETWORK_BOND_NOT_EXISTS); } } else { if (StringUtils.isNotBlank(bondName)) { extractBondSlave(bondSlaves, iface, bondName); } if (!getExistingIfaces().containsKey(NetworkUtils.StripVlan(name))) { violations.add(VdcBllMessages.NETWORK_INTERFACE_NOT_EXISTS); } } if (violations.isEmpty() && StringUtils.isNotBlank(networkName)) { extractNetwork(networks, iface, networkName); } } validateBonds(bonds, bondSlaves); this.networks = new ArrayList<network>(networks.values()); extractRemoveNetworks(networks.keySet(), getExisitingHostNetworkNames()); this.bonds = new ArrayList<VdsNetworkInterface>(bonds.values()); this.removedBonds = extractRemovedBonds(bonds); return violations; }</code><technical_language>vlan bond isBonded false. Please verify case in 3.0</technical_language>

Target:
public List<VdcBllMessages> validate() { Set<String> ifaceNames = new HashSet<String>(); Set<String> bonds = new HashSet<String>(); Set<String> attachedNetworksNames = new HashSet<String>(); Map<String, List<VdsNetworkInterface>> bondSlaves = new HashMap<String, List<VdsNetworkInterface>>(); for (VdsNetworkInterface iface : params.getInterfaces()) { String name = iface.getName(); String networkName = iface.getNetworkName(); String bondName = iface.getBondName(); if (ifaceNames.contains(name)) { violations.add(VdcBllMessages.NETWORK_INTERFACE_NAME_ALREADY_IN_USE); continue; } else { ifaceNames.add(name); } if (isBond(iface)) { extractBondIfModified(bonds, iface, name); } else { if (StringUtils.isNotBlank(bondName)) { extractBondSlave(bondSlaves, iface, bondName); } if (!getExistingIfaces().containsKey(NetworkUtils.StripVlan(name))) { violations.add(VdcBllMessages.NETWORK_INTERFACE_NOT_EXISTS); } } if (violations.isEmpty() && StringUtils.isNotBlank(networkName)) { extractNetwork(attachedNetworksNames, iface, networkName); } } validateBonds(bonds, bondSlaves); detectSlaveChanges(bondSlaves); extractRemoveNetworks(attachedNetworksNames, getExisitingHostNetworkNames()); this.removedBonds = extractRemovedBonds(bonds); return violations; }
Source:
<code>public static void main(String[] args) throws Exception { String filePath = System.getProperty("user.dir") + "\\dl4j-examples\\src\\main\\resources\\NewsData\\RawNewsToGenerateWordVector.txt"; <START> log.info("Load & Vectorize Sentences...."); <END> SentenceIterator iter = new BasicLineIterator(filePath); TokenizerFactory t = new DefaultTokenizerFactory(); t.setTokenPreProcessor(new CommonPreprocessor()); log.info("Building model...."); Word2Vec vec = new Word2Vec.Builder() .minWordFrequency(2) .iterations(5) .layerSize(100) .seed(42) .windowSize(20) .iterate(iter) .tokenizerFactory(t) .build(); log.info("Fitting Word2Vec model...."); vec.fit(); log.info("Writing word vectors to text file...."); WordVectorSerializer.writeWordVectors(vec, System.getProperty("user.dir") + "\\dl4j-examples\\src\\main\\resources\\NewsData\\NewsWordVector.txt"); }</code><technical_language>This assume windows. Please ClassPathResource instead</technical_language>

Target:
public static void main(String[] args) throws Exception { String classPathResource = new ClassPathResource("NewsData").getFile().getAbsolutePath() + File.separator; String filePath = new File(classPathResource + File.separator + "RawNewsToGenerateWordVector.txt").getAbsolutePath(); log.info("Load & Vectorize Sentences...."); SentenceIterator iter = new BasicLineIterator(filePath); TokenizerFactory t = new DefaultTokenizerFactory(); t.setTokenPreProcessor(new CommonPreprocessor()); log.info("Building model...."); Word2Vec vec = new Word2Vec.Builder() .minWordFrequency(2) .iterations(5) .layerSize(100) .seed(42) .windowSize(20) .iterate(iter) .tokenizerFactory(t) .build(); log.info("Fitting Word2Vec model...."); vec.fit(); log.info("Writing word vectors to text file...."); WordVectorSerializer.writeWordVectors(vec, classPathResource + "NewsWordVector.txt"); }
Source:
<code>public IndexMap( <START> Map<Long, IndexProxy> indexesById ) <END> { this( indexesById, indexesByDescriptor( indexesById ), indexIdsByDescriptor( indexesById ) ); }</code><technical_language>this fit a single line..</technical_language>

Target:
IndexMap( Map<Long,IndexProxy> indexesById ) { this( indexesById, indexesByDescriptor( indexesById ), indexIdsByDescriptor( indexesById ) ); }
Source:
<code>public void evaluateRequest(HttpServerRequest request) throws HttpAuthenticationException { List<String> authorizationValues = request.getRequestHeaderValues(HttpConstants.AUTHORIZATION); if (authorizationValues != null) { Matcher matcher; for (String current : authorizationValues) { if ((matcher = BEARER_TOKEN_PATTERN.matcher(current)).matches()) { BearerTokenEvidence tokenEvidence = new BearerTokenEvidence(matcher.group(1)); EvidenceVerifyCallback verifyCallback = new EvidenceVerifyCallback(tokenEvidence); handleCallback(verifyCallback); if (verifyCallback.isVerified()) { AuthorizeCallback authorizeCallback = new AuthorizeCallback(null, null); handleCallback(authorizeCallback); if (authorizeCallback.isAuthorized()) { httpBearer.debugf("Token authentication successful."); handleCallback(new IdentityCredentialCallback(new BearerTokenCredential(tokenEvidence.getToken()), true)); handleCallback(AuthenticationCompleteCallback.SUCCEEDED); request.authenticationComplete(); return; } } httpBearer.debugf("Token authentication failed."); <START> request.authenticationFailed("Invalid bearer token", response -> response.setStatusCode(FORBIDDEN)); <END> } } } request.noAuthenticationInProgress(this::unauthorizedResponse); }</code><technical_language>needs added return prevent tokens verification! attacker is able try multiple tokens in request</technical_language>

Target:
public void evaluateRequest(HttpServerRequest request) throws HttpAuthenticationException { List<String> authorizationValues = request.getRequestHeaderValues(HttpConstants.AUTHORIZATION); if (authorizationValues != null) { Matcher matcher; for (String current : authorizationValues) { if ((matcher = BEARER_TOKEN_PATTERN.matcher(current)).matches()) { BearerTokenEvidence tokenEvidence = new BearerTokenEvidence(matcher.group(1)); EvidenceVerifyCallback verifyCallback = new EvidenceVerifyCallback(tokenEvidence); handleCallback(verifyCallback); if (verifyCallback.isVerified()) { AuthorizeCallback authorizeCallback = new AuthorizeCallback(null, null); handleCallback(authorizeCallback); if (authorizeCallback.isAuthorized()) { httpBearer.debugf("Token authentication successful."); handleCallback(new IdentityCredentialCallback(new BearerTokenCredential(tokenEvidence.getToken()), true)); handleCallback(AuthenticationCompleteCallback.SUCCEEDED); request.authenticationComplete(); return; } } httpBearer.debugf("Token authentication failed."); request.authenticationFailed("Invalid bearer token", response -> response.setStatusCode(FORBIDDEN)); return; } } } request.noAuthenticationInProgress(this::unauthorizedResponse); }
Source:
<code>public static List<File> recursiveListLocalDir(File dir) { File[] files = dir.listFiles(); if (files == null) { <START> return Collections.EMPTY_LIST; <END> } List<File> result = new ArrayList<>(files.length); for (File f : files) { if (f.isDirectory()) { result.addAll(recursiveListLocalDir(f)); continue; } result.add(f); } return result; }</code><technical_language>I Collections.emptyList() work type safety</technical_language>

Target:
public static List<File> recursiveListLocalDir(File dir) { File[] files = dir.listFiles(); if (files == null) { return Collections.emptyList(); } List<File> result = new ArrayList<>(files.length); for (File f : files) { if (f.isDirectory()) { result.addAll(recursiveListLocalDir(f)); continue; } result.add(f); } return result; }
Source:
<code>public void onActivate(ActivateEvent event, EntityRef entity) { LASTeamComponent baseTeamComponent = entity.getComponent(LASTeamComponent.class); EntityRef player = event.getInstigator(); CharacterHeldItemComponent characterHeldItemComponent = player.getComponent(CharacterHeldItemComponent.class); if (characterHeldItemComponent != null) { EntityRef heldItem = characterHeldItemComponent.selectedItem; <START> <END> if (baseTeamComponent.team.equals(LASUtils.RED_TEAM) && heldItem.hasComponent(BlockItemComponent.class) && heldItem.getComponent(BlockItemComponent.class).blockFamily.getURI().toString().equals(LASUtils.BLACK_FLAG_URI)) { redScore++; inventoryManager.removeItem(player, player, heldItem, true); worldProvider.setBlock(new Vector3i(LASUtils.CENTER_BLACK_BASE_POSITION.x, LASUtils.CENTER_BLACK_BASE_POSITION.y + 1, LASUtils.CENTER_BLACK_BASE_POSITION.z), blockManager.getBlock(LASUtils.BLACK_FLAG_URI)); } if (baseTeamComponent.team.equals(LASUtils.BLACK_TEAM) && heldItem.hasComponent(BlockItemComponent.class) && heldItem.getComponent(BlockItemComponent.class).blockFamily.getURI().toString().equals(LASUtils.RED_FLAG_URI)) { blackScore++; inventoryManager.removeItem(player, player, heldItem, true); worldProvider.setBlock(new Vector3i(LASUtils.CENTER_RED_BASE_POSITION.x, LASUtils.CENTER_RED_BASE_POSITION.y + 1, LASUtils.CENTER_RED_BASE_POSITION.z), blockManager.getBlock(LASUtils.RED_FLAG_URI)); } } }</code><technical_language>move entire logic onActivate a method called- checkAndResetGameOnScore This do things, method for each- 1. Check if team score. (Check for team in base's LASTeamComponent for heldItem team's FlagComponent) 2. Increment score. 3. Reset round- (This method for teams completely reset want)</technical_language>

Target:
public void onActivate(ActivateEvent event, EntityRef entity) { checkAndResetGameOnScore(event, entity); }
Source:
<code>public int getIdForLanguage(@NonNull String code) { Integer id = ids.get(code); return <START> id != null ? id : 0; <END> }</code><technical_language>If flip this conditional, == instead of negated logic</technical_language>

Target:
public int getIdForLanguage(@NonNull String code) { Integer id = ids.get(code); return id == null ? 0 : id; }
Source:
<code>private int getPortOffset() { ServerConfiguration carbonConfig = ServerConfiguration.getInstance(); String portOffset = System.getProperty("portOffset", carbonConfig.getFirstProperty(CARBON_CONFIG_PORT_OFFSET)); try { <START> return ((portOffset != null) ? Integer.parseInt(portOffset.trim()) : CARBON_DEFAULT_PORT_OFFSET); <END> } catch (NumberFormatException e) { return CARBON_DEFAULT_PORT_OFFSET; } }</code><technical_language>more clear if break this if else statement</technical_language>

Target:
private int getPortOffset() { ServerConfiguration carbonConfig = ServerConfiguration.getInstance(); String portOffset = System.getProperty("portOffset", carbonConfig.getFirstProperty(CARBON_CONFIG_PORT_OFFSET)); try { if ((portOffset != null)) { return Integer.parseInt(portOffset.trim()); } else { return CARBON_DEFAULT_PORT_OFFSET; } } catch (NumberFormatException e) { return CARBON_DEFAULT_PORT_OFFSET; } }
Source:
<code>public void onNewJobModelConfirmed(String version) { LOG.info("pid=" + processorId + "new version " + version + " of the job model got confirmed"); JobModel jobModel = getJobModel(); if (coordinatorListener != null) { coordinatorListener.onNewJobModel(processorId, jobModel); } <START> zkUtils.cleanupZK(10); <END> }</code><technical_language>questions here: A) please extract this 10 a static constant in this class (Like NUM_CLEANUP_VERSIONS). B) Is this called leader in processors ? benefits in leader * avert potential concurrency problems delete. * remove additional overhead issuing delete in stream processors receiving this event</technical_language>

Target:
public void onNewJobModelConfirmed(String version) { LOG.info("pid=" + processorId + "new version " + version + " of the job model got confirmed"); JobModel jobModel = getJobModel(); if (coordinatorListener != null) { coordinatorListener.onNewJobModel(processorId, jobModel); } }
Source:
<code>protected boolean canDoAction() { <START> return super.canDoAction() && VdsGroupExists() && logicalNetworkExists() && changesAreClusterCompatible(); <END> }</code><technical_language>moving logicalNetworkExists() changesAreClusterCompatible() ? in case changesAreClusterCompatible() returns false, save DB call :)</technical_language>

Target:
protected boolean canDoAction() { return super.canDoAction() && VdsGroupExists() && changesAreClusterCompatible() && logicalNetworkExists(); }
Source:
<code>private void readForward(PipedOutputStream pos) { try { <START> withinOperationsElement = <END> false; final boolean isForwardDir = direction == Direction.Forward; final String closingTag = getClosingTag(isForwardDir); String line = reader.readLine(); while (line != null && !line.contains(closingTag)) { if (line.contains(getOpeningTag(isForwardDir))) { withinOperationsElement = true; } else if (withinOperationsElement) { pos.write(line.getBytes()); } line = reader.readLine(); } if (line != null) { withinOperationsElement = false; } } catch (final IOException ex) { ModelUtil.logException(ex); } finally { try { pos.close(); } catch (final IOException ex) { ModelUtil.logException(ex); } } }</code><technical_language>is this a field</technical_language>

Target:
private void readForward(PipedOutputStream pos) { try { boolean withinOperationsElement = false; final boolean isForwardDir = direction == Direction.Forward; final String closingTag = getClosingTag(isForwardDir); String line = reader.readLine(); while (line != null && !line.contains(closingTag)) { if (line.contains(getOpeningTag(isForwardDir))) { withinOperationsElement = true; } else if (withinOperationsElement) { pos.write(line.getBytes()); } line = reader.readLine(); } if (line != null) { withinOperationsElement = false; } } catch (final IOException ex) { ModelUtil.logException(ex); } finally { try { pos.close(); } catch (final IOException ex) { ModelUtil.logException(ex); } } }
Source:
<code>public long getLong() { <START> return convertTo(Value.LONG).getLong(); <END> }</code><technical_language>typecasts a guards invalid results of convertTo(). this change if result of convertTo() override getter behavior changed. StackOverflowError instead of ClassCastException. If some code expects Exception, expects Error this lead a problem. Hypothetically broken convertTo() implementations, this change needs additional analysis review</technical_language>

Target:
public long getLong() { return ((ValueLong) convertTo(Value.LONG)).getLong(); }
Source:
<code>public void testUnmarshallSubprocessLevelEventWithEdgesEmptyProperties() throws Exception { Diagram<Graph, Metadata> diagram = unmarshall(marshaller, BPMN_CATCHING_INTERMEDIATE_EVENT_FILE_PATH); assertDiagram(diagram, AMOUNT_OF_NODES_IN_DIAGRAM); IntermediateSignalEventCatching emptySubprocessEvent = getCatchingIntermediateNodeById(diagram, EMPTY_WITH_INCOME_SUBPROCESS_LEVEL_EVENT_ID, HAS_INCOME_EDGE, HAS_OUTGOING_EDGE); assertGeneralSet(emptySubprocessEvent.getGeneral(), EMPTY_VALUE, EMPTY_VALUE); <START> assertSignalEventExecutionSet(emptySubprocessEvent.getExecutionSet(), EMPTY_VALUE, CANCELLING, ""); <END> assertDataIOSet(emptySubprocessEvent.getDataIOSet(), EMPTY_VALUE); }</code><technical_language>suggestion assertSignalEventExecutionSet(emptySubprocessEvent.getExecutionSet(), EMPTY_VALUE, CANCELLING, EMPTY_VALUE);</technical_language>

Target:
public void testUnmarshallSubprocessLevelEventWithEdgesEmptyProperties() throws Exception { Diagram<Graph, Metadata> diagram = unmarshall(marshaller, BPMN_CATCHING_INTERMEDIATE_EVENT_FILE_PATH); assertDiagram(diagram, AMOUNT_OF_NODES_IN_DIAGRAM); IntermediateSignalEventCatching emptySubprocessEvent = getCatchingIntermediateNodeById(diagram, EMPTY_WITH_INCOME_SUBPROCESS_LEVEL_EVENT_ID, HAS_INCOME_EDGE, HAS_OUTGOING_EDGE); assertGeneralSet(emptySubprocessEvent.getGeneral(), EMPTY_VALUE, EMPTY_VALUE); assertSignalEventExecutionSet(emptySubprocessEvent.getExecutionSet(), EMPTY_VALUE, CANCELLING, EMPTY_VALUE); assertDataIOSet(emptySubprocessEvent.getDataIOSet(), EMPTY_VALUE); }
Source:
<code>public void run(IProgressMonitor monitor) { ListMultimap<File, String> locationToProjectNames = ArrayListMultimap.create(); for (EclipseProject project : this.projects) { <START> locationToProjectNames.put(project.getProjectDirectory(), project.getName()); <END> } for (File location : locationToProjectNames.keySet()) { List<String> projectNames = locationToProjectNames.get(location); if (projectNames.size() > 1) { throw new UnsupportedConfigurationException(String.format("The following projects all located in the %s directory: %s", location.getAbsolutePath(), Joiner.on(", ").join(projectNames))); } else if (location.equals(WORKSPACE_ROOT)) { throw new UnsupportedConfigurationException(String.format("Project %s location matches workspace root %s", projectNames.get(0), WORKSPACE_ROOT.getAbsolutePath())); } } }</code><technical_language>*are* located</technical_language>

Target:
public void run(IProgressMonitor monitor) { ListMultimap<File, String> locationToProjectNames = ArrayListMultimap.create(); for (EclipseProject project : this.projects) { locationToProjectNames.put(project.getProjectDirectory(), project.getName()); } for (File location : locationToProjectNames.keySet()) { List<String> projectNames = locationToProjectNames.get(location); if (projectNames.size() > 1) { throw new UnsupportedConfigurationException(String.format("The following projects are all located in the %s directory: %s", location.getAbsolutePath(), Joiner.on(", ").join(projectNames))); } else if (location.equals(WORKSPACE_ROOT)) { throw new UnsupportedConfigurationException(String.format("Project %s location matches workspace root %s", projectNames.get(0), WORKSPACE_ROOT.getAbsolutePath())); } } }
Source:
<code><START> public boolean filter(final LogMessage message) { <END> final LocalDate startDate = Optional.ofNullable(startDatePicker.getValue()).orElse(LocalDate.now()); final LocalTime startTime = LocalTime.of(startHourSpinner.getValue(), startMinuteSpinner.getValue(), startSecondSpinner.getValue(), startMilliSpinner.getValue() * 1_000_000); final ZonedDateTime startDateTime = ZonedDateTime.of(LocalDateTime.of(startDate, startTime), ZoneId.systemDefault()); final LocalDate endDate = Optional.ofNullable(endDatePicker.getValue()).orElse(LocalDate.now()); final LocalTime endTime = LocalTime.of(endHourSpinner.getValue(), endMinuteSpinner.getValue(), endSecondSpinner.getValue(), endMilliSpinner.getValue() * 1_000_000); final ZonedDateTime endDateTime = ZonedDateTime.of(LocalDateTime.of(endDate, endTime), ZoneId.systemDefault()); final Set<Level> selectedLevels = Optional.ofNullable(levelComboBox.getSelectionModel().getSelectedItem()). map(l -> Collections.singleton(l)).orElse(Collections.emptySet()); if(!selectedLevels.contains(message.getLevel())) { return false; } if(message.getTimestamp().isBefore(startDateTime)) { return false; } if(message.getTimestamp().isAfter(endDateTime)) { return false; } return true; }</code><technical_language>Add null-check for method parameter</technical_language>

Target:
public boolean filter(final LogMessage message) { Assert.requireNonNull(message, "message"); final LocalDate startDate = Optional.ofNullable(startDatePicker.getValue()).orElse(LocalDate.now()); final LocalTime startTime = LocalTime.of(startHourSpinner.getValue(), startMinuteSpinner.getValue(), startSecondSpinner.getValue(), startMilliSpinner.getValue() * 1_000_000); final ZonedDateTime startDateTime = ZonedDateTime.of(LocalDateTime.of(startDate, startTime), ZoneId.systemDefault()); final LocalDate endDate = Optional.ofNullable(endDatePicker.getValue()).orElse(LocalDate.now()); final LocalTime endTime = LocalTime.of(endHourSpinner.getValue(), endMinuteSpinner.getValue(), endSecondSpinner.getValue(), endMilliSpinner.getValue() * 1_000_000); final ZonedDateTime endDateTime = ZonedDateTime.of(LocalDateTime.of(endDate, endTime), ZoneId.systemDefault()); final Set<Level> selectedLevels = Optional.ofNullable(levelComboBox.getSelectionModel().getSelectedItem()). map(l -> Collections.singleton(l)).orElse(Collections.emptySet()); if(!selectedLevels.contains(message.getLevel())) { return false; } if(message.getTimestamp().isBefore(startDateTime)) { return false; } if(message.getTimestamp().isAfter(endDateTime)) { return false; } return true; }
Source:
<code>public void close() { flipper = false; try { flipperJob.waitTermination(); } catch ( InterruptedException | ExecutionException e ) { <START> e.printStackTrace(); <END> } applier.stop(); Consumer<WritableFulltext> fulltextCloser = luceneFulltextIndex -> { try { luceneFulltextIndex.saveConfiguration( transactionIdStore.getLastCommittedTransactionId() ); luceneFulltextIndex.close(); } catch ( IOException e ) { log.error( "Unable to close fulltext index.", e ); } }; writableNodeIndices[ASIDE].values().forEach( fulltextCloser ); writableNodeIndices[BSIDE].values().forEach( fulltextCloser ); writableRelationshipIndices[ASIDE].values().forEach( fulltextCloser ); writableRelationshipIndices[BSIDE].values().forEach( fulltextCloser ); }</code><technical_language>This log well</technical_language>

Target:
public void close() { closed = true; try { flipperJob.waitTermination(); } catch ( InterruptedException | ExecutionException e ) { log.error( "Unable stop the fulltext index flipper", e ); } applier.stop(); Consumer<WritableFulltext> fulltextCloser = luceneFulltextIndex -> { try { luceneFulltextIndex.saveConfiguration( transactionIdStore.getLastCommittedTransactionId() ); luceneFulltextIndex.close(); } catch ( IOException e ) { log.error( "Unable to close fulltext index.", e ); } }; writableNodeIndices[ASIDE].values().forEach( fulltextCloser ); writableNodeIndices[BSIDE].values().forEach( fulltextCloser ); writableRelationshipIndices[ASIDE].values().forEach( fulltextCloser ); writableRelationshipIndices[BSIDE].values().forEach( fulltextCloser ); }
Source:
<code>protected boolean migrateAllVms(ExecutionContext parentContext, boolean HAOnly) { boolean succeeded = true; for (VM vm : vms) { <START> if (vm.isHostedEngine()) { if (!canScheduleVm(vm)) { succeeded = false; appendCustomCommaSeparatedValue("failedVms", vm.getName()); log.error("There is no host capable of running the hosted engine VM"); } } <END> if (vm.getStatus() != VMStatus.MigratingFrom && (!HAOnly || vm.isAutoStartup())) { if (!migrateVm(vm, parentContext)) { succeeded = false; appendCustomCommaSeparatedValue("failedVms", vm.getName()); log.error("Failed to migrate VM '{}'", vm.getName()); } } } return succeeded; }</code><technical_language>If VM is migrated engine other VMs, this code block removed canScheduleVm() method too</technical_language>

Target:
protected boolean migrateAllVms(ExecutionContext parentContext, boolean HAOnly) { boolean succeeded = true; List<VM> vmsToMigrate = new ArrayList<>(); for (VM vm : vms) { if (vm.isHostedEngine()) { if (!canScheduleVm(vm)) { succeeded = false; log.error("There is no host capable of running the hosted engine VM"); } } if (vm.getStatus() != VMStatus.MigratingFrom && (!HAOnly || vm.isAutoStartup())) { vmsToMigrate.add(vm); } } if (!migrateVms(vmsToMigrate, parentContext)) { succeeded = false; log.error("Failed to migrate one or more VMs."); } return succeeded; }
Source:
<code>public <T> List<T> searchEntitiesWithFullDetails(MambuEntityType searchEntityType, JSONFilterConstraints filterConstraints, String offset, String limit) throws MambuApiException { ENDING", "dataItemType":"LOANS"}} ApiDefinition apiDefinition = SearchService.makeApiDefinitionForSearchByFilter(searchEntityType); <START> apiDefinition.setWithFullDetails(true); <END> return serviceExecutor.executeJson(apiDefinition, filterConstraints, null, null, ServiceHelper.makePaginationParams(offset, limit)); }</code><technical_language>distinct ways of creating apiDefinition full details. In previous classes (LoansService SavingsService), created separate private methods, in this class called setter inline. Moreover, methods LoansService SavingsService in place names (makeFullSearchApiDefinition vs. makeSearchTransactionsWithFullApiDefinition). I a single approach - a distinct method calling setter right apiDefinition creation. Also, method names similar classes. Another idea overload SearchService#makeApiDefinitionForSearchByFilter accept a boolean represents basic / full details level</technical_language>

Target:
public <T> List<T> searchEntitiesWithFullDetails(MambuEntityType searchEntityType, JSONFilterConstraints filterConstraints, String offset, String limit) throws MambuApiException { ENDING", "dataItemType":"LOANS"}} ApiDefinition apiDefinition = makeSearchEntitiesWithFullApiDefinition(searchEntityType); return serviceExecutor.executeJson(apiDefinition, filterConstraints, null, null, ServiceHelper.makePaginationParams(offset, limit)); }
Source:
<code>public File getDownloadDirectory() { final PrefManager prefManger = new PrefManager(context, PrefManager.Pref.SD_CARD); <START> File externalAppDir = null; <END> if (prefManger.getBoolean(PrefManager.Key.DOWNLOAD_TO_SDCARD, false)) { externalAppDir = FileUtil.getRemovableStorageAppDir(context); } if (externalAppDir == null) { externalAppDir = FileUtil.getExternalAppDir(context); } final ProfileModel profile = getProfile(); if (externalAppDir != null && profile != null) { File videosDir = new File(externalAppDir, AppConstants.Directories.VIDEOS); File usersVidsDir = new File(videosDir, Sha1Util.SHA1(profile.username)); usersVidsDir.mkdirs(); try { File noMediaFile = new File(usersVidsDir, ".nomedia"); noMediaFile.createNewFile(); } catch (IOException ioException) { logger.error(ioException); } return usersVidsDir; } return null; }</code><technical_language>downloadDir is a good name here</technical_language>

Target:
public File getDownloadDirectory() { File downloadDir = null; if (isSDCardDownloadEnabled()) { downloadDir = FileUtil.getRemovableStorageAppDir(context); } else { downloadDir = FileUtil.getExternalAppDir(context); } final ProfileModel profile = getProfile(); if (downloadDir != null && profile != null) { File videosDir = new File(downloadDir, AppConstants.Directories.VIDEOS); File usersVidsDir = new File(videosDir, Sha1Util.SHA1(profile.username)); usersVidsDir.mkdirs(); try { File noMediaFile = new File(usersVidsDir, ".nomedia"); noMediaFile.createNewFile(); } catch (IOException ioException) { logger.error(ioException); } return usersVidsDir; } return null; }
Source:
<code>public List<Datastream> getAll(@Context PagingContext pagingContext) { <START> return RestliUtils.withPaging(_store.getAllDatastreams(), pagingContext).collect(Collectors.toList()); <END> }</code><technical_language>Based chat, makesure getDatastream is called for everything</technical_language>

Target:
public List<Datastream> getAll(@Context PagingContext pagingContext) { return RestliUtils.withPaging(_store.getAllDatastreams(), pagingContext).map(_store::getDatastream) .filter(stream -> stream != null).collect(Collectors.toList()); }
Source:
<code>private void execute() { try { HttpResponse response = client.execute(request, context); Logger.debug(LOG_TAG, "Response: " + response.getStatusLine().toString()); HttpResponseObserver observer = getHttpResponseObserver(); if (observer != null) { observer.observeHttpResponse(response); } delegate.handleHttpResponse(response); } catch (ClientProtocolException e) { delegate.handleHttpProtocolException(e); } catch (IOException e) { <START> Logger.debug(LOG_TAG, "I/O exception returned from execute."); <END> if (!retry) { delegate.handleHttpIOException(e); } else { retry = false; Logger.debug(LOG_TAG, "Retrying request..."); this.execute(); } } catch (Exception e) { if (!retry) { delegate.handleHttpIOException(new IOException(e)); } else { retry = false; Logger.debug(LOG_TAG, "Retrying request..."); this.execute(); } } }</code><technical_language>This good</technical_language>

Target:
private void execute() { try { HttpResponse response = client.execute(request, context); Logger.debug(LOG_TAG, "Response: " + response.getStatusLine().toString()); HttpResponseObserver observer = getHttpResponseObserver(); if (observer != null) { observer.observeHttpResponse(response); } delegate.handleHttpResponse(response); } catch (ClientProtocolException e) { delegate.handleHttpProtocolException(e); } catch (IOException e) { Logger.debug(LOG_TAG, "I/O exception returned from execute."); if (!retryOnFailedRequest) { delegate.handleHttpIOException(e); } else { retryRequest(); } } catch (Exception e) { if (!retryOnFailedRequest) { delegate.handleHttpIOException(new IOException(e)); } else { retryRequest(); } } }
Source:
<code>public void markNotificationsAsRead() { if (this.getNumberOfUnreadNotifications() > 0) { if (this.markNotificationsAsReadThisWiki.isDisplayed()) { <START> this.clickAndWait(this.markNotificationsAsReadThisWiki); <END> } else { this.clickAndWait(this.markNotificationsAsRead); this.waitForElementVisibleByElement(this.markNotificationsAsReadAllWikis); this.clickAndWait(this.markNotificationsAsReadAllWikis); } this.waitForElementNotPresent(unreadNotificationReddot); } }</code><technical_language>do click Element</technical_language>

Target:
public void markNotificationsAsRead() { if (this.getNumberOfUnreadNotifications() > 0) { if (this.markNotificationsAsReadThisWiki.isDisplayed()) { this.scrollAndClick(this.markNotificationsAsReadThisWiki); } else { this.scrollAndClick(this.markNotificationsAsRead); this.waitForElementVisibleByElement(this.markNotificationsAsReadAllWikis); this.scrollAndClick(this.markNotificationsAsReadAllWikis); } this.waitForElementNotPresent(unreadNotificationReddot); } }
Source:
<code>public static void main(String[] args) { try { <START> final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); <END> final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.environment().getActiveDirectoryEndpoint()) .build(); Azure azure = Azure .configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); System.out.println("Selected subscription: " + azure.subscriptionId()); runSample(azure); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } }</code><technical_language>do add subId tenantId in samples</technical_language>

Target:
public static void main(String[] args) { try { final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE, true); final TokenCredential credential = new DefaultAzureCredentialBuilder() .authorityHost(profile.environment().getActiveDirectoryEndpoint()) .build(); Azure azure = Azure .configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credential, profile) .withDefaultSubscription(); System.out.println("Selected subscription: " + azure.subscriptionId()); runSample(azure); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } }