auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void parseSingleRuleNode(RuleSetReferenceId ruleSetReferenceId, RuleSetBuilder ruleSetBuilder, Node ruleNode) throws ClassNotFoundException, InstantiationException, IllegalAccessException { Element ruleElement = (Element) ruleNode; if (StringUtils.isNotBlank(ruleSetReferenceId.getRuleName()) && !isRuleName(ruleElement, ruleSetReferenceId.getRuleName())) { return; } <START> Rule rule = new RuleFactory().buildRule(ruleElement, resourceLoader); <END> rule.setRuleSetName(ruleSetBuilder.getName()); ruleSetBuilder.addRule(rule); }</code><technical_language>add constructors in RuleFactory? * RuleFactory() - default constructor for compatibility * RuleFactory(ResourceLoader) - new I think, resource loader a property of rule factory a method argument for parsing rule element. In theory, reuse RuleFactory instance for parsing rules ruleset (which do currently)</technical_language>

Target:
private void parseSingleRuleNode(RuleSetReferenceId ruleSetReferenceId, RuleSetBuilder ruleSetBuilder, Node ruleNode) throws ClassNotFoundException, InstantiationException, IllegalAccessException { Element ruleElement = (Element) ruleNode; if (StringUtils.isNotBlank(ruleSetReferenceId.getRuleName()) && !isRuleName(ruleElement, ruleSetReferenceId.getRuleName())) { return; } Rule rule = new RuleFactory(resourceLoader).buildRule(ruleElement); rule.setRuleSetName(ruleSetBuilder.getName()); ruleSetBuilder.addRule(rule); }
Source:
<code>private boolean loadMediaInfo() { Log.d(TAG, "Loading media info"); <START> if (controller != null) { <END> Playable media = controller.getMedia(); if (media != null) { txtvTitle.setText(media.getEpisodeTitle()); mFeedName.setText(media.getFeedTitle()); onPositionObserverUpdate(); Glide.with(getActivity()) .load(media.getImageLocation()) .placeholder(R.color.light_gray) .error(R.color.light_gray) .diskCacheStrategy(ApGlideSettings.AP_DISK_CACHE_STRATEGY) .fitCenter() .dontAnimate() .into(imgvCover); fragmentLayout.setVisibility(View.VISIBLE); if (controller.isPlayingVideoLocally()) { butPlay.setVisibility(View.GONE); } else { butPlay.setVisibility(View.VISIBLE); } return true; } else { Log.w(TAG, "loadMediaInfo was called while the media object of playbackService was null!"); return false; } } else { Log.w(TAG, "loadMediaInfo was called while playbackService was null!"); return false; } }</code><technical_language>please invert</technical_language>

Target:
private boolean loadMediaInfo() { Log.d(TAG, "Loading media info"); if (controller == null) { Log.w(TAG, "loadMediaInfo was called while PlaybackController was null!"); return false; } Playable media = controller.getMedia(); if (media != null) { txtvTitle.setText(media.getEpisodeTitle()); mFeedName.setText(media.getFeedTitle()); onPositionObserverUpdate(); Glide.with(getActivity()) .load(media.getImageLocation()) .placeholder(R.color.light_gray) .error(R.color.light_gray) .diskCacheStrategy(ApGlideSettings.AP_DISK_CACHE_STRATEGY) .fitCenter() .dontAnimate() .into(imgvCover); fragmentLayout.setVisibility(View.VISIBLE); if (controller.isPlayingVideoLocally()) { butPlay.setVisibility(View.GONE); } else { butPlay.setVisibility(View.VISIBLE); } return true; } else { Log.w(TAG, "loadMediaInfo was called while the media object of playbackService was null!"); return false; } }
Source:
<code>public Simulation cloneSimulation() { Simulation toReturn = new Simulation(); this.scenarios.forEach(scenario -> toReturn.scenarios.add(scenario.cloneScenario())); final List<FactMapping> originalFactMappings = this.simulationDescriptor.getUnmodifiableFactMappings(); for (int i = 0; i < originalFactMappings.size(); i++) { final FactMapping originalFactMapping = originalFactMappings.get(i); final FactIdentifier clonedFactIdentifier = originalFactMapping.getFactIdentifier().cloneFactIdentifier(); <START> final ExpressionIdentifier clonedExpressionIdentifier = originalFactMapping.getExpressionIdentifier().cloneExpressionIdentifier(); <END> final FactMapping clonedFactMapping = toReturn.simulationDescriptor.addFactMapping(i, clonedFactIdentifier, clonedExpressionIdentifier); clonedFactMapping.setFactAlias(originalFactMapping.getFactAlias()); clonedFactMapping.setExpressionAlias(originalFactMapping.getExpressionAlias()); originalFactMapping.getExpressionElements().forEach(expressionElement -> clonedFactMapping.getExpressionElements().add(new ExpressionElement(expressionElement.getStep()))); } return toReturn; }</code><technical_language>clonedFactIdentifier clonedExpressionIdentifier needed</technical_language>

Target:
public Simulation cloneSimulation() { Simulation toReturn = new Simulation(); this.scenarios.forEach(scenario -> toReturn.scenarios.add(scenario.cloneScenario())); final List<FactMapping> originalFactMappings = this.simulationDescriptor.getUnmodifiableFactMappings(); for (int i = 0; i < originalFactMappings.size(); i++) { final FactMapping originalFactMapping = originalFactMappings.get(i); toReturn.simulationDescriptor.addFactMapping(i, originalFactMapping); } return toReturn; }
Source:
<code>public Payload(final Object data, final Visibility visibility, final String visibilityId) { if(null == data){ <START> this.type = Object.class.getName(); <END> }else{ this.type = data.getClass().getName(); } this.data = data; this.visibility = visibility; this.visibilityId = visibilityId; }</code><technical_language>object class?, set type null a idea</technical_language>

