auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>CommitMessageWithCaretPosition calculateCommitMessageAndCaretPosition() { StringBuilder finalMessage = new StringBuilder(); int caretPosition = CommitMessageWithCaretPosition.DEFAULT_POSITION; for (ICommitMessageProvider provider : providers) { String messagePart = ""; try { if (provider instanceof ICommitMessageProvider2) { messagePart = getCommitMessage( (ICommitMessageProvider2) provider, finalMessage.length() == 0); } else { messagePart = getCommitMessage(provider, finalMessage.length() == 0); } caretPosition = getUpdatedCaretPosition(finalMessage, <START> caretPosition, provider); <END> } catch (RuntimeException e) { Activator.logError(e.getMessage(), e); } finalMessage.append(messagePart); } if (isCaretPositionSet) { return new CommitMessageWithCaretPosition(finalMessage.toString(), caretPosition); } else { return new CommitMessageWithCaretPosition(finalMessage.toString(), CommitMessageWithCaretPosition.DEFAULT_POSITION); } }</code><technical_language>This separation is awkward results in calling ICommitMessageProvider2 twice, is unnecessary returns message desired caret position in call</technical_language>

Target:
CommitMessageWithCaretPosition calculateCommitMessageAndCaretPosition() { StringBuilder finalMessage = new StringBuilder(); int caretPosition = CommitMessageWithCaretPosition.DEFAULT_POSITION; for (ICommitMessageProvider provider : providers) { String messagePart = ""; try { if (provider instanceof ICommitMessageProvider2) { CommitMessageWithCaretPosition commitMessageWithPosition = ((ICommitMessageProvider2) provider) .getCommitMessageWithPosition(resourcesArray); messagePart = getCommitMessage( commitMessageWithPosition, finalMessage.length() == 0); if (commitMessageWithPosition != null) { caretPosition = getUpdatedCaretPosition(finalMessage, caretPosition, commitMessageWithPosition, (ICommitMessageProvider2) provider); } } else { messagePart = getCommitMessage(provider, finalMessage.length() == 0); } } catch (RuntimeException e) { Activator.logError(e.getMessage(), e); } finalMessage.append(messagePart); } if (isCaretPositionSet) { return new CommitMessageWithCaretPosition(finalMessage.toString(), caretPosition); } else { return new CommitMessageWithCaretPosition(finalMessage.toString(), CommitMessageWithCaretPosition.DEFAULT_POSITION); } }
Source:
<code>public boolean hasPermission(String username, String permissionID) throws PermissionException { if (log.isDebugEnabled()) { <START> log.debug("Check permission " + permissionID); <END> } List<Role> roles = getRoles(username); return this.getPermissionsDAO().hasPermission(roles, permissionID); }</code><technical_language>@NisalaNiroshana , Provide more context debug log. Include username debug log</technical_language>

Target:
public boolean hasPermission(String username, String permissionID) throws PermissionException { if (log.isDebugEnabled()) { log.debug("Checking permission with ID " + permissionID + " for the username " + username); } List<Role> roles = getRoles(username); return this.getPermissionsDAO().hasPermission(roles, permissionID); }
Source:
<code>public void setValue(PersonAttribute personAttribute, String value) { PersonAttributeType attributeType = personAttribute.getAttributeType(); if(attributeType == null) { personAttribute.setValue(value); } else { try { <START> Class<?> clazz = Context.loadClass(personAttribute.getAttributeType().getFormat()); <END> if (Attributable.class.isAssignableFrom(clazz)) { Attributable instance = (Attributable) ConversionUtil.convert(value, clazz); if (instance != null) { personAttribute.setValue(instance.serialize()); } else { personAttribute.setValue(value); } } else { personAttribute.setValue(value); } } catch (ClassNotFoundException cnfe) { personAttribute.setValue(value); } catch (ConversionException ce) { personAttribute.setValue(value); } } }</code><technical_language>format is NULL</technical_language>

Target:
public void setValue(PersonAttribute personAttribute, String value) { PersonAttributeType attributeType = personAttribute.getAttributeType(); if(attributeType == null) { personAttribute.setValue(value); } else { try { String format = personAttribute.getAttributeType().getFormat(); if(format == null) { personAttribute.setValue(value); } else { Class<?> clazz = Context.loadClass(personAttribute.getAttributeType().getFormat()); if (Attributable.class.isAssignableFrom(clazz)) { Attributable instance = (Attributable) ConversionUtil.convert(value, clazz); if (instance != null) { personAttribute.setValue(instance.serialize()); } else { personAttribute.setValue(value); } } else { personAttribute.setValue(value); } } } catch (ClassNotFoundException cnfe) { personAttribute.setValue(value); } catch (ConversionException ce) { personAttribute.setValue(value); } } }
Source:
<code>private String resolveValue(String value) { StringBuffer valueBuffer = new StringBuffer(); Matcher jobParameterMatcher = OPERATOR_PATTERN.matcher(value); while (jobParameterMatcher.find()) { Matcher jobParameterKeyMatcher = PROPERTY_KEY_SEPERATOR.matcher(jobParameterMatcher.group(1)); if (jobParameterKeyMatcher.find()) { String propertyType = jobParameterMatcher.group(2); String extractedProperty = jobParameterKeyMatcher.group(1); Properties properties = propertyMap.get(propertyType); if(properties == null) { throw new IllegalArgumentException("Unknown property type: " + propertyType); } String resolvedProperty = properties.getProperty(extractedProperty, NULL); <START> if (LOG.isInfoEnabled()) { <END> if(NULL.equals(resolvedProperty)) { LOG.info(propertyType + " with key of: " + extractedProperty + " could not be resolved. Possible configuration error?"); } } jobParameterMatcher.appendReplacement(valueBuffer, resolvedProperty); } } jobParameterMatcher.appendTail(valueBuffer); String resolvedValue = valueBuffer.toString(); if (NULL.equals(resolvedValue)) { return ""; } return expressionParser.parseExpression(resolvedValue); }</code><technical_language>double check..</technical_language>

