auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static Image getCamoImage(String category, String name) { <START> if (category == null || name == null) { <END> return ImageUtil.failStandardImage(); } initializeCamos(); if (camoDirectory == null) { return ImageUtil.failStandardImage(); } try { if (category.equals(IPlayer.NO_CAMO)) { return colorCamoImage(PlayerColors.getColor(name)); } if (IPlayer.ROOT_CAMO.equals(category)) { category = ""; } Image image = (Image) camoDirectory.getItem(category, name); if (image != null) { return image; } } catch (Exception e) { e.printStackTrace(); } LOG.error(CamoManager.class, "Could not create camo image! Category: " + category + "; Name: " + name); return ImageUtil.failStandardImage(); }</code><technical_language>suggestion if ((category == null) || (name == null)) {</technical_language>

Target:
public static Image getCamoImage(String category, String name) { if ((category == null) || (name == null)) { return ImageUtil.failStandardImage(); } initializeCamos(); if (camoDirectory == null) { return ImageUtil.failStandardImage(); } try { if (category.equals(IPlayer.NO_CAMO)) { return colorCamoImage(PlayerColors.getColor(name)); } if (IPlayer.ROOT_CAMO.equals(category)) { category = ""; } Image image = (Image) camoDirectory.getItem(category, name); if (image != null) { return image; } } catch (Exception e) { e.printStackTrace(); } MegaMek.getLogger().error(CamoManager.class, "Could not create camo image! Category: " + category + "; Name: " + name); return ImageUtil.failStandardImage(); }
Source:
<code>public void receiveNoPin() { mySignerId = JPAKE_SIGNERID_RECEIVER; theirSignerId = JPAKE_SIGNERID_SENDER; jParty = new JPakeParty(mySignerId); jpakeMaxTries = MAX_TRIES_FIRST_MSG; createSecret(); <START> prepareStagesAndStartWithPin(false); <END> }</code><technical_language>Similarly</technical_language>

Target:
public void receiveNoPin() { mySignerId = JPAKE_SIGNERID_RECEIVER; theirSignerId = JPAKE_SIGNERID_SENDER; jParty = new JPakeParty(mySignerId); jpakeMaxTries = MAX_TRIES_FIRST_MSG; createSecret(); prepareReceiverStages(); runNextStage(); }
Source:
<code>public HiveTableInstance createMutable(HiveTableDefinition tableDefinition, State state, TableHandle tableHandle) { TableName tableName = createMutableTableName(tableHandle); LOGGER.debug("creating mutable table {}", tableName); if (state == PREPARED) { return new HiveTableInstance(tableName, tableDefinition); } createTable(tableDefinition, tableName, Optional.empty()); if (tableDefinition.isPartitioned()) { int partitionId = 0; for (HiveTableDefinition.PartitionDefinition partitionDefinition : tableDefinition.getPartitionDefinitons()) { String partitionDataPath = getMutableTableHdfsPath(tableName, Optional.of(partitionId)); if (state == LOADED) { uploadTableData(partitionDataPath, partitionDefinition.getDataSource()); } queryExecutor.executeQuery(partitionDefinition.getAddPartitionTableDDL(tableName, partitionDataPath)); partitionId++; } } else if (state == LOADED) { String tableDataPath = getMutableTableHdfsPath(tableName, Optional.empty()); uploadTableData(tableDataPath, tableDefinition.getDataSource()); } if (state == LOADED && analyzeMutableTables && tableDefinition.getDataSource().getStatistics().isPresent()) { <START> checkState(!tableDefinition.isPartitioned(), "Statisitcs are not yet supported for parititioned tables"); <END> hiveThriftClient.setStatistics(tableName, tableDefinition.getDataSource().getStatistics().get()); } return new HiveTableInstance(tableName, tableDefinition); }</code><technical_language>drop</technical_language>

Target:
public HiveTableInstance createMutable(HiveTableDefinition tableDefinition, State state, TableHandle tableHandle) { TableName tableName = createMutableTableName(tableHandle); LOGGER.debug("creating mutable table {}", tableName); if (state == PREPARED) { return new HiveTableInstance(tableName, tableDefinition); } createTable(tableDefinition, tableName, Optional.empty()); if (tableDefinition.isPartitioned()) { int partitionId = 0; for (HiveTableDefinition.PartitionDefinition partitionDefinition : tableDefinition.getPartitionDefinitons()) { String partitionDataPath = getMutableTableHdfsPath(tableName, Optional.of(partitionId)); if (state == LOADED) { uploadTableData(partitionDataPath, partitionDefinition.getDataSource()); } queryExecutor.executeQuery(partitionDefinition.getAddPartitionTableDDL(tableName, partitionDataPath)); partitionId++; } } else if (state == LOADED) { String tableDataPath = getMutableTableHdfsPath(tableName, Optional.empty()); uploadTableData(tableDataPath, tableDefinition.getDataSource()); } if (state == LOADED && analyzeMutableTables && tableDefinition.getDataSource().getStatistics().isPresent()) { checkState(!tableDefinition.isPartitioned(), "Statisitcs are not supported for parititioned tables"); hiveThriftClient.setStatistics(tableName, tableDefinition.getDataSource().getStatistics().get()); } return new HiveTableInstance(tableName, tableDefinition); }
Source:
<code><START> public Optional<Repository> findRepository(Class<? extends Message> entityStateClass) { <END> if (!guard.hasRepository(entityStateClass)) { return Optional.empty(); } Optional<Repository> repository = guard.repositoryFor(entityStateClass); return repository; }</code><technical_language>a method telling repository is registered? In this way, API more consistent. TherepositoryFor is strict assumes repository *is* registered, is is. I fill this gap instead of duplicating API call a small lexical difference</technical_language>

Target:
public Optional<Repository> findRepository(Class<? extends Message> entityStateClass) { if (!guard.hasRepository(entityStateClass)) { throw newIllegalStateException("No repository found for the entity state class `%s`.", entityStateClass.getName()); } Optional<Repository> repository = guard.repositoryFor(entityStateClass); return repository; }
Source:
<code>private MappingParameters(Field field) { index = field.index(); store = field.store(); fielddata = field.fielddata(); type = field.type(); dateFormat = field.format(); datePattern = field.pattern(); analyzer = field.analyzer(); searchAnalyzer = field.searchAnalyzer(); normalizer = field.normalizer(); copyTo = field.copyTo(); ignoreAbove = field.ignoreAbove() >= 0 ? field.ignoreAbove() : null; coerce = field.coerce(); docValues = field.docValues(); Assert.isTrue(!((type == FieldType.Text || type == FieldType.Nested) && !docValues), "docValues false is not allowed for field type text"); ignoreMalformed = field.ignoreMalformed(); indexOptions = field.indexOptions(); indexPhrases = field.indexPhrases(); if (field.indexPrefixes().length > 0) { indexPrefixes = field.indexPrefixes()[0]; } norms = field.norms(); nullValue = field.nullValue(); positionIncrementGap = field.positionIncrementGap(); similarity = field.similarity(); termVector = field.termVector(); scalingFactor = field.scalingFactor(); <START> maxShingleSize = field.maxShingleSize(); <END> Assert.isTrue(type != FieldType.Search_As_You_Type || (maxShingleSize >= 2 && maxShingleSize <= 4), "maxShingleSize must be in inclusive range from 2 to 4 for field type search_as_you_type"); }</code><technical_language>suggestion maxShingleSize = field.maxShingleSize() >= 0 ? field.maxShingleSize : null; check in Assert account for a set default of null</technical_language>

Target:
private MappingParameters(Field field) { index = field.index(); store = field.store(); fielddata = field.fielddata(); type = field.type(); dateFormat = field.format(); datePattern = field.pattern(); analyzer = field.analyzer(); searchAnalyzer = field.searchAnalyzer(); normalizer = field.normalizer(); copyTo = field.copyTo(); ignoreAbove = field.ignoreAbove() >= 0 ? field.ignoreAbove() : null; coerce = field.coerce(); docValues = field.docValues(); Assert.isTrue(!((type == FieldType.Text || type == FieldType.Nested) && !docValues), "docValues false is not allowed for field type text"); ignoreMalformed = field.ignoreMalformed(); indexOptions = field.indexOptions(); indexPhrases = field.indexPhrases(); if (field.indexPrefixes().length > 0) { indexPrefixes = field.indexPrefixes()[0]; } norms = field.norms(); nullValue = field.nullValue(); positionIncrementGap = field.positionIncrementGap(); similarity = field.similarity(); termVector = field.termVector(); scalingFactor = field.scalingFactor(); maxShingleSize = field.maxShingleSize() >= 0 ? field.maxShingleSize() : null; Assert.isTrue(type != FieldType.Search_As_You_Type || maxShingleSize == null || (maxShingleSize >= 2 && maxShingleSize <= 4), "maxShingleSize must be in inclusive range from 2 to 4 for field type search_as_you_type"); }
Source:
<code>public void setSpicePluginImplEnabled(boolean enabled, String reason) { <START> spicePluginImplRadioButton.setVisible(enabled); END> spicePluginImplRadioButton.setEnabled(enabled); if (!enabled) { spicePluginImplRadioButtonTooltip.setText(reason); } }</code><technical_language>need a method for this - fact if plugin is supported in browser is independent of if is enabled in vdc_options. If is enabled, work before</technical_language>

Target:
public void setSpicePluginImplEnabled(boolean enabled, String reason) { spicePluginImplRadioButton.setEnabled(enabled); if (!enabled) { spicePluginImplRadioButtonTooltip.setText(reason); } }
Source:
<code>public void checkAttributeValue(PerunSessionImpl perunSession, Resource resource, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongReferenceAttributeValueException, WrongAttributeAssignmentException { Facility facility = perunSession.getPerunBl().getResourcesManagerBl().getFacility(perunSession, resource); <START> List<Attribute> attributes = perunSession.getPerunBl().getAttributesManagerBl().getAttributes(perunSession, facility); <END> Boolean found = false; for (Attribute attr: attributes) { if (attr.getFriendlyName().equals("homeMountPoints")) { if(attr.getValue().equals(attribute.getValue())){ found = true; break; } } } if(!found){ throw new WrongAttributeValueException(attribute, "ReplicaSourcePath has to be the same as one of the F:D:homeMountPoints"); } }</code><technical_language>get concrete attribute getAttribute(PerunSession, Facility, String attrName)</technical_language>

Target:
public void checkAttributeValue(PerunSessionImpl perunSession, Resource resource, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongReferenceAttributeValueException, WrongAttributeAssignmentException { if(attribute.getValue() == null) { throw new WrongAttributeValueException(attribute, resource, "This attribute can't be empty"); } Facility facility = perunSession.getPerunBl().getResourcesManagerBl().getFacility(perunSession, resource); Attribute facilityAttr = null; try { facilityAttr = perunSession.getPerunBl().getAttributesManagerBl().getAttribute(perunSession, facility, AttributesManager.NS_FACILITY_ATTR_DEF + ":homeMountPoints"); } catch (AttributeNotExistsException ex) { throw new InternalErrorException(ex); } if(facilityAttr.getValue() != null) { if (!((List<String>) facilityAttr.getValue()).containsAll((List<String>) attribute.getValue())) { throw new WrongReferenceAttributeValueException(attribute, facilityAttr, resource, facility, "ReplicaSourcePath has to be the same as one of the F:D:homeMountPoints"); } } }
Source:
<code>public BytesInput compress(BytesInput bytes) throws IOException { compressedOutBuffer.reset(); <START> CompressionOutputStream cos = hadoopCodec.createOutputStream(compressedOutBuffer, compressor); <END> bytes.writeAllTo(cos); cos.finish(); cos.close(); return BytesInput.from(compressedOutBuffer); }</code><technical_language>Please try-with-resource close stream exception happens. Also, I calling finish is required here, close() stream calls statement</technical_language>

Target:
public BytesInput compress(BytesInput bytes) throws IOException { compressedOutBuffer.reset(); try (CompressionOutputStream cos = hadoopCodec.createOutputStream(compressedOutBuffer, compressor)) { bytes.writeAllTo(cos); return BytesInput.from(compressedOutBuffer); } }
Source:
<code>public static Method getMethod(String methodName, String obfName, Class clazz, Class<?>... params) { Method method = null; try { method = clazz.getDeclaredMethod(obfName, params); } catch (NoSuchMethodException e) { <START> EsteemedInnovation.logger.warn("[EI] Unable to find method " + methodName + " with its obfuscated name. Trying to" + <END> " find it by its name " + methodName); try { method = clazz.getDeclaredMethod(methodName, params); } catch (NoSuchMethodException e1) { e1.printStackTrace(); boolean builderHasAMethod = false; StringBuilder builder = new StringBuilder(); for (Method method1 : clazz.getDeclaredMethods()) { if (builderHasAMethod) { builder.append(", "); } builder.append(method1.getName()); builderHasAMethod = true; } EsteemedInnovation.logger.warn("[EI] Unable to find " + methodName + " method in " + clazz.getName() + ".class. Available methods are: " + builder + ". Things are not going to work right."); } } return method; }</code><technical_language>[EI] removed this, [esteemedinnovation] in log entry</technical_language>

Target:
public static Method getMethod(String methodName, String obfName, Class clazz, Class<?>... params) { Method method = null; try { method = clazz.getDeclaredMethod(obfName, params); } catch (NoSuchMethodException e) { EsteemedInnovation.logger.warn("Unable to find method " + methodName + " with its obfuscated name. Trying to" + " find it by its name " + methodName); try { method = clazz.getDeclaredMethod(methodName, params); } catch (NoSuchMethodException e1) { e1.printStackTrace(); boolean builderHasAMethod = false; StringBuilder builder = new StringBuilder(); for (Method method1 : clazz.getDeclaredMethods()) { if (builderHasAMethod) { builder.append(", "); } builder.append(method1.getName()); builderHasAMethod = true; } EsteemedInnovation.logger.warn("Unable to find " + methodName + " method in " + clazz.getName() + ".class. Available methods are: " + builder + ". Things are not going to work right."); } } return method; }
Source:
<code>public void processAsSingleReferenceSlice(final Slice slice) { final ReferenceContext sliceContext = slice.getReferenceContext(); if (sliceContext.isMultiRef()) { throw new SAMException("Expecting a single reference or unmapped slice." ); } <START> <END> try { if (sliceContext.isMappedSingleRef()) { final int reference = sliceContext.getSequenceId(); if (reference != currentReference) { advanceToReference(reference); } if (reference != currentReference) { throw new SAMException("Unexpected reference " + reference + " when constructing index for " + currentReference + " for record " + slice); } } indexBuilder.recordSliceIndexMetadata(slice); if (sliceContext.isMappedSingleRef()) { indexBuilder.processSingleReferenceSlice(slice); } } catch (final Exception e) { throw new SAMException("Exception creating BAM index for slice " + slice, e); } }</code><technical_language>enclosing try/catch is redundant</technical_language>

Target:
public void processAsSingleReferenceSlice(final Slice slice) { final ReferenceContext sliceContext = slice.getReferenceContext(); if (sliceContext.isMultiRef()) { throw new SAMException("Expecting a single reference or unmapped slice."); } if (sliceContext.isMappedSingleRef()) { final int reference = sliceContext.getSequenceId(); if (reference != currentReference) { advanceToReference(reference); } if (reference != currentReference) { throw new SAMException("Unexpected reference " + reference + " when constructing index for " + currentReference + " for record " + slice); } } indexBuilder.recordSliceIndexMetadata(slice); if (sliceContext.isMappedSingleRef()) { indexBuilder.processSingleReferenceSlice(slice); } }
Source:
<code>public List<ScanResult> scan() { String contextPath = servletContext.getContextPath(); List<ScanResult> results = new ArrayList<>(super.scan()); File webInfClasses = null; ScanResult webInfBeansXML = null; try { URL beansXmlUrl = null; for (String resource : RESOURCES) { URL resourceUrl; resourceUrl = servletContext.getResource(resource); if (resourceUrl != null) { if (beansXmlUrl != null) { WeldServletLogger.LOG.foundBothConfiguration(beansXmlUrl); } else { beansXmlUrl = resourceUrl; } } } if (beansXmlUrl != null) { BeansXml beansXml = parseBeansXml(beansXmlUrl); if (accept(beansXml)) { webInfClasses = Servlets.getRealFile(servletContext, WEB_INF_CLASSES); if (webInfClasses != null) { webInfBeansXML = new ScanResult(beansXml, webInfClasses.getPath()).extractBeanArchiveId(contextPath, WEB_INF); } else { webInfBeansXML = new ScanResult(beansXml, WEB_INF_CLASSES); } } } } catch (MalformedURLException e) { throw WeldServletLogger.LOG.errorLoadingResources(e); } for (Iterator<ScanResult> iterator = results.iterator(); iterator.hasNext();) { ScanResult result = iterator.next(); String path = result.getBeanArchiveRef().toString(); <START> if (new File(path).equals(webInfClasses)) { <END> iterator.remove(); } else { result.extractBeanArchiveId(contextPath, WEB_INF); } } if (webInfBeansXML != null) { results.add(webInfBeansXML); } return ImmutableList.copyOf(results); }</code><technical_language>webInfClasses is null for WARs extracted file system. I original conditions, i.e. : java if (path.contains(WEB_INF_CLASSES_FILE_PATH) || path.contains(WEB_INF_CLASSES) || new File(path).equals(webInfClasses)) { ... }</technical_language>

Target:
public List<ScanResult> scan() { String contextPath = servletContext.getContextPath(); List<ScanResult> results = new ArrayList<>(super.scan()); File webInfClasses = null; ScanResult webInfBeansXML = null; try { URL beansXmlUrl = null; for (String resource : RESOURCES) { URL resourceUrl; resourceUrl = servletContext.getResource(resource); if (resourceUrl != null) { if (beansXmlUrl != null) { WeldServletLogger.LOG.foundBothConfiguration(beansXmlUrl); } else { beansXmlUrl = resourceUrl; } } } if (beansXmlUrl != null) { BeansXml beansXml = parseBeansXml(beansXmlUrl); if (accept(beansXml)) { webInfClasses = Servlets.getRealFile(servletContext, WEB_INF_CLASSES); if (webInfClasses != null) { webInfBeansXML = new ScanResult(beansXml, webInfClasses.getPath()).extractBeanArchiveId(contextPath, WEB_INF); } else { webInfBeansXML = new ScanResult(beansXml, WEB_INF_CLASSES); } } } } catch (MalformedURLException e) { throw WeldServletLogger.LOG.errorLoadingResources(e); } for (Iterator<ScanResult> iterator = results.iterator(); iterator.hasNext();) { ScanResult result = iterator.next(); String path = result.getBeanArchiveRef().toString(); if (path.contains(WEB_INF_CLASSES_FILE_PATH) || path.contains(WEB_INF_CLASSES) || new File(path).equals(webInfClasses)) { iterator.remove(); } else { result.extractBeanArchiveId(contextPath, WEB_INF); } } if (webInfBeansXML != null) { results.add(webInfBeansXML); } return ImmutableList.copyOf(results); }
Source:
<code>private int columnIndexForParameter(List<String> columnNames, String parameterName) { int result = -1; for (int i = 0; i < columnNames.size(); i++) { for (ColumnNameMappingStrategy strategy : nameMappingStrategies) { if (strategy.nameMatches(parameterName, columnNames.get(i))) { if (result >= 0) { throw new IllegalArgumentException(String.format( "Constructor '%s' parameter '%s' matches multiple " + "columns: '%s' (%d) and '%s' (%d)", constructor, parameterName, columnNames.get(result), result, columnNames.get(i), i)); } result = i; break; } } } if (result >= 0) { return result; } throw new IllegalArgumentException("Constructor '" + constructor + "' parameter '" + parameterName + "' has no column in the result set. Verify that the Java " + <START> "compiler is confiured to emit parameter names, " + <END> "that your result set has the columns expect, " + "or annotate the parameter names explicitly with @Bean"); }</code><technical_language>typo: confiured</technical_language>

Target:
private int columnIndexForParameter(List<String> columnNames, String parameterName) { int result = -1; for (int i = 0; i < columnNames.size(); i++) { for (ColumnNameMappingStrategy strategy : nameMappingStrategies) { if (strategy.nameMatches(parameterName, columnNames.get(i))) { if (result >= 0) { throw new IllegalArgumentException(String.format( "Constructor '%s' parameter '%s' matches multiple " + "columns: '%s' (%d) and '%s' (%d)", constructor, parameterName, columnNames.get(result), result, columnNames.get(i), i)); } result = i; break; } } } if (result >= 0) { return result; } throw new IllegalArgumentException("Constructor '" + constructor + "' parameter '" + parameterName + "' has no column in the result set. Verify that the Java " + "compiler is configured to emit parameter names, " + "that your result set has the columns expected, " + "or annotate the parameter names explicitly with @ColumnName"); }
Source:
<code>public Iterable<Language> languages() { <START> return new ArrayList<Language>(0); <END> }</code><technical_language>nice languages inside. Empty list is useless</technical_language>

Target:
public Iterable<Language> languages() { final List<Language> languages = new ArrayList<Language>(0); final int java = 999; languages.add(new RtLanguage("Java", java)); final int php = 888; languages.add(new RtLanguage("PHP", php)); final int ruby = 777; languages.add(new RtLanguage("Ruby", ruby)); return languages; }
Source:
<code>public Response remove() { get(); <START> return performAction(VdcActionType.UnlabelNic, new LabelNicParameters(parent.getNicId(), id)); <END> }</code><technical_language>pls change return performAction(VdcActionType.RemoveVfsConfigLabel, new VfsConfigLabelParameters(parent.getHostNicId(), id));</technical_language>

Target:
public Response remove() { get(); return performAction(VdcActionType.RemoveVfsConfigLabel, new VfsConfigLabelParameters(parent.getNicId(), id)); }
Source:
<code>public int update(final String updateClause, final Object... params) throws SQLException { int retry = 0; SQLException exception; String errorMsg = "Update failed: Reached maximum number of retries: " + AzDBUtil.MAX_RETRIES_ON_DEADLOCK; do { try { return this.queryRunner.update(updateClause, params); } catch (final SQLException ex) { exception = ex; if (ex.getErrorCode() == 1213) { retry++; logger.warn("Deadlock detected when trying to execute: " + updateClause + " with values: " + Arrays.toString(params)); try { Thread.sleep(AzDBUtil.RETRY_WAIT_TIME); } catch (InterruptedException e) { <START> logger.info("Sleep interrupted"); <END> } } else { errorMsg = "update failed"; break; } } } while (retry < AzDBUtil.MAX_RETRIES_ON_DEADLOCK); logger.error(errorMsg, exception); if (this.dbMetrics != null) { this.dbMetrics.markDBFailUpdate(); } throw exception; }</code><technical_language>A more detailed message "Sleep DB update retry interrupted" more useful</technical_language>

Target:
public int update(final String updateClause, final Object... params) throws SQLException { int retryCount = 0; SQLException exception; String errorMsg = "Update failed: Reached maximum number of retries: " + AzDBUtil.MAX_RETRIES_ON_DEADLOCK; do { try { return this.queryRunner.update(updateClause, params); } catch (final SQLException ex) { exception = ex; if (queryRunner.getDataSource() instanceof MySQLDataSource && ex.getErrorCode() == MySQLDataSource.MYSQL_ER_LOCK_DEADLOCK) { retryCount++; logger.warn("Deadlock detected when trying to execute: " + updateClause + " with values: " + Arrays.toString(params)); try { Thread.sleep(AzDBUtil.RETRY_WAIT_TIME); } catch (InterruptedException e) { logger.info("Sleep during DB operation retry interrupted."); } } else { errorMsg = "update failed"; break; } } } while (retryCount < AzDBUtil.MAX_RETRIES_ON_DEADLOCK); logger.error(errorMsg, exception); if (this.dbMetrics != null) { this.dbMetrics.markDBFailUpdate(); } throw exception; }
Source:
<code>public void testListNumeric() { builder.beginDocument(); builder.beginBlock(BlockType.NUMERIC_LIST, new Attributes()); builder.beginBlock(BlockType.LIST_ITEM, new Attributes()); builder.characters("One"); builder.endBlock(); builder.beginBlock(BlockType.LIST_ITEM, new Attributes()); builder.characters("Two"); builder.endBlock(); builder.beginBlock(BlockType.LIST_ITEM, new Attributes()); builder.characters("Three"); builder.endBlock(); builder.endBlock(); builder.endDocument(); <START> assertMarkup("1. One\n1. Two\n1. Three\n\n"); <END> }</code><technical_language>Consider tracking number of list items parent block do number prefixes (i.e. 1., 2., 3., ..)</technical_language>

Target:
public void testListNumeric() { builder.beginDocument(); builder.beginBlock(BlockType.NUMERIC_LIST, new Attributes()); builder.beginBlock(BlockType.LIST_ITEM, new Attributes()); builder.characters("One"); builder.endBlock(); builder.beginBlock(BlockType.LIST_ITEM, new Attributes()); builder.characters("Two"); builder.endBlock(); builder.beginBlock(BlockType.LIST_ITEM, new Attributes()); builder.characters("Three"); builder.endBlock(); builder.endBlock(); builder.endDocument(); assertMarkup("1. One\n2. Two\n3. Three\n\n"); }
Source:
<code>public List<Issue> getRelatedIssues(final PullRequest pullRequest) throws MalformedURLException, NotFoundException { <START> Objects.requireNonNull(pullRequest, "url cannot be null"); <END> checkIssueTrackerExists(); final String body = pullRequest.getBody(); final String[] urls = extractURLs(body, RELATED_ISSUES, true); if (urls == null || urls.length == 0 || urls[0] == null) { return null; } else { List<Issue> issues = new ArrayList<>(urls.length); for (String url : urls) { issues.add(getIssue(new URL(url))); } return issues; } }</code><technical_language>incorrect message "url null"</technical_language>

Target:
public List<Issue> getRelatedIssues(final PullRequest pullRequest) throws MalformedURLException, NotFoundException { Objects.requireNonNull(pullRequest, "pull request cannot be null"); checkIssueTrackerExists(); final String body = pullRequest.getBody(); final String[] urls = extractURLs(body, RELATED_ISSUES, true); if (urls == null || urls.length == 0 || urls[0] == null) { return null; } else { List<Issue> issues = new ArrayList<>(urls.length); for (String url : urls) { issues.add(getIssue(new URL(url))); } return issues; } }
Source:
<code>protected Message(Message original) { <START> this.decryptionInfo = original.decryptionInfo; <END> this.relatedUserAnonymizedId = original.relatedUserAnonymizedId; this.threadHeadMessage = null; this.messagesInThread = new ArrayList<>(); this.repliedMessage = null; this.replies = new ArrayList<>(); this.messageDestination = null; this.creationTime = original.creationTime; this.isSentItem = original.isSentItem; this.isRead = original.isRead; }</code><technical_language>decryptionInfo copied? I is of value, encrypted fields copied clone</technical_language>

Target:
protected Message(Message original) { this.decryptionInfo = null; this.relatedUserAnonymizedId = original.relatedUserAnonymizedId; this.threadHeadMessage = null; this.messagesInThread = new ArrayList<>(); this.repliedMessage = null; this.replies = new ArrayList<>(); this.messageDestination = null; this.creationTime = original.creationTime; this.isSentItem = original.isSentItem; this.isRead = original.isRead; }
Source:
<code>public void createReviewClientWithConfiguration() { Project project = new Project(new NameKey("name")); TaskRepository repository = new TaskRepository(GerritConnector.CONNECTOR_KIND, "http://repository"); GerritConfiguration configuration = new GerritConfiguration(new GerritConfigX(), Collections.singletonList(project), null); connector.saveConfiguration(repository, configuration); GerritClient client = connector.createReviewClient(repository, true); <START> assertNotNull(client.getConfiguration().getProjects()); <END> assertNotNull(client.getGerritConfig()); }</code><technical_language>assert contains project</technical_language>

Target:
public void createReviewClientWithConfiguration() { Project project = new Project(new NameKey("name")); TaskRepository repository = new TaskRepository(GerritConnector.CONNECTOR_KIND, "http://repository"); GerritConfiguration configuration = new GerritConfiguration(new GerritConfigX(), Collections.singletonList(project), null); connector.saveConfiguration(repository, configuration); GerritClient client = connector.createReviewClient(repository, true); List<Project> projects = client.getConfiguration().getProjects(); assertNotNull(projects); assertEquals(1, projects.size()); assertEquals(project.getNameKey(), projects.get(0).getNameKey()); assertNotNull(client.getGerritConfig()); }
Source:
<code>private static void clearTomcatCache() throws InvocationTargetException, NoSuchMethodException, IllegalAccessException, NoSuchFieldException { ClassLoader loader = Thread.currentThread().getContextClassLoader(); Class cl = loader.getClass(); if ("org.apache.catalina.loader.WebappClassLoader".equals(cl.getName())) { <START> ArrayList<Field> fields = new ArrayList<Field>(Arrays.asList(cl.getDeclaredFields())); <END> boolean found = false; for (Field field : fields) { if ("resourceEntries".equals(field.getName())) { found = true; } } if (found) { clearMap(cl, loader, "resourceEntries"); } else { Object obj = loader.getClass().getSuperclass().cast(loader); clearMap(cl.getSuperclass(), obj, "resourceEntries"); } } else { LOGGER.debug("class loader " + cl.getName() + " is not tomcat loader."); } }</code><technical_language>do need array list? list arrays? iterate array? Anyway, FieldUtils.getDeclaredField() apache commons-lang</technical_language>

Target:
private static void clearTomcatCache() throws InvocationTargetException, NoSuchMethodException, IllegalAccessException, NoSuchFieldException { ClassLoader loader = Thread.currentThread().getContextClassLoader(); Class cl = loader.getClass(); if ("org.apache.catalina.loader.WebappClassLoader".equals(cl.getName())) { clearMap(cl, loader, "resourceEntries"); } else { LOGGER.debug("class loader " + cl.getName() + " is not tomcat loader."); } }
Source:
<code>public ActivateMavenProfileJob(Action action, IProject project) { super(NLS.bind("{0} maven profile \"openshift\" for project {1}", action == Action.ACTIVATE? "Activating" : "Deactivating", project.getName())); this.action = action; this.project = project; <START> setRule(ResourcesPlugin.getWorkspace().getRuleFactory().createRule(ResourcesPlugin.getWorkspace().getRoot())); <END> }</code><technical_language>IWorkspaceRoot IContainer implement ISchedulingRule odds replace setRule(ResourcesPlugin.getWorkspace().getRuleFactory().createRule(ResourcesPlugin.getWorkspace().getRoot())); setRule(ResourcesPlugin.getWorkspace().getRoot());</technical_language>

Target:
public ActivateMavenProfileJob(Action action, IProject project) { super(NLS.bind("{0} maven profile \"openshift\" for project {1}", action == Action.ACTIVATE? "Activating" : "Deactivating", project.getName())); this.action = action; this.project = project; setRule(ResourcesPlugin.getWorkspace().getRoot()); }
Source:
<code>private void generateImages(GenerationMode mode, String messageKey) { Folder generatorSource = myProcess.getProject().getGeneratorSource(); List<Folder> contentFolders = currentTask.getContentFolders(); <START> if (Objects.isNull(generatorSource)) { Helper.setErrorMessage("noSourceFolderConfiguredInProject"); } if(Objects.isNull(contentFolders)){ Helper.setErrorMessage("noImageFolderConfiguredInProject"); } <END> Integer numberOfFiles = 0; try { String uri = ServiceManager.getFileService().getProcessBaseUriForExistingProcess(myProcess).toString() + myProcess.getProject().getGeneratorSource(); numberOfFiles = ServiceManager.getFileService().getNumberOfFiles(new URI(uri)); if (numberOfFiles > 0) { Subfolder sourceFolder = new Subfolder(myProcess, generatorSource); List<Subfolder> outputs = SubfolderFactoryService.createAll(myProcess, contentFolders); ImageGenerator imageGenerator = new ImageGenerator(sourceFolder, mode, outputs); TaskManager.addTask(new TaskImageGeneratorThread(myProcess.getTitle(), imageGenerator)); Helper.setMessage(messageKey); } else { Helper.setErrorMessage("emptySourceFolder"); } } catch (RuntimeException | URISyntaxException e) { Helper.setErrorMessage(e.getLocalizedMessage(), logger, e); } }</code><technical_language>leave method if of conditions is met, instead of executing try block</technical_language>

Target:
private void generateImages(GenerationMode mode, String messageKey) { Folder generatorSource = myProcess.getProject().getGeneratorSource(); List<Folder> contentFolders = currentTask.getContentFolders(); if (Objects.isNull(generatorSource)) { Helper.setErrorMessage("noSourceFolderConfiguredInProject"); return; } if(Objects.isNull(contentFolders)){ Helper.setErrorMessage("noImageFolderConfiguredInProject"); return; } Integer numberOfFiles = 0; try { String uri = ServiceManager.getFileService().getProcessBaseUriForExistingProcess(myProcess).toString() + myProcess.getProject().getGeneratorSource(); numberOfFiles = ServiceManager.getFileService().getNumberOfFiles(new URI(uri)); if (numberOfFiles > 0) { Subfolder sourceFolder = new Subfolder(myProcess, generatorSource); List<Subfolder> outputs = SubfolderFactoryService.createAll(myProcess, contentFolders); ImageGenerator imageGenerator = new ImageGenerator(sourceFolder, mode, outputs); TaskManager.addTask(new TaskImageGeneratorThread(myProcess.getTitle(), imageGenerator)); Helper.setMessage(messageKey); } else { Helper.setErrorMessage("emptySourceFolder"); } } catch (RuntimeException | URISyntaxException e) { Helper.setErrorMessage(e.getLocalizedMessage(), logger, e); } }
Source:
<code>protected void updateExpiryPolicyOfRecord(CacheRecord record, Object expiryPolicy) { Object inMemoryExpiryPolicy; switch (cacheConfig.getInMemoryFormat()) { case OBJECT: if (expiryPolicy instanceof Data) { inMemoryExpiryPolicy = dataToValue((Data) expiryPolicy); } else { inMemoryExpiryPolicy = expiryPolicy; <START> } <END> break; case BINARY: case NATIVE: inMemoryExpiryPolicy = toData(expiryPolicy); break; default: throw new IllegalArgumentException("Invalid storage format: " + cacheConfig.getInMemoryFormat()); } record.setExpiryPolicy(inMemoryExpiryPolicy); }</code><technical_language>toValue instead of if-else in this [line](<LINK_0></technical_language>

Target:
protected void updateExpiryPolicyOfRecord(CacheRecord record, Object expiryPolicy) { Object inMemoryExpiryPolicy; switch (cacheConfig.getInMemoryFormat()) { case OBJECT: inMemoryExpiryPolicy = toValue(expiryPolicy); break; case BINARY: case NATIVE: inMemoryExpiryPolicy = toData(expiryPolicy); break; default: throw new IllegalArgumentException("Invalid storage format: " + cacheConfig.getInMemoryFormat()); } record.setExpiryPolicy(inMemoryExpiryPolicy); }
Source:
<code>private void stateTransition(State newState, UnaryOperator<CircuitBreakerState> newStateGenerator) { CircuitBreakerState previousState = stateReference.getAndUpdate(currentState -> { StateTransition.transitionBetween(getName(), currentState.getState(), newState); <START> if (currentState instanceof OpenState) { <END> ((OpenState) currentState).cancelAutomaticTransitionToHalfOpen(); } return newStateGenerator.apply(currentState); }); publishStateTransitionEvent( StateTransition.transitionBetween(getName(), previousState.getState(), newState)); }</code><technical_language>happy this state-specific code is in generic method of CircuitBreakerStateMachine. add a postTransitionHook preTransitionHook states invoked in a generic form</technical_language>

Target:
private void stateTransition(State newState, UnaryOperator<CircuitBreakerState> newStateGenerator) { CircuitBreakerState previousState = stateReference.getAndUpdate(currentState -> { StateTransition.transitionBetween(getName(), currentState.getState(), newState); currentState.preTransitionHook(); return newStateGenerator.apply(currentState); }); publishStateTransitionEvent( StateTransition.transitionBetween(getName(), previousState.getState(), newState)); }
Source:
<code>public Server choose(Object key) { if (loadBalancerStats == null) { return super.choose(key); } List<Server> serverList = getLoadBalancer().getAllServers(); int minimalConcurrentConnections = Integer.MAX_VALUE; long currentTime = System.currentTimeMillis(); Server chosen = null; for (Server server: serverList) { ServerStats serverStats = loadBalancerStats.getSingleServerStat(server); <START> if (!serverStats.isCircuitBreakerTripped(currentTime) && server.isAlive() && server.isReadyToServe()) { <END> int concurrentConnections = serverStats.getActiveRequestsCount(currentTime); if (concurrentConnections < minimalConcurrentConnections) { minimalConcurrentConnections = concurrentConnections; chosen = server; } } } if (chosen == null) { return super.choose(key); } else { return chosen; } }</code><technical_language>cleaner change call getAllServers getReachableServers</technical_language>

Target:
public Server choose(Object key) { if (loadBalancerStats == null) { return super.choose(key); } List<Server> serverList = getLoadBalancer().getReachableServers(); int minimalConcurrentConnections = Integer.MAX_VALUE; long currentTime = System.currentTimeMillis(); Server chosen = null; for (Server server: serverList) { ServerStats serverStats = loadBalancerStats.getSingleServerStat(server); if (!serverStats.isCircuitBreakerTripped(currentTime) && server.isReadyToServe()) { int concurrentConnections = serverStats.getActiveRequestsCount(currentTime); if (concurrentConnections < minimalConcurrentConnections) { minimalConcurrentConnections = concurrentConnections; chosen = server; } } } if (chosen == null) { return super.choose(key); } else { return chosen; } }
Source:
<code>public boolean select(Viewer viewer, Object parentElement, Object element) { ChangeMessageInfoImpl row = (ChangeMessageInfoImpl) element; if (row != null && row.getAuthor() != null) { if (fIsMachine) { if (row.getAuthor().getName().contains("Hudson") || row.getAuthor().getName().contains("Jenkins")) { return true; } return false; } else { if (row.getAuthor().getName().contains("Hudson") || row.getAuthor().getName().contains("Jenkins")) { return false; } return true; } <START> } else if (fIsMachine) { <END> return false; } else { return true; } }</code><technical_language>I need else if / else simply return true. reasoning is get here, row preserve displayed</technical_language>

Target:
public boolean select(Viewer viewer, Object parentElement, Object element) { ChangeMessageInfoImpl row = (ChangeMessageInfoImpl) element; if (row != null && row.getAuthor() != null) { if (fIsMachine) { if (row.getAuthor().getName().contains("Hudson") || row.getAuthor().getName().contains("Jenkins")) { return true; } return false; } else { if (row.getAuthor().getName().contains("Hudson") || row.getAuthor().getName().contains("Jenkins")) { return false; } return true; } } else { return true; } }
Source:
<code>public void testImmediatePruning() throws Exception { BranchBuilder bb = tr.branch("refs/heads/master"); bb.commit().message("M").add("M", "M").create(); String tempRef = "refs/heads/soon-to-be-unreferenced"; BranchBuilder bb2 = tr.branch(tempRef); bb2.commit().message("M").add("M", "M").create(); gc.setExpireAgeMillis(0); gc.gc(); stats = gc.getStatistics(); fsTick(); RefUpdate update = tr.getRepository().getRefDatabase().newUpdate(tempRef, false); update.setForceUpdate(true); update.delete(); bb.commit().message("B").add("B", "Q").create(); FileBasedConfig config = repo.getConfig(); config.setString(ConfigConstants.CONFIG_GC_SECTION, null, ConfigConstants.CONFIG_KEY_PRUNEEXPIRE, "now"); config.save(); gc.setPackExpireAgeMillis(0); gc.gc(); stats = gc.getStatistics(); assertEquals(0, stats.numberOfLooseObjects); assertEquals(6, stats.numberOfPackedObjects); assertEquals(1, stats.numberOfPackFiles); <START> assertEquals(0, stats.numberOfLooseObjects); <END> }</code><technical_language>This done L287</technical_language>

Target:
public void testImmediatePruning() throws Exception { BranchBuilder bb = tr.branch("refs/heads/master"); bb.commit().message("M").add("M", "M").create(); String tempRef = "refs/heads/soon-to-be-unreferenced"; BranchBuilder bb2 = tr.branch(tempRef); bb2.commit().message("M").add("M", "M").create(); gc.setExpireAgeMillis(0); gc.gc(); stats = gc.getStatistics(); fsTick(); RefUpdate update = tr.getRepository().getRefDatabase().newUpdate(tempRef, false); update.setForceUpdate(true); update.delete(); bb.commit().message("B").add("B", "Q").create(); FileBasedConfig config = repo.getConfig(); config.setString(ConfigConstants.CONFIG_GC_SECTION, null, ConfigConstants.CONFIG_KEY_PRUNEEXPIRE, "now"); config.save(); gc.setPackExpireAgeMillis(0); gc.gc(); stats = gc.getStatistics(); assertEquals(0, stats.numberOfLooseObjects); assertEquals(6, stats.numberOfPackedObjects); assertEquals(1, stats.numberOfPackFiles); }
Source:
<code>public void testDoesNotRegisterTwiceOnRegister() { monitor.register(); monitor.register(); <START> assertThat(harness.getNetworkCall()).contains(monitor.callback); <END> }</code><technical_language>This verify registered - I suggest .containsExactly(monitor.callback)</technical_language>

Target:
public void testDoesNotRegisterTwiceOnRegister() { monitor.register(); monitor.register(); assertThat(harness.getNetworkCall()).containsExactly(monitor.callback); }
Source:
<code>public static Task<OsDetails> getOsDetails(final Entity entity) { Optional<SshMachineLocation> location = Locations.findUniqueSshMachineLocation(entity.getLocations()); if (!location.isPresent()) { throw new IllegalStateException("Entity "+entity+" has no SSH location to gather OS details. Locations: "+entity.getLocations()); } final SshMachineLocation sshLocation = location.get(); return Tasks.<OsDetails>builder() .name("Get OsDetails for " + entity) .body(new Callable<OsDetails>() { @Override public OsDetails call() throws Exception { String architecture = DynamicTasks.queue(SshEffectorTasks.ssh("uname -m") .machine(sshLocation) .requiringZeroAndReturningStdout()).get().trim(); BufferedReader reader = new BufferedReader(Streams.reader( new ResourceUtils(this).getResourceFromUrl("classpath://brooklyn/entity/software/os-and-version.sh"))); <START> List<String> script = Lists.newArrayList(); <END> for (String line; (line = reader.readLine()) != null; ) { script.add(line); } String[] nameAndVersion = DynamicTasks.queue(SshEffectorTasks.ssh(script.toArray(new String[script.size()])) .machine(sshLocation) .requiringZeroAndReturningStdout()) .get() .split("\\r?\\n"); String name = nameAndVersion.length > 0 ? nameAndVersion[0] : "unknown"; String version = nameAndVersion.length > 1 ? nameAndVersion[1] : "unknown"; OsDetails details = new BasicOsDetails(name, architecture, version); if (LOG.isDebugEnabled()) LOG.debug("OsDetails for {}: {}", entity, details); return details; } }) .build(); }</code><technical_language>instead like: List<String> script = CharStreams.readLines(reader);</technical_language>

Target:
public static Task<OsDetails> getOsDetails(final Entity entity) { Optional<SshMachineLocation> location = Locations.findUniqueSshMachineLocation(entity.getLocations()); if (!location.isPresent()) { throw new IllegalStateException("Entity "+entity+" has no SSH location to gather OS details. Locations: "+entity.getLocations()); } return getOsDetails(location.get()); }
Source:
<code>public int createDownloadNotification(Context context, String programName) { if (context == null || programName == null) { return -1; } initNotificationManager(context); Intent downloadIntent = new Intent(context, MainMenuActivity.class); downloadIntent.setAction(Intent.ACTION_MAIN).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) .putExtra(EXTRA_PROJECT_NAME, programName); PendingIntent pendingIntent = PendingIntent.getActivity(context, notificationId, downloadIntent, PendingIntent.FLAG_CANCEL_CURRENT); NotificationData data = new NotificationData(pendingIntent, R.drawable.ic_stat, programName, context.getString(R.string.notification_download_title_pending), context.getString(R.string.notification_title_open), context.getString(R.string.notification_download_pending), context.getString(R.string.notification_download_finished), <START> 0, 100, false, false); <END> return createNotification(context, data); }</code><technical_language>MAX_PERCENT here</technical_language>

Target:
public int createDownloadNotification(Context context, String programName) { if (context == null || programName == null) { return -1; } initNotificationManager(context); Intent downloadIntent = new Intent(context, MainMenuActivity.class); downloadIntent.setAction(Intent.ACTION_MAIN).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) .putExtra(EXTRA_PROJECT_NAME, programName); PendingIntent pendingIntent = PendingIntent.getActivity(context, notificationId, downloadIntent, PendingIntent.FLAG_CANCEL_CURRENT); NotificationData data = new NotificationData(pendingIntent, R.drawable.ic_stat, programName, context.getString(R.string.notification_download_title_pending), context.getString(R.string.notification_title_open), context.getString(R.string.notification_download_pending), context.getString(R.string.notification_download_finished), 0, MAX_PERCENT, false, false); return createNotification(context, data); }
Source:
<code>public Application beforeApprove(PerunSession session, Application app) throws PerunException { <START> User user = app.getUser(); <END> Group group = app.getGroup(); AttributesManager am = session.getPerun().getAttributesManager(); Attribute attestation = am.getAttribute(session, group, A_G_D_groupAttestation); if (attestation == null) { throw new CantBeApprovedException("Application cannot be approved: Group does not have attestation attribute set."); } String newValue = attestation.valueAsString(); if (newValue == null || newValue.isEmpty()) { throw new CantBeApprovedException("Application cannot be approved: Group does not have attestation value set."); } return app; }</code><technical_language>Group is present for group type applications. sure, this registration module VO ? I prefer checking group null passing getAttribute() rely check. skip logic if group is present (depends use-case). Right throw ugly exception user/admin like: "something wrong - please report"</technical_language>

Target:
public Application beforeApprove(PerunSession session, Application app) throws PerunException { Group group = app.getGroup(); if (group == null) { throw new CantBeApprovedException("This module can be set only for registration to Group."); } AttributesManager am = session.getPerun().getAttributesManager(); Attribute attestation = am.getAttribute(session, group, A_G_D_groupAttestation); if (attestation == null) { throw new CantBeApprovedException("Application cannot be approved: Group does not have attestation attribute set."); } String newValue = attestation.valueAsString(); if (newValue == null || newValue.isEmpty()) { throw new CantBeApprovedException("Application cannot be approved: Group does not have attestation value set."); } return app; }
Source:
<code>public ChannelHandlerContext firstContext() { synchronized (handlers) { <START> if (handlers.isEmpty()) { <END> return null; } return handlers.get(0); } }</code><technical_language>simplify conditional operator? java return handlers.isEmpty() ? null : handlers.get(0);</technical_language>

Target:
public ChannelHandlerContext firstContext() { synchronized (handlers) { return handlers.isEmpty() ? null : handlers.get(0); } }
Source:
<code>void setupIndentationLevel() { final int indentationLevel = presenter.getLevel(); <START> final int pixelsPerLevel = 35; <END> final int marginPixels = pixelsPerLevel * indentationLevel; this.level.style.marginLeft = margin(marginPixels); }</code><technical_language>a static</technical_language>

Target:
void setupIndentationLevel() { final int indentationLevel = presenter.getLevel(); final int marginPixels = PIXELS_PER_LEVEL * indentationLevel; this.level.style.marginLeft = margin(marginPixels); }