Target:
public Payload(final Object data, final Visibility visibility, final String visibilityId) { this.type = data.getClass().getName(); this.data = data; this.visibility = visibility; this.visibilityId = visibilityId; }
Source:
<code>private boolean fileIsInRepository(AbstractFile file) throws TskCoreException { if (fileRepositoryLookupCache.containsKey(file.getId())) { return fileRepositoryLookupCache.get(file.getId()).equals(FileRepoState.EXISTS); } if (file.getSha256Hash() == null || file.getSha256Hash().isEmpty()) { throw new TskCoreException("Missing SHA-256 hash for file " + file.getName() + "(ID: " + file.getId() + ")"); } try { boolean exists = FileRepository.exists(file); if (exists) { fileRepositoryLookupCache.put(file.getId(), FileRepoState.EXISTS); } else { fileRepositoryLookupCache.put(file.getId(), FileRepoState.DOES_NOT_EXIST); } return exists; } catch (IOException | FileRepositoryException ex) { <START> throw new TskCoreException("Error looking up file in file repository"); <END> } }</code><technical_language>Exception is dropped</technical_language>

Target:
private boolean fileIsInRepository(AbstractFile file) throws TskCoreException { if (fileRepositoryLookupCache.containsKey(file.getId())) { return fileRepositoryLookupCache.get(file.getId()).equals(FileRepoState.EXISTS); } if (file.getSha256Hash() == null || file.getSha256Hash().isEmpty()) { throw new TskCoreException("Missing SHA-256 hash for file " + file.getName() + "(ID: " + file.getId() + ")"); } try { boolean exists = FileRepository.exists(file); if (exists) { fileRepositoryLookupCache.put(file.getId(), FileRepoState.EXISTS); } else { fileRepositoryLookupCache.put(file.getId(), FileRepoState.DOES_NOT_EXIST); } return exists; } catch (IOException | FileRepositoryException ex) { throw new TskCoreException("Error looking up file in file repository", ex); } }
Source:
<code>protected void updateURLInformation() { <START> String url = serverUrlCombo.getText(); <END> apiKey.setToolTipText( NLS.bind(Messages.BugzillaRestRepositorySettingsPage_Please_create_or_copy_the_API_Key_from, url)); apiKeyLabel.setToolTipText( NLS.bind(Messages.BugzillaRestRepositorySettingsPage_Please_create_or_copy_the_API_Key_from, url)); apikeyPreferenceLink.setText(url + userprefs); apikeyPreferenceLink .setToolTipText(NLS.bind(Messages.BugzillaRestRepositorySettingsPage_View_your_apikey_settings, url)); apikeyPreferenceLink.setEnabled(TasksUiInternal.isValidUrl(url + userprefs)); }</code><technical_language>url = serverUrl + userprefs, full URL place API key</technical_language>

Target:
protected void updateURLInformation() { String url = serverUrlCombo.getText() + userprefs; apiKey.setToolTipText( NLS.bind(Messages.BugzillaRestRepositorySettingsPage_Please_create_or_copy_the_API_Key_from, url)); apiKeyLabel.setToolTipText( NLS.bind(Messages.BugzillaRestRepositorySettingsPage_Please_create_or_copy_the_API_Key_from, url)); apikeyPreferenceLink.setText(url); apikeyPreferenceLink .setToolTipText(NLS.bind(Messages.BugzillaRestRepositorySettingsPage_View_your_apikey_settings, url)); apikeyPreferenceLink.setEnabled(TasksUiInternal.isValidUrl(url)); }
Source:
<code>public void deleteEntity(WebContext ctx, Optional<? extends BaseEntity<?>> optionalEntity) { if (ctx.isSafePOST()) { optionalEntity.ifPresent(entity -> { if (entity.getDescriptor().isComplexDelete() && Sirius.isFrameworkEnabled(Processes.FRAMEWORK_PROCESSES)) { <START> Processes processes = globalContext.getPart(Processes.class); <END> String processId = processes.createProcessForCurrentUser("delete-entity", NLS.fmtr("BizController.deleteProcessTitle") .set("entity", Strings.limit(entity, 30)) .format(), "fa-trash", Collections.emptyMap()); tasks.defaultExecutor().fork(() -> { processes.execute(processId, process -> { process.log(ProcessLog.info() .withNLSKey("BizController.startDelete") .withContext("entity", String.valueOf(entity))); entity.getDescriptor().getMapper().delete(entity); process.log(ProcessLog.success().withNLSKey("BizController.deleteCompleted")); }); }); UserContext.message(Message.info(NLS.get("BizController.deletingInBackground")) .withAction("/ps/" + processId, NLS.get("BizController.deleteProcess"))); } else { entity.getDescriptor().getMapper().delete(entity); showDeletedMessage(); } }); } }</code><technical_language>real part</technical_language>

Target:
public void deleteEntity(WebContext ctx, Optional<? extends BaseEntity<?>> optionalEntity) { if (ctx.isSafePOST()) { optionalEntity.ifPresent(entity -> { if (entity.getDescriptor().isComplexDelete() && processes != null) { deleteComplexEntity(entity); } else { entity.getDescriptor().getMapper().delete(entity); showDeletedMessage(); } }); } }
Source:
<code>public ImmutableSet<EventClass> outgoingEvents() { AggregateClass<A> aggregateClass = aggregateClass(); SetView<EventClass> eventClasses = <START> union(aggregateClass.outgoingEvents(), aggregateClass.importableEvents()); <END> return eventClasses.immutableCopy(); }</code><technical_language>extract this union+immutableCopy AggregateClass itself</technical_language>

Target:
public ImmutableSet<EventClass> outgoingEvents() { return aggregateClass().outgoingEvents(); }
Source:
<code>private static String escapeSpecialCharacters(String str) { StringBuilder builder = new StringBuilder(); for (int j = 0; j < str.length(); j++) { char c = str.charAt(j); <START> if (c == '%') { <END> builder.append('%'); } if (contains(c, SPECIAL_CHARS)) { builder.append('^'); } builder.append(c); } return builder.toString(); }</code><technical_language>add % SPECIAL_CHARS avoid additional if</technical_language>

Target:
private static String escapeSpecialCharacters(String str) { StringBuilder builder = new StringBuilder(); for (int j = 0; j < str.length(); j++) { char c = str.charAt(j); if (c == PERCENT_CHAR) { builder.append(PERCENT_CHAR); } if (contains(c, SPECIAL_CHARS)) { builder.append(ESCAPE_CHAR); } builder.append(c); } return builder.toString(); }
Source:
<code>public void testGetProjectedSchema1() throws Exception { MessageType originalMsg = MessageTypeParser.parseMessageType( "message hive_schema {\n" + " optional group structCol {\n" + " optional int32 a;\n" + " optional double b;\n" + " optional boolean c;\n" + " optional fixed_len_byte_array(3) d (DECIMAL(5,2));\n" + " }\n" + "}\n"); testConversion("structCol", "struct<a:int>", DataWritableReadSupport .getProjectedSchema(originalMsg, Arrays.asList("structCol"), Arrays.asList(0), <START> new HashSet<>(Arrays.asList("structCol.a"))).toString()); <END> }</code><technical_language>Hint: readable is simply google Guava importing com.google.common.collect.Sets: Set<String> StringSet = Sets.newHashSet("structCol.a"); other test cases</technical_language>