Target:
private String resolveValue(String value) { StringBuffer valueBuffer = new StringBuffer(); Matcher jobParameterMatcher = OPERATOR_PATTERN.matcher(value); while (jobParameterMatcher.find()) { Matcher jobParameterKeyMatcher = PROPERTY_KEY_SEPERATOR.matcher(jobParameterMatcher.group(1)); if (jobParameterKeyMatcher.find()) { String propertyType = jobParameterMatcher.group(2); String extractedProperty = jobParameterKeyMatcher.group(1); Properties properties = propertyMap.get(propertyType); if(properties == null) { throw new IllegalArgumentException("Unknown property type: " + propertyType); } String resolvedProperty = properties.getProperty(extractedProperty, NULL); if (NULL.equals(resolvedProperty)) { LOG.info(propertyType + " with key of: " + extractedProperty + " could not be resolved. Possible configuration error?"); } jobParameterMatcher.appendReplacement(valueBuffer, resolvedProperty); } } jobParameterMatcher.appendTail(valueBuffer); String resolvedValue = valueBuffer.toString(); if (NULL.equals(resolvedValue)) { return ""; } return expressionParser.parseExpression(resolvedValue); }
Source:
<code>public String letterify(String letterString, boolean isUpper) { StringBuffer sb = new StringBuffer(); <START> int baseChar = (isUpper) ? 65 : 97; END> for (int i = 0; i < letterString.length(); i++) { if (letterString.charAt(i) == '?') { sb.append((char) (baseChar + nextInt(26))); } else { sb.append(letterString.charAt(i)); } } return sb.toString(); }</code><technical_language>please perform extract method put common parts in method letterify methods call? Thanks</technical_language>

Target:
public String letterify(String letterString, boolean isUpper) { return letterHelper((isUpper) ? 65 : 97, letterString); }
Source:
<code>public @NonNull String getName() { <START> return ""; <END> }</code><technical_language>return test</technical_language>

Target:
public @NonNull String getName() { return "aspect name"; }
Source:
<code>private void updateGameMode(CommandSender sender, Player who, GameMode gameMode) { String gameModeName = GameModeUtils.prettyPrint(gameMode); who.setGameMode(gameMode); <START> who.setFallDistance(0); <END> if (!sender.equals(who)) { sender.sendMessage(who.getDisplayName() + "'s game mode has been updated to " + ChatColor.GRAY + "" + ChatColor.ITALIC + gameModeName + " Mode" + ChatColor.RESET); } who.sendMessage("Your game mode has been updated to " + ChatColor.GRAY + "" + ChatColor.ITALIC + gameModeName + " Mode" + ChatColor.RESET); }</code><technical_language>add this statement GlowPlayer#setGameMode method instead? way, this fix apply plugins changing a player's game mode</technical_language>

Target:
private void updateGameMode(CommandSender sender, Player who, GameMode gameMode) { String gameModeName = GameModeUtils.prettyPrint(gameMode); who.setGameMode(gameMode); if (!sender.equals(who)) { sender.sendMessage( who.getDisplayName() + "'s game mode has been updated to " + ChatColor.GRAY + "" + ChatColor.ITALIC + gameModeName + " Mode" + ChatColor.RESET); } who.sendMessage( "Your game mode has been updated to " + ChatColor.GRAY + "" + ChatColor.ITALIC + gameModeName + " Mode" + ChatColor.RESET); }
Source:
<code>private Map<Nucleotide, ArrayList<BaseQuality>> getPileupBaseQualities(final SamLocusIterator.LocusInfo locus) { <START> Map<Nucleotide, ArrayList<BaseQuality>> baseQualities = new HashMap<>(); <END> for (Nucleotide base : BASES) { baseQualities.put(base, new ArrayList<>()); } for (final SamLocusIterator.RecordAndOffset rec : locus.getRecordAndPositions()) { Nucleotide currentBase = Nucleotide.valueOf(rec.getReadBase()); ArrayList<BaseQuality> currentBaseQualityList = baseQualities.get(currentBase); if (currentBaseQualityList == null) { currentBaseQualityList = new ArrayList<>(); baseQualities.put(currentBase, currentBaseQualityList); } currentBaseQualityList.add(new BaseQuality( errorProbabilityAdjustmentFactor * QualityUtils.qualToErrorProb(rec.getBaseQuality()), errorProbabilityAdjustmentFactor * QualityUtils.qualToErrorProb(rec.getRecord().getMappingQuality())) ); } return baseQualities; }</code><technical_language>final</technical_language>

Target:
private Map<Nucleotide, List<BaseQuality>> getPileupBaseQualities(final SamLocusIterator.LocusInfo locus) { final Map<Nucleotide, List<BaseQuality>> baseQualities = locus.getRecordAndPositions().stream() .map(rp -> new ImmutablePair<>( Nucleotide.valueOf(rp.getReadBase()), new BaseQuality( errorProbabilityAdjustmentFactor * QualityUtils.qualToErrorProb(rp.getBaseQuality()), errorProbabilityAdjustmentFactor * QualityUtils.qualToErrorProb(rp.getRecord().getMappingQuality()) ) )).collect(Collectors.groupingBy( ImmutablePair::getLeft, Collectors.mapping(ImmutablePair::getRight, Collectors.toList())) ); for (final Nucleotide base : BASES) { if (!baseQualities.containsKey(base)) { baseQualities.put(base, new ArrayList<>()); } } return baseQualities; }
Source:
<code>private String collateCsvResults(HttpServletRequest request, Model model, Site site, MultiValueMap<String, String> params, Integer totalRows) throws IOException { StringBuilder resultsBuilder = new StringBuilder(); <START> Integer start = 0; <END> for (int i = 0; i < totalRows; i += MAXIMUM_SOLR_RESULT_COUNT) { final String rows = ((Integer) Math.min(MAXIMUM_SOLR_RESULT_COUNT, totalRows - i)).toString(); params.set("resultsPerPage", rows); params.set("start", start.toString()); if (!performValidSearch(request, model, site, params, true)) { throw new IOException("Invalid solr query. Please alter and try again."); } final Map<String, ?> searchResults = (Map<String, ?>) model.asMap().get("searchResults"); resultsBuilder.append(searchResults.get("stringResponse")); } return resultsBuilder.toString(); }</code><technical_language>start get assigned a new value? 0? If 0, a constant instead</technical_language>