Target:
public void testGetProjectedSchema1() throws Exception { MessageType originalMsg = MessageTypeParser.parseMessageType( "message hive_schema {\n" + " optional group structCol {\n" + " optional int32 a;\n" + " optional double b;\n" + " optional boolean c;\n" + " optional fixed_len_byte_array(3) d (DECIMAL(5,2));\n" + " }\n" + "}\n"); testConversion("structCol", "struct<a:int>", DataWritableReadSupport .getProjectedSchema(originalMsg, Arrays.asList("structCol"), Arrays.asList(0), Sets.newHashSet("structCol.a")).toString()); }
Source:
<code>public CloudBigtableTableConfiguration build() { return new CloudBigtableTableConfiguration(projectId, zoneId, clusterId, tableId, <START> additionalConfigurations); <END> }</code><technical_language>singular is good here, IMHO</technical_language>

Target:
public CloudBigtableTableConfiguration build() { return new CloudBigtableTableConfiguration(projectId, zoneId, clusterId, tableId, additionalConfiguration); }
Source:
<code>public String getMissingRunTypeClass() { if (null != dataFile && dataFile.getMissingRunTypes().size() > 0) { <START> return "show"; <END> } return "hidden"; }</code><technical_language>This shown</technical_language>

Target:
public String getMissingRunTypeClass() { if (null != dataFile && dataFile.getMissingRunTypes().size() > 0) { return "shown"; } return "hidden"; }
Source:
<code>public List<String> getInvalidityInfo() { <START> return null; <END> }</code><technical_language>Return empty list instead</technical_language>

Target:
public List<String> getInvalidityInfo() { return new ArrayList<String>(); }
Source:
<code>public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { try { MediaType mediaType = ContentNegotiationResolver.INSTANCE.getContentType(request, response, supportedMediaTypes); if (MediaType.APPLICATION_JSON.equals(mediaType)) { <START> request.getRequestDispatcher("/me").forward(request, response); <END> } else { request.getSession().setAttribute(FormController.SPRING_SECURITY_AUTHENTICATION_FAILED_KEY, errorModelFactory.toError(request, exception)); this.delegate.onAuthenticationFailure(request, response, exception); } } catch (UnresolvedMediaTypeException ex) { log.error("Couldn't resolve media type: {}", ex.getMessage(), ex); } finally { FailedAuthenticationRequestEvent event = createFailureEvent(request, response, exception); publisher.publish(event); } }</code><technical_language>uri of endpoint configured stormpath.web.me.uri. @dogeared requested, do change</technical_language>

Target:
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { try { MediaType mediaType = ContentNegotiationResolver.INSTANCE.getContentType(request, response, supportedMediaTypes); if (MediaType.APPLICATION_JSON.equals(mediaType)) { request.getRequestDispatcher(meUri).forward(request, response); } else { request.getSession().setAttribute(FormController.SPRING_SECURITY_AUTHENTICATION_FAILED_KEY, errorModelFactory.toError(request, exception)); this.delegate.onAuthenticationFailure(request, response, exception); } } catch (UnresolvedMediaTypeException ex) { log.error("Couldn't resolve media type: {}", ex.getMessage(), ex); } finally { FailedAuthenticationRequestEvent event = createFailureEvent(request, response, exception); publisher.publish(event); } }
Source:
<code>public static void main(String[] args) throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.option(ChannelOption.SO_BACKLOG, 1024); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new HttpNativeServerInitializer()); b.bind(PORT).sync().channel(); <START> System.err.println("Server started, will shutdown now."); <END> System.exit(0); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }</code><technical_language>@pmlopes call channel.close().sync()</technical_language>

Target:
public static void main(String[] args) throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); boolean serverStartSucess = false; try { ServerBootstrap b = new ServerBootstrap(); b.option(ChannelOption.SO_BACKLOG, 1024); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new HttpNativeServerInitializer()); Channel channel = b.bind(0).sync().channel(); System.err.println("Server started, will shutdown now."); channel.close().sync(); serverStartSucess = true; } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } System.exit(serverStartSucess ? 0 : 1); }
Source:
<code>ColorBuffer getOutputString(Rows rows, Rows.Row row, String delim) { ColorBuffer buf = beeLine.getColorBuffer(); for (int i = 0; i < row.values.length; i++) { if (buf.getVisibleLength() > 0) { buf.green(delim); } <START> if (row.values[i] == null) { <END> continue; } ColorBuffer v; if (row.isMeta) { v = beeLine.getColorBuffer().center(row.values[i], row.sizes[i]); if (rows.isPrimaryKey(i)) { buf.cyan(v.getMono()); } else { buf.bold(v.getMono()); } } else { v = beeLine.getColorBuffer().pad(row.values[i], row.sizes[i]); if (rows.isPrimaryKey(i)) { buf.cyan(v.getMono()); } else { buf.append(v.getMono()); } } } if (row.deleted) { buf = beeLine.getColorBuffer().red(buf.getMono()); } else if (row.updated) { buf = beeLine.getColorBuffer().blue(buf.getMono()); } else if (row.inserted) { buf = beeLine.getColorBuffer().green(buf.getMono()); } return buf; }</code><technical_language>In apache/master, "SELECT 'Upgrading MetaStore schema 2.1.0 2.2.0' MESSAGE;" issue description in jira. I think, skipping row based null values is incorrect other side effect</technical_language>