Target:
private String collateCsvResults(HttpServletRequest request, Model model, Site site, MultiValueMap<String, String> params, Integer totalRows) throws IOException { StringBuilder resultsBuilder = new StringBuilder(); for (Integer start = 0; start < totalRows; start += MAXIMUM_SOLR_RESULT_COUNT) { final String rows = ((Integer) Math.min(MAXIMUM_SOLR_RESULT_COUNT, totalRows - start)).toString(); params.set("rows", rows); params.set("start", start.toString()); if (!performValidSearch(request, model, site, params, true)) { throw new IOException("Invalid solr query. Please alter and try again."); } final Map<String, ?> searchResults = (Map<String, ?>) model.asMap().get("searchResults"); resultsBuilder.append(searchResults.get("stringResponse")); } return resultsBuilder.toString(); }
Source:
<code>public FreeMarkerConfigurer freemarkerConfig(ServletContext servletContext) { FreeMarkerConfigurer configurer = new NGrinderFreeMarkerConfigure(); configurer.setTemplateLoaderPath("classpath:/templates/ftl/"); configurer.setPreferFileSystemAccess(false); <START> configurer.setDefaultEncoding("UTF-8"); <END> return configurer; }</code><technical_language>I this set spring application.properties creating bean explicitly</technical_language>

Target:
public FreeMarkerConfigurer freemarkerConfig(ServletContext servletContext) { FreeMarkerConfigurer configurer = new NGrinderFreeMarkerConfigure(); configurer.setTemplateLoaderPath("classpath:/templates/ftl/"); configurer.setPreferFileSystemAccess(false); configurer.setDefaultEncoding(defaultEncoding); return configurer; }
Source:
<code>void park(EnhancedQueueExecutor enhancedQueueExecutor, long nanos) { long start = System.nanoTime(); int spins = SPINS; ThreadLocalRandom tl = ThreadLocalRandom.current(); <START> while (spins > 0) { <END> if (tl.nextInt(spins) == 0) { Thread.yield(); } if (unsafe.compareAndSwapInt(this, parkedOffset, 2, 0)) { return; } if (System.nanoTime() - start > nanos) { return; } spins--; } long remaining = nanos - (System.nanoTime() - start); if (remaining < 0) { return; } try { if (unsafe.compareAndSwapInt(this, parkedOffset, 0, 1)) { LockSupport.parkNanos(enhancedQueueExecutor, remaining); } } finally { unsafe.compareAndSwapInt(this, parkedOffset, 1, 0); } }</code><technical_language>a random number? try a graduated system (spin for N times, yield for M times, park)? Also, try Runtime.onSpinWait() in variation? I want number of spins configurable, number of yields well. 1 CPU is detected, spin counts fixed 0. want onSpinWait usage (if any) configurable, pause duration is variable CPU families; ideally (eventually) able detect target CPU CPU count get a good guess optimum parameters if possible</technical_language>

Target:
void park(EnhancedQueueExecutor enhancedQueueExecutor, long nanos) { long start = System.nanoTime(); int spins = SPINS; ThreadLocalRandom tl = ThreadLocalRandom.current(); while (spins > 0) { if (tl.nextInt(SPINS) == 0) { Thread.yield(); } if (unsafe.compareAndSwapInt(this, parkedOffset, STATE_UNPARKED, STATE_NORMAL)) { return; } spins--; } long remaining = nanos - (System.nanoTime() - start); if (remaining < 0) { return; } try { if (unsafe.compareAndSwapInt(this, parkedOffset, STATE_NORMAL, STATE_PARKED)) { LockSupport.parkNanos(enhancedQueueExecutor, remaining); } } finally { unsafe.compareAndSwapInt(this, parkedOffset, STATE_PARKED, STATE_NORMAL); } }
Source:
<code>protected String getUrl(String serviceName) { String result = ""; try { result = getWebServiceProxyHelper().getUrlLocalHomeCommunity(serviceName); } catch (Exception ex) { <START> LOG.warn("Unable to retreive url for service: " + serviceName); <END> LOG.warn("Error: " + ex.getMessage(), ex); } return result; }</code><technical_language>extra log in here? combine 1</technical_language>

Target:
protected String getUrl(String serviceName) { String result = ""; try { result = getWebServiceProxyHelper().getUrlLocalHomeCommunity(serviceName); } catch (Exception ex) { LOG.warn("Unable to retreive url for service: Error: ", serviceName, ex.getMessage(), ex); } return result; }
Source:
<code>List<Boolean> resolveBooleanExpressions(List<String> expressions, Entity entity) { if (expressions.isEmpty()) { return Collections.emptyList(); } <START> Bindings bindings = jsMagmaScriptEvaluator.createBindings(entity); <END> List<Boolean> validationResults = new ArrayList<>(expressions.size()); for (String expression : expressions) { Object value = jsMagmaScriptEvaluator.eval(bindings, expression); validationResults.add(value != null ? Boolean.valueOf(value.toString()) : null); } return validationResults; }</code><technical_language>This introduces a dependency Java scripting API. Is this desirable</technical_language>