Target:
ColorBuffer getOutputString(Rows rows, Rows.Row row, String delim) { ColorBuffer buf = beeLine.getColorBuffer(); for (int i = 0; i < row.values.length; i++) { if (buf.getVisibleLength() > 0) { buf.green(delim); } ColorBuffer v; if (row.isMeta) { v = beeLine.getColorBuffer().center(row.values[i], row.sizes[i]); if (rows.isPrimaryKey(i)) { buf.cyan(v.getMono()); } else { buf.bold(v.getMono()); } } else { v = beeLine.getColorBuffer().pad(row.values[i], row.sizes[i]); if (rows.isPrimaryKey(i)) { buf.cyan(v.getMono()); } else { buf.append(v.getMono()); } } } if (row.deleted) { buf = beeLine.getColorBuffer().red(buf.getMono()); } else if (row.updated) { buf = beeLine.getColorBuffer().blue(buf.getMono()); } else if (row.inserted) { buf = beeLine.getColorBuffer().green(buf.getMono()); } return buf; }
Source:
<code>protected void addInTarget(AttributeChange diff, boolean rightToLeft) { final Match match = diff.getMatch(); final EObject expectedContainer; if (rightToLeft) { expectedContainer = match.getLeft(); } else { expectedContainer = match.getRight(); } if (expectedContainer == null) { } else { final Comparison comparison = match.getComparison(); final EStructuralFeature attribute = diff.getAttribute(); final Object expectedValue = diff.getValue(); if (attribute.isMany()) { final int insertionIndex = findInsertionIndex(comparison, diff, rightToLeft); <START> final List<Object> targetList = (List<Object>)safeEGet(expectedContainer, attribute); <END> addAt(targetList, expectedValue, insertionIndex); } else { safeESet(expectedContainer, attribute, expectedValue); } } }</code><technical_language>please split changes in another review</technical_language>

Target:
protected void addInTarget(AttributeChange diff, boolean rightToLeft) { final Match match = diff.getMatch(); final EObject expectedContainer; if (rightToLeft) { expectedContainer = match.getLeft(); } else { expectedContainer = match.getRight(); } if (expectedContainer == null) { } else { final Comparison comparison = match.getComparison(); final EStructuralFeature attribute = diff.getAttribute(); final Object expectedValue = diff.getValue(); if (attribute.isMany()) { final int insertionIndex = findInsertionIndex(comparison, diff, rightToLeft); final List<Object> targetList = (List<Object>)expectedContainer.eGet(attribute); addAt(targetList, expectedValue, insertionIndex); } else { expectedContainer.eSet(attribute, expectedValue); } } }
Source:
<code>public void testStartOvertime_default() { <START> ClockModel pc = sbm.getClockModel(Clock.ID_PERIOD); <END> ClockModel jc = sbm.getClockModel(Clock.ID_JAM); ClockModel lc = sbm.getClockModel(Clock.ID_LINEUP); ClockModel tc = sbm.getClockModel(Clock.ID_TIMEOUT); ClockModel ic = sbm.getClockModel(Clock.ID_INTERMISSION); ((DefaultSettingsModel) sbm.getSettings()).set("Clock." + Clock.ID_LINEUP + ".OvertimeTime", "60000"); assertFalse(pc.isRunning()); pc.setTime(0); assertTrue(pc.isTimeAtEnd()); pc.setNumber(pc.getMaximumNumber()); assertFalse(jc.isRunning()); jc.setTime(0); assertTrue(jc.isTimeAtEnd()); assertFalse(lc.isRunning()); lc.setMaximumTime(30000); assertFalse(tc.isRunning()); ic.start(); sbm.startOvertime(); advance(0); assertTrue(sbm.isInOvertime()); assertFalse(pc.isRunning()); assertFalse(jc.isRunning()); assertTrue(lc.isRunning()); assertEquals(60000, lc.getMaximumTime()); assertFalse(tc.isRunning()); assertFalse(ic.isRunning()); }</code><technical_language>part of object, a lot</technical_language>

Target:
public void testStartOvertime_default() { (sbm.getSettingsModel()).set("Clock." + Clock.ID_LINEUP + ".OvertimeTime", "60000"); assertFalse(pc.isRunning()); pc.setTime(0); assertTrue(pc.isTimeAtEnd()); pc.setNumber(pc.getMaximumNumber()); assertFalse(jc.isRunning()); jc.setTime(0); assertTrue(jc.isTimeAtEnd()); assertFalse(lc.isRunning()); lc.setMaximumTime(30000); assertFalse(tc.isRunning()); ic.start(); sbm.startOvertime(); advance(0); assertTrue(sbm.isInOvertime()); assertFalse(pc.isRunning()); assertFalse(jc.isRunning()); assertTrue(lc.isRunning()); assertEquals(60000, lc.getMaximumTime()); assertFalse(tc.isRunning()); assertFalse(ic.isRunning()); }
Source:
<code>private static void setUpPingForChannel(final Channel channel, int timeoutSeconds, int intervalSeconds) { final AtomicBoolean isInClosed = new AtomicBoolean(false); final PingThread t = new PingThread(channel, timeoutSeconds * 1000L, intervalSeconds * 1000L) { protected void onDead(Throwable cause) { try { for (PingFailureAnalyzer pfa : PingFailureAnalyzer.all()) { pfa.onPingFailure(channel,cause); } if (isInClosed.get()) { LOGGER.log(FINE,"Ping failed after the channel "+channel.getName()+" is already partially closed.",cause); } else { LOGGER.log(INFO,"Ping failed. Terminating the channel "+channel.getName()+".",cause); channel.close(cause); } } catch (IOException e) { LOGGER.log(SEVERE,"Failed to terminate the channel "+channel.getName(),e); } } protected void onDead() { onDead(null); } }; channel.addListener(new Channel.Listener() { @Override public void onClosed(Channel channel, IOException cause) { LOGGER.fine("Terminating ping thread for " + channel.getName()); isInClosed.set(true); t.interrupt(); } }); t.start(); LOGGER.fine("Ping thread started for " + channel + " with a " + <START> intervalSeconds + " second interval and a " + timeoutSeconds + " second timeout."); <END> }</code><technical_language>change slow logging</technical_language>

Target:
static void setUpPingForChannel(final Channel channel, int timeoutSeconds, int intervalSeconds) { final AtomicBoolean isInClosed = new AtomicBoolean(false); final PingThread t = new PingThread(channel, timeoutSeconds * 1000L, intervalSeconds * 1000L) { protected void onDead(Throwable cause) { try { for (PingFailureAnalyzer pfa : PingFailureAnalyzer.all()) { pfa.onPingFailure(channel,cause); } if (isInClosed.get()) { LOGGER.log(Level.FINE,"Ping failed after the channel "+channel.getName()+" is already partially closed.",cause); } else { LOGGER.log(Level.INFO,"Ping failed. Terminating the channel "+channel.getName()+".",cause); channel.close(cause); } } catch (IOException e) { LOGGER.log(Level.SEVERE,"Failed to terminate the channel "+channel.getName(),e); } } protected void onDead() { onDead(null); } }; channel.addListener(new Channel.Listener() { @Override public void onClosed(Channel channel, IOException cause) { LOGGER.fine("Terminating ping thread for " + channel.getName()); isInClosed.set(true); t.interrupt(); } }); t.start(); LOGGER.log(Level.FINE, "Ping thread started for {0} with a {1} second interval and a {2} second timeout.", new Object[] { channel, intervalSeconds, timeoutSeconds }); }
Source:
<code>public BaseSRXControlledSubsystem( String systemName, int masterChannel, boolean invertMaster, boolean invertMasterSensor, WPIFactory factory, PIDPropertyManager pidPropertyManager, XPropertyManager propManager){ <START> log.info("Creating " + systemName + " system"); <END> this.pidPropertyManager = pidPropertyManager; this.systemName = systemName; this.masterChannel = masterChannel; systemSpeedThresh = propManager.createPersistentProperty(systemName + " nominal speed thresh (TPC)", 1); systemCurrentSpeed = propManager.createEphemeralProperty(systemName + " current speed (TPC)", 0); systemTargetSpeed = propManager.createEphemeralProperty(systemName + " goal speed (TPC)", 0); systemOutputPower = propManager.createEphemeralProperty(systemName + " voltage", 0); atSpeedProp = propManager.createEphemeralProperty("Is" + systemName + " at speed?", false); systemTalonError = propManager.createEphemeralProperty(systemName + " speed error", 0); enablesystemLogging = propManager.createEphemeralProperty("Is " + systemName + " logging enabled?", false); masterMotor = factory.getCANTalonSpeedController(masterChannel); initializeMotorConfiguration(invertMaster, invertMasterSensor); masterMotor.createTelemetryProperties(systemName + " master", propManager); }</code><technical_language>Call super(name);</technical_language>

Target:
public BaseSRXControlledSubsystem( String systemName, int masterChannel, boolean invertMaster, boolean invertMasterSensor, WPIFactory factory, PIDPropertyManager pidPropertyManager, XPropertyManager propManager){ super(systemName); log.info("Creating " + systemName + " system"); this.pidPropertyManager = pidPropertyManager; this.systemName = systemName; this.masterChannel = masterChannel; systemSpeedThresh = propManager.createPersistentProperty(systemName + " nominal speed thresh (TPC)", 1); systemCurrentSpeed = propManager.createEphemeralProperty(systemName + " current speed (TPC)", 0); systemTargetSpeed = propManager.createEphemeralProperty(systemName + " goal speed (TPC)", 0); systemOutputPower = propManager.createEphemeralProperty(systemName + " voltage", 0); atSpeedProp = propManager.createEphemeralProperty("Is" + systemName + " at speed?", false); systemTalonError = propManager.createEphemeralProperty(systemName + " speed error", 0); enablesystemLogging = propManager.createEphemeralProperty("Is " + systemName + " logging enabled?", false); masterMotor = factory.getCANTalonSpeedController(masterChannel); initializeMasterMotorConfiguration(invertMaster, invertMasterSensor); masterMotor.createTelemetryProperties(systemName + " master", propManager); }
Source:
<code>private String getAdditionalXmsHeaders(Map<String, String> headers) { final List<String> xmsHeaderNameArray = headers.entrySet().stream() .filter(entry -> entry.getKey().toLowerCase(Locale.ROOT).startsWith("x-ms-")) .filter(entry -> entry.getValue() != null) .map(Map.Entry::getKey) .collect(Collectors.toList()); if (xmsHeaderNameArray.isEmpty()) { return ""; } <START> Collections.sort(xmsHeaderNameArray, Collator.getInstance()); <END> final StringBuilder canonicalizedHeaders = new StringBuilder(); for (final String key : xmsHeaderNameArray) { if (canonicalizedHeaders.length() > 0) { canonicalizedHeaders.append('\n'); } canonicalizedHeaders.append(key.toLowerCase(Locale.ROOT)) .append(':') .append(headers.get(key)); } return canonicalizedHeaders.toString(); }</code><technical_language>Collator.getInstance(Locale) ? this local machine JVM default expect. I guess en_US safe choice</technical_language>

Target:
private String getAdditionalXmsHeaders(Map<String, String> headers) { final List<String> xmsHeaderNameArray = headers.entrySet().stream() .filter(entry -> entry.getKey().toLowerCase(Locale.ROOT).startsWith("x-ms-")) .filter(entry -> entry.getValue() != null) .map(Map.Entry::getKey) .collect(Collectors.toList()); if (xmsHeaderNameArray.isEmpty()) { return ""; } Collections.sort(xmsHeaderNameArray, Collator.getInstance(Locale.ROOT)); final StringBuilder canonicalizedHeaders = new StringBuilder(); for (final String key : xmsHeaderNameArray) { if (canonicalizedHeaders.length() > 0) { canonicalizedHeaders.append('\n'); } canonicalizedHeaders.append(key.toLowerCase(Locale.ROOT)) .append(':') .append(headers.get(key)); } return canonicalizedHeaders.toString(); }
Source:
<code>public MantaClient(final ConfigContext config, final MantaConnectionFactoryConfigurator connectionFactoryConfigurator) { dumpConfig(config); ConfigContext.validate(config); this.url = config.getMantaURL(); this.config = config; this.home = ConfigContext.deriveHomeDirectoryFromUser(config.getMantaUser()); this.beanSupervisor = new MantaMBeanSupervisor(); final KeyPair keyPair = new KeyPairFactory(config).createKeyPair(); final Signer.Builder builder = new Signer.Builder(keyPair); if (BooleanUtils.isTrue(config.disableNativeSignatures())) { builder.providerCode("stdlib"); } final ThreadLocalSigner signer = new ThreadLocalSigner(builder); this.signerRef = new WeakReference<>(signer); final MantaConnectionFactory connectionFactory = new MantaConnectionFactory( config, keyPair, signer, connectionFactoryConfigurator); final MantaApacheHttpClientContext connectionContext = new MantaApacheHttpClientContext(connectionFactory); if (BooleanUtils.isTrue(config.isClientEncryptionEnabled())) { this.httpHelper = new EncryptionHttpHelper(connectionContext, config); } else { this.httpHelper = new StandardHttpHelper(connectionContext, config); } this.uriSigner = new UriSigner(this.config, keyPair, signer); <START> this.beanSupervisor = new MantaMBeanSupervisor(); <END> beanSupervisor.expose(this.config); beanSupervisor.expose(connectionFactory); this.findForkJoinPool = FindForkJoinPoolFactory.getInstance(config); }</code><technical_language>unsure this connects fork-join related changes</technical_language>