Target:
List<Boolean> resolveBooleanExpressions(List<String> expressions, Entity entity) { if (expressions.isEmpty()) { return Collections.emptyList(); } return jsMagmaScriptEvaluator.eval(expressions, entity) .stream() .map(this::convertToBoolean) .collect(toList()); }
Source:
<code>public PathBuilder path(final String pathFragment) { if (pathFragment == null) { return this; } <START> if (!pathFragment.startsWith("/") && !currentPathEndsWith('/')) { <END> this.path.append("/").append(pathFragment); } else if(!pathFragment.startsWith("/") && currentPathEndsWith('/')) { this.path.append(pathFragment); } else if(pathFragment.startsWith("/") && !currentPathEndsWith('/')) { this.path.append(pathFragment); } else if(pathFragment.startsWith("/") && currentPathEndsWith('/') && pathFragment.length() > 1) { this.path.append(pathFragment.substring(1)); } else if(pathFragment.startsWith("/") && this.path.toString().length() == 0) { this.path.append(pathFragment); } else { } return this; }</code><technical_language>in terms of code readability easier if cases grouped (conditions repeated): if (pathFragment.startsWith("/") { if (currentPathEndsWith('/') { ... } else { } } else { ... }</technical_language>

Target:
public PathBuilder path(final String pathFragment) { if (pathFragment == null) { return this; } if (!pathFragment.startsWith("/")) { if (!currentPathEndsWith('/')) { this.path.append("/").append(pathFragment); } else if (currentPathEndsWith('/')) { this.path.append(pathFragment); } } else { if (!currentPathEndsWith('/')) { this.path.append(pathFragment); } else if (currentPathEndsWith('/') && pathFragment.length() > 1) { this.path.append(pathFragment.substring(1)); } else if (this.path.toString().length() == 0) { this.path.append(pathFragment); } } return this; }
Source:
<code>public void testDeleteRecursive() throws Exception { final File tmpDir = tmp.getRoot(); final File dir = new File(tmpDir, "dir"); final File d1 = new File(dir, "d1"); final File d2 = new File(dir, "d2"); final File f1 = new File(dir, "f1"); final File d1f1 = new File(d1, "d1f1"); final File d2f2 = new File(d2, "d1f2"); try { mkdirs(dir, d1, d2); mkfiles(f1, d1f1, d2f2); Util.deleteRecursive(dir); assertFalse("dir exists", dir.exists()); mkdirs(dir, d1, d2); mkfiles(f1, d1f1, d2f2); lockFileForDeletion(d1f1); try { Util.deleteRecursive(dir); fail("Expected IOException"); } catch (IOException x) { assertTrue("dir exists", dir.exists()); assertTrue("d1 exists", d1.exists()); assertTrue("d1f1 exists", d1f1.exists()); assertThat(x.getMessage(), containsString(dir.getPath())); } unlockFilesForDeletion(); } finally { unlockFilesForDeletion(); <START> Util.deleteRecursive(tmpDir); <END> } }</code><technical_language>TemporaryFolder care of this</technical_language>

Target:
public void testDeleteRecursive() throws Exception { final File dir = tmp.newFolder(); final File d1 = new File(dir, "d1"); final File d2 = new File(dir, "d2"); final File f1 = new File(dir, "f1"); final File d1f1 = new File(d1, "d1f1"); final File d2f2 = new File(d2, "d1f2"); mkdirs(dir, d1, d2); mkfiles(f1, d1f1, d2f2); Util.deleteRecursive(dir); assertFalse("dir exists", dir.exists()); }
Source:
<code>private boolean isSequenceElementChange(Notification notification) { boolean isSequenceElement = isSequenceElement(notification.getNotifier()); <START> Object value = null; <END> Object newValue = notification.getNewValue(); if (newValue instanceof EObject) { value = newValue; } else { Object oldValue = notification.getOldValue(); if (oldValue instanceof EObject) { value = oldValue; } } if (value != null) { boolean valueIsSequenceElt = false; if (value instanceof EObject) { valueIsSequenceElt = isSequenceElement(value); } else if (value instanceof Collection<?>) { Collection<?> values = (Collection<?>) value; for (Object val : values) { if (isSequenceElement(val)) { valueIsSequenceElt = true; break; } } } isSequenceElement = isSequenceElement && valueIsSequenceElt; } return isSequenceElement; }</code><technical_language>Add a condition isSequenceElement, code is unnecessary if isSequenceElement == false</technical_language>

Target:
private boolean isSequenceElementChange(Notification notification) { boolean isSequenceElement = isSequenceElement(notification.getNotifier()); Object value = getValue(notification); if (value != null) { boolean valueIsSequenceElt = false; if (value instanceof EObject) { valueIsSequenceElt = isSequenceElement(value); } else if (value instanceof Collection<?>) { Collection<?> values = (Collection<?>) value; for (Object val : values) { if (isSequenceElement(val)) { valueIsSequenceElt = true; break; } } } isSequenceElement = isSequenceElement && valueIsSequenceElt; } return isSequenceElement; }
Source:
<code>public boolean isValid(AddSeriesDto dto, ConstraintValidatorContext context) { if (dto == null) { return true; } <START> LocalDate today = LocalDate.now(); <END> if (yearInFuture(today, dto)) { rejectField(context, "year"); return false; } if (yearAndMonthInFuture(today, dto)) { rejectField(context, "month"); return false; } if (dateInFuture(today, dto)) { rejectField(context, "day"); return false; } return true; }</code><technical_language>Ok, move this methods, benefits of extracting here. :)</technical_language>

Target:
public boolean isValid(AddSeriesDto dto, ConstraintValidatorContext context) { if (dto == null) { return true; } if (yearInFuture(dto)) { rejectField(context, "year"); return false; } if (yearAndMonthInFuture(dto)) { rejectField(context, "month"); return false; } if (dateInFuture(dto)) { rejectField(context, "day"); return false; } return true; }
Source:
<code>protected boolean validate() { if (!super.validate()) { return false; } DiskImage image = imagesHandler.getVolumeInfoFromVdsm(getStoragePoolId(), getStorageDomainId(), getImageGroupId(), getParameters().getDestinationImageId()); <START> return validate(isLeaf(image)); <END> }</code><technical_language>I missing something, this fail if removing internal snapshot</technical_language>

Target:
protected boolean validate() { if (!super.validate()) { return false; } if (!imagesHandler.hasCorrectVolType(getStoragePoolId(), getStorageDomainId(), getImageGroupId(), getParameters().getDestinationImageId())) { return failValidation(EngineMessage.ACTION_TYPE_FAILED_IMAGE_IS_NOT_A_LEAF); } return true; }
Source:
<code>private void addWatchdogActions(VersionCaps version, WatchdogAction[] values) { <START> if (VersionUtils.greaterOrEqual(version, VERSION_3_2)) { <END> version.setWatchdogActions(new WatchdogActions()); for (WatchdogAction watchdogAction : values) { version.getWatchdogActions().getWatchdogActions().add(watchdogAction.value()); } } }</code><technical_language>this is 3.3 feature, 3.2</technical_language>

Target:
private void addWatchdogActions(VersionCaps version, WatchdogAction[] values) { if (VersionUtils.greaterOrEqual(version, VERSION_3_3)) { version.setWatchdogActions(new WatchdogActions()); for (WatchdogAction watchdogAction : values) { version.getWatchdogActions().getWatchdogActions().add(watchdogAction.value()); } } }
Source:
<code>public void unloadFromTransportShip(Unit u) { <START> if (removeTransportedUnit(u)) { <END> double unitWeight; if (u.getEntity().getUnitType() == UnitType.INFANTRY) { unitWeight = calcInfantryBayWeight(u.getEntity()); } else { unitWeight = u.getEntity().getWeight(); } if (u.hasTransportShipAssignment()) { updateBayCapacity(u.getEntity().getUnitType(), unitWeight, true, u.getTransportShipAssignment().getBayNumber()); } u.setTransportShipAssignment(null); } }</code><technical_language>case a unit is assigned this transport unit transport ship</technical_language>

Target:
public void unloadFromTransportShip(Unit u) { Objects.requireNonNull(u); removeTransportedUnit(u); if (u.hasTransportShipAssignment() && u.getTransportShipAssignment().getTransportShip().equals(this)) { double unitWeight; if (u.getEntity().getUnitType() == UnitType.INFANTRY) { unitWeight = calcInfantryBayWeight(u.getEntity()); } else { unitWeight = u.getEntity().getWeight(); } updateBayCapacity(u.getEntity().getUnitType(), unitWeight, true, u.getTransportShipAssignment().getBayNumber()); u.setTransportShipAssignment(null); } }
Source:
<code>private Invocable lazyGetTemplateInvocable() { if (templateInvocable == null) { <START> synchronized(this) { <END> templateInvocable = newTemplateInvocable(params); } } return templateInvocable; }</code><technical_language>synchronized is unnecessary Context is (must be) instanciated for thread. purpose of Context class is making invokeTemplate single-threaded</technical_language>

Target:
private Invocable lazyGetTemplateInvocable() { if (templateInvocable == null) { templateInvocable = newTemplateInvocable(params); } return templateInvocable; }
Source:
<code>public static final List<BriefcaseFormDefinition> getBriefcaseFormList() { List<BriefcaseFormDefinition> formsList = new ArrayList<BriefcaseFormDefinition>(); File forms = FileSystemUtils.getFormsFolder(); if (forms.exists()) { File[] formDirs = forms.listFiles(); for (File f : formDirs) { if (f.isDirectory()) { try { File formFile = new File(f, f.getName() + ".xml"); String formFileHash = getMd5Hash(formFile); String existingFormFileHash = String.valueOf(pathToHashMap.get(formFile.getAbsolutePath())); <START> BriefcaseFormDefinition existingDefinition = (BriefcaseFormDefinition) pathToDefinitionMap.get(formFile.getAbsolutePath()); <END> if (existingFormFileHash == null || existingDefinition == null || !existingFormFileHash.equalsIgnoreCase(formFileHash)) { pathToHashMap.put(formFile.getAbsolutePath(), formFileHash); existingDefinition = new BriefcaseFormDefinition(f, formFile); pathToDefinitionMap.put(formFile.getAbsolutePath(), existingDefinition); } formsList.add(existingDefinition); } catch (BadFormDefinition e) { e.printStackTrace(); } } else { f.delete(); } } } return formsList; }</code><technical_language>Redundant cast</technical_language>

Target:
public static final List<BriefcaseFormDefinition> getBriefcaseFormList() { List<BriefcaseFormDefinition> formsList = new ArrayList<BriefcaseFormDefinition>(); File forms = FileSystemUtils.getFormsFolder(); if (forms.exists()) { File[] formDirs = forms.listFiles(); for (File f : formDirs) { if (f.isDirectory()) { try { File formFile = new File(f, f.getName() + ".xml"); String formFileHash = getMd5Hash(formFile); String existingFormFileHash = String.valueOf(CacheUtils.getFormFileMd5Hash(formFile.getAbsolutePath())); BriefcaseFormDefinition existingDefinition = CacheUtils.getFormFileFormDefinition(formFile.getAbsolutePath()); if (existingFormFileHash == null || existingDefinition == null || !existingFormFileHash.equalsIgnoreCase(formFileHash)) { CacheUtils.putFormFileMd5Hash(formFile.getAbsolutePath(), formFileHash); existingDefinition = new BriefcaseFormDefinition(f, formFile); CacheUtils.putFormFileFormDefinition(formFile.getAbsolutePath(), existingDefinition); } formsList.add(existingDefinition); } catch (BadFormDefinition e) { log.debug("bad form definition", e); } } else { f.delete(); } } } return formsList; }
Source:
<code>public OutputView(OutputController controller) { super(controller); this.controller.getModel().addJobOutputListener(this); this.noOutputMessage = "No output available<br><br><br>" + "Click <strong>Finished Tasks Output</strong> to retrieve logs for already finished tasks. For all the finished Tasks within the Job, or for the selected Task. The command does work when Job is still in Running state, as well as when Job is Finished. In case of large number of Tasks (over 20), because the Tasks are paginated, when Selected Job is activated, it will add to the display the logs of the current page of Tasks.<br><br>"+ <START> "Use <strong>Streaming Output</strong> to auto-fetch logs for running tasks of the entire Job. You cannot select a specific Task in the streaming mode. If you activate streaming while some Tasks are already finished, you will get the logs of those Tasks as well."; <END> this.refreshButtonLabel = "Finished Tasks Output"; this.refreshButtonTooltip = "Request fetching the logs for finished tasks of the entire Job, or for a selected Task"; }</code><technical_language>this sentence ("In case of large.... ) is long clear. Please reformulate 2 sentences</technical_language>

Target:
public OutputView(OutputController controller) { super(controller); this.controller.getModel().addJobOutputListener(this); this.noOutputMessage = "No output available<br><br><br>" + "Click <strong>Finished Tasks Output</strong> to retrieve logs for already finished tasks within the Job, or for the selected Task. The command does work when Job is still in Running state, as well as when Job is Finished. In case of large number of Tasks (over 20), the command displays only the logs of the current page of Tasks.<br><br>" + "Use <strong>Streaming Output</strong> to auto-fetch logs for running tasks of the entire Job. You cannot select a specific Task in the streaming mode. If you activate streaming while some Tasks are already finished, you will get the logs of those Tasks as well."; this.refreshButtonLabel = "Finished Tasks Output"; this.refreshButtonTooltip = "Request fetching the logs for finished tasks of the entire Job, or for a selected Task"; }
Source:
<code>private static PCollection<Read> getReadsFromAPI() throws IOException { final String rgsId = pipelineOptions.getReadGroupSetId(); LOG.info("Sharded reading of ReadGroupSet: " + rgsId); List<StreamReadsRequest> requests = Lists.newArrayList(); if (pipelineOptions.isAllReferences()) { requests.addAll(ShardUtils.getReadRequests(rgsId, SexChromosomeFilter.INCLUDE_XY, pipelineOptions.getBasesPerShard(), auth)); } else { requests.addAll( ShardUtils.getReadRequests(Collections.singletonList(rgsId), pipelineOptions.getReferences(), pipelineOptions.getBasesPerShard())); } <START> LOG.info("Reading form the API with: "+ requests.size() + " shards"); <END> PCollection<Read> reads = pipeline.apply(Create.of(requests)) .apply(new ReadStreamer(auth, ShardBoundary.Requirement.STRICT, null)); return reads; }</code><technical_language>s/"+/" + extra space</technical_language>

Target:
private static PCollection<Read> getReadsFromAPI() throws IOException { final String rgsId = pipelineOptions.getReadGroupSetId(); LOG.info("Sharded reading of ReadGroupSet: " + rgsId); List<StreamReadsRequest> requests = Lists.newArrayList(); if (pipelineOptions.isAllReferences()) { requests.addAll(ShardUtils.getReadRequests(rgsId, SexChromosomeFilter.INCLUDE_XY, pipelineOptions.getBasesPerShard(), auth)); } else { requests.addAll( ShardUtils.getReadRequests(Collections.singletonList(rgsId), pipelineOptions.getReferences(), pipelineOptions.getBasesPerShard())); } LOG.info("Reading from the API with: " + requests.size() + " shards"); PCollection<Read> reads = pipeline.apply(Create.of(requests)) .apply(new ReadStreamer(auth, ShardBoundary.Requirement.STRICT, null)); return reads; }
Source:
<code><START> private Region resolveRegion(String id) throws IOException { <END> ChannelGroup<?> channelGroup = resolveChannelGroup(id); if (channelGroup instanceof Platform) { return (Region) channelGroup; } else { Throwables.propagate(new NotAcceptableException( String.format( "%s is a channel group of type '%s', should be 'region", id, channelGroup ) )); return null; } }</code><technical_language>Optional<Region> instead of null please</technical_language>

Target:
private Region resolveRegion(String id) throws IOException { ChannelGroup<?> channelGroup = resolveChannelGroup(id); if (channelGroup instanceof Region) { return (Region) channelGroup; } else { throw new RuntimeException(new NotAcceptableException( String.format( "%s is a channel group of type '%s', should be 'region", id, channelGroup ) )); } }
Source:
<code>public BaseShadowSystem (NearFarAnalyzer nearFarAnalyzer, ShadowMapAllocator allocator, DirectionalAnalyzer directionalAnalyzer, LightFilter lightFilter) { this.nearFarAnalyzer = nearFarAnalyzer; this.allocator = allocator; this.directionalAnalyzer = directionalAnalyzer; this.lightFilter = lightFilter; frameBuffers = new FrameBuffer[getPassQuantity()]; passShaderProviders = new ShaderProvider[getPassQuantity()]; <START> init(); <END> }</code><technical_language>Calling a protected method in constructor of base class is a good idea ;)</technical_language>

Target:
public BaseShadowSystem (NearFarAnalyzer nearFarAnalyzer, ShadowMapAllocator allocator, DirectionalAnalyzer directionalAnalyzer, LightFilter lightFilter) { this.nearFarAnalyzer = nearFarAnalyzer; this.allocator = allocator; this.directionalAnalyzer = directionalAnalyzer; this.lightFilter = lightFilter; }
Source:
<code><START> public static Long getWSClientConnectionTimeout() throws Exception { <END> String defaultTimeout = "60000"; String inputTimeout = System.getProperty(WS_CLIENT_CONNECTION_TIME_VALUE); if (inputTimeout != null) { try { long timeout = Long.parseLong(inputTimeout); if (timeout > 0) { return new Long(inputTimeout); } } catch (Exception exception) { throw new RuntimeException("Webservice client connection timeout value '" + inputTimeout + "' is invalid", exception); } } return new Long(defaultTimeout); }</code><technical_language>beeter int type</technical_language>

Target:
public static int getWSClientConnectionTimeout() throws Exception { int defaultTimeout = 60000; String inputTimeout = System.getProperty(WS_CLIENT_CONNECTION_TIME_VALUE); if (inputTimeout != null) { try { int timeout = Integer.parseInt(inputTimeout); if (timeout > 0) { return timeout; } } catch (Exception exception) { throw new RuntimeException("Webservice client connection timeout value '" + inputTimeout + "' is invalid", exception); } } return defaultTimeout; }
Source:
<code>public void fireEvent(ExecEvent eo) { List<ISessionEventListener> v; synchronized (this) { if (_listeners.size() == 0) { return; } v = new ArrayList<>(_listeners); } for (Object aV : v) { <START> ISessionEventListener target = (ISessionEventListener) aV; <END> try { target.sessionUpdate(eo); } catch (Exception ex) { LOG.log(Level.SEVERE, "Couldn't invoke method sessionUpdate() on " + target, ex); } } }</code><technical_language>java for (ISessionEventListener target : v) { ... }</technical_language>

Target:
public void fireEvent(ExecEvent eo) { List<ISessionEventListener> v; synchronized (this) { if (_listeners.size() == 0) { return; } v = new ArrayList<>(_listeners); } for (ISessionEventListener target : v) { try { target.sessionUpdate(eo); } catch (Exception ex) { LOG.log(Level.SEVERE, "Couldn't invoke method sessionUpdate() on " + target, ex); } } }
Source:
<code>public static <T> T getParameterValue(final WorkflowActionClassParameter parameter) { T paramValue = null; try { paramValue = (T) parameter.getValue(); <START> } catch (Exception e) { <END> } return paramValue; }</code><technical_language>![MINOR](<LINK_2> 'Severity: MINOR') Catch a list of specific exception subtypes instead. [![rule](<LINK_1>](<LINK_0></technical_language>

Target:
public static <T> T getParameterValue(final WorkflowActionClassParameter parameter) { T paramValue = null; try { if (null != parameter && UtilMethods.isSet(parameter.getValue())) { paramValue = (T) parameter.getValue(); } } catch (Exception e) { Logger.debug(WorkflowActionletUtil.class, "Value of parameter '" + parameter.getId() + "' could not be returned.", e); } return paramValue; }
Source:
<code>private static String toHostName(String inetAddressStringRepresentation) { try { String[] parts = inetAddressStringRepresentation.split("/"); <START> String ip = parts[parts.length - 1]; <END> InetAddress addr = InetAddress.getByName(ip); return addr.getHostName(); } catch (UnknownHostException e) { return inetAddressStringRepresentation; } }</code><technical_language>2 lines try-catch block, wdyt</technical_language>

Target:
private static String toHostName(String inetAddressStringRepresentation) { String[] parts = inetAddressStringRepresentation.split("/"); String ip = parts[parts.length - 1]; try { InetAddress addr = InetAddress.getByName(ip); return addr.getHostName(); } catch (UnknownHostException e) { return inetAddressStringRepresentation; } }
Source:
<code>private void syncLunsForBlockStorageDomains() { Collection<VDS> hosts = new LinkedList<>(vdsDao.getAllForStoragePoolAndStatus( getStoragePool().getId(), VDSStatus.Up)); <START> if (hosts.isEmpty()) { return; } <END> Collection<StorageDomain> unSyncedStorageDomains = syncLunsForStorageDomains(storageDomainDao.getAllForStoragePool(getStoragePoolId()), hosts); if (!unSyncedStorageDomains.isEmpty()) { String unSyncedStorageDomainsList = unSyncedStorageDomains.stream() .map(StorageDomain::getId) .map(Guid::toString) .collect(Collectors.joining(", ")); addCustomValue("StorageDomainsIds", unSyncedStorageDomainsList); auditLogDirector.log(this, AuditLogType.STORAGE_DOMAINS_COULD_NOT_BE_SYNCED); } }</code><technical_language>If hosts for this op, warn domains synched</technical_language>

Target:
private void syncLunsForBlockStorageDomains() { if (getOldStoragePool().getCompatibilityVersion().lessOrEquals(Version.v4_0) && getStoragePool().getCompatibilityVersion().greaterOrEquals(Version.v4_1)) { Collection<StorageDomain> unSyncedStorageDomains = syncLunsForStorageDomains(storageDomainDao.getAllForStoragePool(getStoragePoolId())); if (!unSyncedStorageDomains.isEmpty()) { String unSyncedStorageDomainsList = unSyncedStorageDomains.stream() .map(StorageDomain::getId) .map(Guid::toString) .collect(Collectors.joining(", ")); addCustomValue("StorageDomainsIds", unSyncedStorageDomainsList); auditLogDirector.log(this, AuditLogType.STORAGE_DOMAINS_COULD_NOT_BE_SYNCED); } } }
Source:
<code>public Map<String, Integer> getNumberOpenedSockets() { Map<String, Integer> numberOpenedSocketByUri = new LinkedHashMap<>(); <START> for (Map.Entry<String, List<Socket>> socketByUri : socketsByUri.entrySet()) { <END> numberOpenedSocketByUri.put(socketByUri.getKey(), socketByUri.getValue().size()); } return numberOpenedSocketByUri; }</code><technical_language>protected concurrent accesses</technical_language>

Target:
public Map<String, Integer> getNumberOpenedSockets() { Map<String, Integer> numberOpenedSocketByUri = new LinkedHashMap<>(); synchronized (this) { for (Map.Entry<String, List<Socket>> socketByUri : socketsByUri.entrySet()) { numberOpenedSocketByUri.put(socketByUri.getKey(), socketByUri.getValue().size()); } } return numberOpenedSocketByUri; }
Source:
<code>private void onPreviewImage(DocDisplay docDisplay, String href, Position position, Range tokenRange) { String srcPath = href; if (!href.startsWith("http")) { srcPath = href.startsWith("~/") <START> ? "files/" + href.substring(2) <END> : "file_show?path=" + StringUtil.encodeURIComponent(href); } String encoded = StringUtil.encodeURIComponent(srcPath); Element el = Document.get().getElementById(encoded); if (el != null) return; ImageElement imgEl = Document.get().createImageElement(); imgEl.setAttribute("src", srcPath); imgEl.getStyle().setProperty("maxWidth", "100px"); ScreenCoordinates coordinates = docDisplay.documentPositionToScreenCoordinates(position); AnchoredPopupPanel panel = new AnchoredPopupPanel(docDisplay, tokenRange); panel.getElement().setId(encoded); panel.getElement().appendChild(imgEl); panel.setPopupPosition(coordinates.getPageX(), coordinates.getPageY() + 20); panel.show(); }</code><technical_language>do need do special for Windows directory separators</technical_language>

Target:
private void onPreviewImage(DocDisplay docDisplay, String href, Position position, Range tokenRange) { String srcPath = imgSrcPathFromHref(href); String encoded = StringUtil.encodeURIComponent(srcPath); Element el = Document.get().getElementById(encoded); if (el != null) return; AnchoredPopupPanel panel = new AnchoredPopupPanel(docDisplay, tokenRange, srcPath); panel.getElement().setId(encoded); ScreenCoordinates coordinates = docDisplay.documentPositionToScreenCoordinates(position); panel.setPopupPosition(coordinates.getPageX(), coordinates.getPageY() + 20); panel.show(); }
Source:
<code>public boolean isUnset(String key) { <START> Attribute a = map.get(key); return a != null ? a.getState() == State.UNSET : false; <END> }</code><technical_language>question</technical_language>

Target:
public boolean isUnset(String key) { return (getState(key) == State.UNSET); }
Source:
<code>protected String gatherRevision(ExecutionEvent event) throws ExecutionException { Repository repository = getRepository(true, event); try { final RevWalk walk = new RevWalk(repository); ObjectId commitId = repository.resolve(repository.getFullBranch()); <START> RevCommit commit = walk.parseCommit(commitId); <END> int parentCount = commit.getParentCount(); if (parentCount == 0) { MessageDialog .openError( getShell(event), UIText.ReplaceWithPreviousActionHandler_NoParentCommitDialogTitle, UIText.ReplaceWithPreviousActionHandler_NoParentCommitDialogMessage); throw new OperationCanceledException(); } else if (parentCount > 1) { List<RevCommit> commits = new ArrayList<RevCommit>(); for (int i = 0; i < parentCount; i++) commits.add(walk.parseCommit(commit.getParent(i))); CommitSelectDialog dlg = new CommitSelectDialog( getShell(event), commits); if (dlg.open() == Window.OK) return dlg.getSelectedCommit().getName(); else throw new OperationCanceledException(); } else return commit.getParent(0).getName(); } catch (IOException e) { throw new ExecutionException(e.getMessage(), e); } }</code><technical_language>A path limited RevWalk is needed find commit modified file selected path else previous commit exact version of file HEAD version. CompareWithPreviousActionHandler for example use</technical_language>

Target:
protected String gatherRevision(ExecutionEvent event) throws ExecutionException { Repository repository = getRepository(true, event); IResource[] resources = getSelectedResources(event); if (resources.length != 1) throw new ExecutionException( "Unexpected number of selected Resources"); try { List<RevCommit> previousCommits = findPreviousCommits(repository, resources[0]); int parentCount = previousCommits.size(); if (parentCount == 0) { MessageDialog .openError( getShell(event), UIText.ReplaceWithPreviousActionHandler_NoParentCommitDialogTitle, UIText.ReplaceWithPreviousActionHandler_NoParentCommitDialogMessage); throw new OperationCanceledException(); } else if (parentCount > 1) { CommitSelectDialog dlg = new CommitSelectDialog( getShell(event), previousCommits); if (dlg.open() == Window.OK) return dlg.getSelectedCommit().getName(); else throw new OperationCanceledException(); } else return previousCommits.get(0).getName(); } catch (IOException e) { throw new ExecutionException(e.getMessage(), e); } }
Source:
<code>public BlobUtils(AzureClient client, String containerName, String blobName, long length) { this.blobClient = client.getBlobClient(); try { this.container = blobClient.getContainerReference(containerName); <START> container.createIfNotExists(); <END> this.blob = container.getPageBlobReference(blobName); if (!blob.exists()) { blob.create(length); } } catch (URISyntaxException e) { LOG.error("Container name: " + containerName + " or blob name: " + blobName + " invalid.", e); throw new AzureException(e); } catch (StorageException e) { LOG.error("Azure Storage Exception!", e); throw new AzureException(e); } }</code><technical_language>QQ: create container processor holds lease blob? I looked Azure JobCoordinator, I want multiple clients competing create blob</technical_language>

Target:
public BlobUtils(AzureClient client, String containerName, String blobName, long length) { this.blobClient = client.getBlobClient(); try { this.container = blobClient.getContainerReference(containerName); container.createIfNotExists(); this.blob = container.getPageBlobReference(blobName); if (!blob.exists()) { blob.create(length, AccessCondition.generateIfNotExistsCondition(), null, null); } } catch (URISyntaxException e) { LOG.error("Container name: " + containerName + " or blob name: " + blobName + " invalid.", e); throw new AzureException(e); } catch (StorageException e) { int httpStatusCode = e.getHttpStatusCode(); if (httpStatusCode == HttpStatus.CONFLICT_409) { LOG.info("The blob you're trying to create exists already.", e); } else { LOG.error("Azure Storage Exception!", e); throw new AzureException(e); } } }
Source:
<code>public void editFeedbackResponseComment(String commentIdSuffix, String newCommentText) { <START> executeScript("scroll(0,300)"); <END> WebElement commentRow = waitForElementPresence(By.id("responseCommentRow" + commentIdSuffix)); click(commentRow.findElements(By.tagName("a")).get(1)); WebElement commentEditForm = browser.driver.findElement(By.id("responseCommentEditForm" + commentIdSuffix)); fillRichTextEditor("responsecommenttext" + commentIdSuffix, newCommentText); click(commentEditForm.findElement(By.className("col-sm-offset-5")).findElement(By.tagName("a"))); ThreadHelper.waitFor(1000); }</code><technical_language>a need for this line</technical_language>

Target:
public void editFeedbackResponseComment(String commentIdSuffix, String newCommentText) { WebElement commentRow = waitForElementPresence(By.id("responseCommentRow" + commentIdSuffix)); click(commentRow.findElements(By.tagName("a")).get(1)); WebElement commentEditForm = browser.driver.findElement(By.id("responseCommentEditForm" + commentIdSuffix)); fillRichTextEditor("responsecommenttext" + commentIdSuffix, newCommentText); click(commentEditForm.findElement(By.className("col-sm-offset-5")).findElement(By.tagName("a"))); ThreadHelper.waitFor(1000); }
Source:
<code>private static void runCheckCodeStyle(Map<String, Path> paths) { Optional<ValidationResult> validationResult = executor.runCheckCodeStyle(paths.get(EXERCISE_PATH)); if (validationResult.isPresent()) { JsonWriter.writeObjectIntoJsonFormat(validationResult.get(), paths.get(OUTPUT_PATH)); System.out.println("Codestyle report can be found at " + paths.get(OUTPUT_PATH)); } else { <START> System.out.println("ERROR: Something went wrong, could not output validation result!"); <END> } }</code><technical_language>Please print status messages System.err. generally good practice, nice try System.out clean in case want a command outputs JSON stdout</technical_language>

Target:
private static void runCheckCodeStyle(Map<String, Path> paths) { ValidationResult validationResult = null; try { validationResult = executor.runCheckCodeStyle(paths.get(EXERCISE_PATH)); } catch (NoLanguagePluginFoundException e) { printErrAndExit("ERROR: Could not find suitable language plugin for the given exercise path."); } try { JsonWriter.writeObjectIntoJsonFormat(validationResult, paths.get(OUTPUT_PATH)); System.out.println("Codestyle report can be found at " + paths.get(OUTPUT_PATH)); } catch (IOException e) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, "Could not write result into given output file", e); printErrAndExit("ERROR: Could not write the results to the given file."); } }
Source:
<code>public void testExcludeTable() throws Exception { <START> MaxwellAbstractRowsEvent e; <END> List<RowMap> list; MaxwellFilter filter = new MaxwellFilter(); filter.excludeTable("minimal"); list = getRowsForSQL(filter, insertSQL, createDBs); assertThat(list.size(), is(1)); assertThat(list.get(0).getTable(), is("bars")); }</code><technical_language>remove unused 'e's</technical_language>

Target:
public void testExcludeTable() throws Exception { List<RowMap> list; MaxwellFilter filter = new MaxwellFilter(); filter.excludeTable("minimal"); list = getRowsForSQL(filter, insertSQL, createDBs); assertThat(list.size(), is(1)); assertThat(list.get(0).getTable(), is("bars")); }
Source:
<code>public static void execShell(String command) { String[] args = { "/system/bin/sh", "-c", command }; try { <START> Libcore.os.execv("/system/bin/sh", args); <END> } catch (ErrnoException e) { throw new RuntimeException(e); } }</code><technical_language>(args[0], args)</technical_language>

Target:
public static void execShell(String command) { String[] args = { "/system/bin/sh", "-c", command }; try { Libcore.os.execv(args[0], args); } catch (ErrnoException e) { throw new RuntimeException(e); } }