Target:
public MantaClient(final ConfigContext config, final MantaConnectionFactoryConfigurator connectionFactoryConfigurator) { dumpConfig(config); ConfigContext.validate(config); this.url = config.getMantaURL(); this.config = config; this.home = ConfigContext.deriveHomeDirectoryFromUser(config.getMantaUser()); final KeyPair keyPair = new KeyPairFactory(config).createKeyPair(); final Signer.Builder builder = new Signer.Builder(keyPair); if (BooleanUtils.isTrue(config.disableNativeSignatures())) { builder.providerCode("stdlib"); } final ThreadLocalSigner signer = new ThreadLocalSigner(builder); this.signerRef = new WeakReference<>(signer); final MantaConnectionFactory connectionFactory = new MantaConnectionFactory( config, keyPair, signer, connectionFactoryConfigurator); final MantaApacheHttpClientContext connectionContext = new MantaApacheHttpClientContext(connectionFactory); if (BooleanUtils.isTrue(config.isClientEncryptionEnabled())) { this.httpHelper = new EncryptionHttpHelper(connectionContext, config); } else { this.httpHelper = new StandardHttpHelper(connectionContext, config); } this.uriSigner = new UriSigner(this.config, keyPair, signer); this.beanSupervisor = new MantaMBeanSupervisor(); beanSupervisor.expose(this.config); beanSupervisor.expose(connectionFactory); this.findForkJoinPool = FindForkJoinPoolFactory.getInstance(config); }
Source:
<code>public Map<IProject, IProject[]> getDanglingReferences() { IProject[] projects = getRoot().getProjects(IContainer.INCLUDE_HIDDEN); Map<IProject, IProject[]> result = new HashMap<>(projects.length); for (IProject project : projects) { if (!project.isAccessible()) continue; IProject[] refs = ((Project)project).internalGetDescription().getReferencedProjects(false); List<IProject> dangling = new ArrayList<>(refs.length); for (IProject ref : <START> refs) <END> if (!ref.exists()) dangling.add(ref); if (!dangling.isEmpty()) result.put(project, dangling.toArray(new IProject[dangling.size()])); } return result; }</code><technical_language>If touching this code, add curly braces if/for conditions</technical_language>

Target:
public Map<IProject, IProject[]> getDanglingReferences() { IProject[] projects = getRoot().getProjects(IContainer.INCLUDE_HIDDEN); Map<IProject, IProject[]> result = new HashMap<>(projects.length); for (IProject project : projects) { if (!project.isAccessible()) { continue; } IProject[] refs = ((Project)project).internalGetDescription().getReferencedProjects(false); List<IProject> dangling = new ArrayList<>(refs.length); for (IProject ref : refs) { if (!ref.exists()) { dangling.add(ref); } } if (!dangling.isEmpty()) { result.put(project, dangling.toArray(new IProject[dangling.size()])); } } return result; }
Source:
<code>public PackFile(final File packFile, Iterable<PackExt> extensions) { this.packFile = packFile; this.packLastModified = (int) (packFile.lastModified() >> 10); <START> this.extensions = new ArrayList<PackExt>(PackExt.values().length); <END> for (PackExt ext : extensions) { this.extensions.add(ext); } hash = System.identityHashCode(this) * 31; length = Long.MAX_VALUE; }</code><technical_language>I thought talked making this a BitSet somehow. PackExt a static int counts PackExts created declared. Change constructor instead a static factory method automatically registers PackExt VALUES array assigns a unique bit. Assume permit 32 PackExts for now. a simple int is a bit set of PackExts present</technical_language>

Target:
public PackFile(final File packFile, Iterable<PackExt> extensions) { this.packFile = packFile; this.packLastModified = (int) (packFile.lastModified() >> 10); int bits = 0; for (PackExt ext : extensions) bits |= 1 << ext.getPosition(); this.extensions = bits; hash = System.identityHashCode(this) * 31; length = Long.MAX_VALUE; }
Source:
<code>public GeofenceCircle(String wkt) throws ParseException { super(); <START> fromWKT(wkt); <END> }</code><technical_language>Please camel case. fromWkt</technical_language>

Target:
public GeofenceCircle(String wkt) throws ParseException { fromWkt(wkt); }
Source:
<code>public static Set<String> getRequiredFields(Query query) { Set<String> dimensions = new HashSet<>(); Set<String> dimsInFilter = getDimensionsInFilter(query.getFilter()); if (dimsInFilter != null) { dimensions.addAll(dimsInFilter); } if (query instanceof TopNQuery) { TopNQuery q = (TopNQuery) query; dimensions.addAll(extractFieldsFromAggregations(q.getAggregatorSpecs())); dimensions.add(q.getDimensionSpec().getDimension()); } else if (query instanceof TimeseriesQuery) { TimeseriesQuery q = (TimeseriesQuery) query; dimensions.addAll(extractFieldsFromAggregations(q.getAggregatorSpecs())); } else if (query instanceof GroupByQuery) { GroupByQuery q = (GroupByQuery) query; dimensions.addAll(extractFieldsFromAggregations(q.getAggregatorSpecs())); for (DimensionSpec spec : q.getDimensions()) { String dim = spec.getDimension(); dimensions.add(dim); } } return dimensions; <START> } <END></code><technical_language>Please throw exception if query type is unknown</technical_language>

Target:
public static Set<String> getRequiredFields(Query query) { Set<String> dimensions = new HashSet<>(); Set<String> dimsInFilter = getDimensionsInFilter(query.getFilter()); if (dimsInFilter != null) { dimensions.addAll(dimsInFilter); } if (query instanceof TopNQuery) { TopNQuery q = (TopNQuery) query; dimensions.addAll(extractFieldsFromAggregations(q.getAggregatorSpecs())); dimensions.add(q.getDimensionSpec().getDimension()); } else if (query instanceof TimeseriesQuery) { TimeseriesQuery q = (TimeseriesQuery) query; dimensions.addAll(extractFieldsFromAggregations(q.getAggregatorSpecs())); } else if (query instanceof GroupByQuery) { GroupByQuery q = (GroupByQuery) query; dimensions.addAll(extractFieldsFromAggregations(q.getAggregatorSpecs())); for (DimensionSpec spec : q.getDimensions()) { String dim = spec.getDimension(); dimensions.add(dim); } } else { throw new UnsupportedOperationException("Method getRequeiredFields only support TopNQuery/TimeseriesQuery/GroupByQuery"); } return dimensions; }
Source:
<code>private static String serializePropertyValue(PropertyInterface property, com.xpn.xwiki.objects.classes.PropertyClass propertyClass, XWikiContext context) { if (propertyClass instanceof ComputedFieldClass) { XWikiDocument document = context.getDoc(); try { context.setDoc(property.getObject().getOwnerDocument()); ComputedFieldClass computedFieldClass = (ComputedFieldClass) propertyClass; <START> return computedFieldClass.getComputedValue(propertyClass.getName(), "", property.getObject(), context); <END> } finally { context.setDoc(document); } } else { return serializePropertyValue(property); } }</code><technical_language>if right catch exception in case getComputedValue worked for some reason. in catch I guess log error actual exception, fallback serializePropertyValue(property);</technical_language>

Target:
private String serializePropertyValue(PropertyInterface property, com.xpn.xwiki.objects.classes.PropertyClass propertyClass, XWikiContext context) { if (propertyClass instanceof ComputedFieldClass) { XWikiDocument document = context.getDoc(); try { context.setDoc(property.getObject().getOwnerDocument()); ComputedFieldClass computedFieldClass = (ComputedFieldClass) propertyClass; return computedFieldClass.getComputedValue(propertyClass.getName(), "", property.getObject(), context); } catch (Exception e) { logger.error("Error while computing property value of [{}]", propertyClass.getName(), property.getObject(), e); return serializePropertyValue(property); } finally { context.setDoc(document); } } else { return serializePropertyValue(property); } }
Source:
<code>public WorkspaceConfigImpl createWorkspaceConfig( <START> Devfile devfile, RecipeFileContentProvider recipeFileContentProvider) <END> throws DevfileFormatException, DevfileRecipeFormatException { integrityValidator.validateDevfile(devfile); return devfileConverter.devFileToWorkspaceConfig(devfile, recipeFileContentProvider); }</code><technical_language>Please update java doc new parameter exception adding</technical_language>

Target:
public WorkspaceConfigImpl createWorkspaceConfig( Devfile devfile, RecipeFileContentProvider recipeFileContentProvider) throws DevfileFormatException, DevfileRecipeFormatException, DevfileException { integrityValidator.validateDevfile(devfile); return devfileConverter.devFileToWorkspaceConfig(devfile, recipeFileContentProvider); }
Source:
<code>public void onChildMoved(DataSnapshot snapshot, String previousChildKey) { int oldIndex = getIndexForKey(snapshot.getKey()); mSnapshots.remove(oldIndex); int newIndex = previousChildKey == null ? 0 : (getIndexForKey(previousChildKey) + 1); mSnapshots.add(newIndex, snapshot); <START> mSnapshotMap.put(snapshot.getKey(), newIndex); <END> notifyChangedListeners(OnChangedListener.EventType.MOVED, newIndex, oldIndex); }</code><technical_language>onChildMoved affect indexes of key? I a feeling @puf a Map in place I wrong</technical_language>

Target:
public void onChildMoved(DataSnapshot snapshot, String previousChildKey) { int oldIndex = getIndexForKey(snapshot.getKey()); mSnapshots.remove(oldIndex); int newIndex = previousChildKey == null ? 0 : (scanArrayForKey(previousChildKey) + 1); mSnapshots.add(newIndex, snapshot); mSnapshotMap.clear(); for (int i = 0; i < mSnapshots.size(); i++) { mSnapshotMap.put(mSnapshots.get(i).getKey(), i); } notifyChangedListeners(OnChangedListener.EventType.MOVED, newIndex, oldIndex); }
Source:
<code>public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle args = getArguments(); if (getArguments() != null) { location_id = args.getString(LOCATION_ID); Log.d("DirectionsFragment", "Got location " + location_id); use_location = args.getBoolean(USE_CURRENT_LOCATION); if (use_location) { <START> Log.d("DirectionsFragment", "Showing directiosn from current location"); <END> } else { Log.d("DirectionsFragment", "Showing directions from entered address"); } } }</code><technical_language>typo</technical_language>

Target:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle args = getArguments(); if (getArguments() != null) { location_id = args.getString(LOCATION_ID); Log.d("DirectionsFragment", "Got location " + location_id); use_location = args.getBoolean(USE_CURRENT_LOCATION); if (use_location) { Log.d("DirectionsFragment", "Showing directions from current location"); } else { Log.d("DirectionsFragment", "Showing directions from entered address"); } } }
Source:
<code>public void testDoesNotGetSubscriptionByCreateTopicIfAutosubscribeDisabled() throws NotFoundException { Topic createdTopic = ObjectsFactory.topics(user, 1).get(0); user.setAutosubscribe(false); <START> replyTopicStubs(createdTopic); <END> Topic createdTopicLast = topicService.createTopic(createdTopic, ANSWER_BODY); assertFalse(createdTopicLast.userSubscribed(user), UNSUBSCRIBED); }</code><technical_language>Again, test for topic creation replyTopicStubs</technical_language>

Target:
public void testDoesNotGetSubscriptionByCreateTopicIfAutosubscribeDisabled() throws NotFoundException { Topic createdTopic = ObjectsFactory.topics(user, 1).get(0); user.setAutosubscribe(false); createTopicStubs(); Topic createdTopicLast = topicService.createTopic(createdTopic, ANSWER_BODY); verify(subscriptionService,never()).subscribe(createdTopicLast); }
Source:
<code><START> private void sendDataToListView(final BattleReportStatistics statistics) { <END> List<BaseItem> itemList = new ArrayList<BaseItem>(); if(statistics.getFavoriteReports().size() > 0) { itemList.add(new BattleReportHeader(R.string.header_favorite_battlereport)); itemList.addAll(buildBaseItemList(new ArrayList<GameReport>(statistics.getFavoriteReports()), statistics.getSoldierId())); } itemList.add(new BattleReportHeader(R.string.header_latest_battlereport)); itemList.addAll(buildBaseItemList(new ArrayList<GameReport>(statistics.getStatsGameReports()), statistics.getSoldierId())); BattleReportAdapter adapter = new BattleReportAdapter(getActivity().getApplicationContext(), itemList); setListAdapter(adapter); }</code><technical_language>I solution headers&items. :+1:</technical_language>

Target:
private void sendDataToListView(final BattleReportStatistics statistics) { List<BaseItem> itemList = new ArrayList<BaseItem>(); if(statistics.getFavoriteReports().size() > 0) { itemList.add(new BattleReportHeader(R.string.header_favorite_battlereport)); itemList.addAll(buildBaseItemList(new ArrayList<GameReport>(statistics.getFavoriteReports()), statistics.getSoldierId())); } itemList.add(new BattleReportHeader(R.string.header_latest_battlereport)); itemList.addAll(buildBaseItemList(new ArrayList<GameReport>(statistics.getStatsGameReports()), statistics.getSoldierId())); BattleReportAdapter adapter = new BattleReportAdapter(getActivity(), itemList); setListAdapter(adapter); }
Source:
<code>public boolean equals(Object obj) { if (obj == null) { return false; } <START> if (!JavaVersion.class.isAssignableFrom(obj.getClass())) { <END> return false; } final JavaVersion other = (JavaVersion) obj; return this.discard == other.discard && this.major == other.major && this.minor == other.minor && this.update == other.update && this.build == other.build; }</code><technical_language>Is this subtype equality needed</technical_language>

Target:
public boolean equals(Object obj) { if (obj == null) { return false; } if (!(obj instanceof JavaVersion)) { return false; } final JavaVersion other = (JavaVersion) obj; return compareTo(other) == 0; }
Source:
<code>public void filter(ContainerRequestContext requestContext) { <START> if (healthCheck.shootTimeLock()) { <END> requestContext.abortWith( Response.status(Response.Status.SERVICE_UNAVAILABLE).build()); } }</code><technical_language>a fan of shootTimelock - feels pretty ambiguous (particularly this is a boolean!)</technical_language>

Target:
public void filter(ContainerRequestContext requestContext) { if (healthCheck.shouldRejectRequests()) { requestContext.abortWith( Response.status(Response.Status.SERVICE_UNAVAILABLE).build()); } }
Source:
<code><START> static public boolean exists(File basePath) { <END> return basePath.isDirectory() && basePath.list().length > 0; }</code><technical_language>Correct keyword order</technical_language>

Target:
protected static boolean exists(File basePath) { return basePath.isDirectory() && basePath.list().length > 0; }
Source:
<code>public WindowImpl(final long start, final long size) { <START> latestTimestamp = Long.MIN_VALUE; <END> latestWatermark = null; dataCollection = new LinkedList<>(); this.start = start; this.end = start + size; }</code><technical_language>Is this correct</technical_language>

Target:
public WindowImpl(final long start, final long size) { latestTimestamp = 0L; latestWatermark = null; dataCollection = new LinkedList<>(); this.start = start; this.end = start + size; }
Source:
<code>public String getQuestionResultStatisticsHtml(List<FeedbackResponseAttributes> responses, <START> FeedbackQuestionAttributes question, <END> String studentEmail, FeedbackSessionResultsBundle bundle, String view) { if ("student".equals(view) || responses.isEmpty()) { return ""; } StringBuilder fragments = new StringBuilder(); Map<String, Integer> answerFrequency = new LinkedHashMap<>(); for (String option : mcqChoices) { answerFrequency.put(option, 0); } if (otherEnabled) { answerFrequency.put("Other", 0); } for (FeedbackResponseAttributes response : responses) { String answerString = response.getResponseDetails().getAnswerString(); boolean isOtherOptionAnswer = ((FeedbackMcqResponseDetails) response.getResponseDetails()).isOtherOptionAnswer(); if (isOtherOptionAnswer) { answerFrequency.putIfAbsent("Other", 0); answerFrequency.put("Other", answerFrequency.get("Other") + 1); } else { answerFrequency.putIfAbsent(answerString, 0); answerFrequency.put(answerString, answerFrequency.get(answerString) + 1); } } DecimalFormat df = new DecimalFormat("#.##"); for (Entry<String, Integer> entry : answerFrequency.entrySet()) { fragments.append(Templates.populateTemplate(FormTemplates.MCQ_RESULT_STATS_OPTIONFRAGMENT, Slots.MCQ_CHOICE_VALUE, SanitizationHelper.sanitizeForHtml(entry.getKey()), Slots.COUNT, entry.getValue().toString(), Slots.PERCENTAGE, df.format(100 * (double) entry.getValue() / responses.size()))); } return Templates.populateTemplate(FormTemplates.MCQ_RESULT_STATS, Slots.FRAGMENTS, fragments.toString()); }</code><technical_language>here. Pls refer <LINK_0></technical_language>

Target:
public String getQuestionResultStatisticsHtml(List<FeedbackResponseAttributes> responses, FeedbackQuestionAttributes question, String studentEmail, FeedbackSessionResultsBundle bundle, String view) { if ("student".equals(view) || responses.isEmpty()) { return ""; } StringBuilder fragments = new StringBuilder(); Map<String, Integer> answerFrequency = collateAnswerFrequency(responses); DecimalFormat df = new DecimalFormat("#.##"); answerFrequency.forEach((key, value) -> fragments.append(Templates.populateTemplate(FormTemplates.MCQ_RESULT_STATS_OPTIONFRAGMENT, Slots.MCQ_CHOICE_VALUE, SanitizationHelper.sanitizeForHtml(key), Slots.COUNT, value.toString(), Slots.PERCENTAGE, df.format(100 * (double) value / responses.size())))); return Templates.populateTemplate(FormTemplates.MCQ_RESULT_STATS, Slots.FRAGMENTS, fragments.toString()); }