auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void serve() throws TException { Dispatcher dispatcher = conn.createDispatcher(newRequestHandler()); for (String subject : subjects) { if (queue != null && !queue.isEmpty()) { dispatcher.subscribe(subject, queue); } else { dispatcher.subscribe(subject); } } LOGGER.info("Frugal server running..."); partiesAwaitingFullShutdown.register(); try { boolean shutdownSignalReceived = false; try { shutdownSignal.await(); shutdownSignalReceived = true; } catch (InterruptedException ignored) { <START> } <END> LOGGER.info("Frugal server stopping..."); for (String subject : subjects) { try { dispatcher.unsubscribe(subject); } catch (IllegalStateException e) { LOGGER.warn("Frugal server failed to unsubscribe from " + subject + ": " + e .getMessage()); } } conn.closeDispatcher(dispatcher); if (shutdownSignalReceived) { partiesAwaitingFullShutdown.arriveAndAwaitAdvance(); partiesAwaitingFullShutdown.arriveAndAwaitAdvance(); } } finally { partiesAwaitingFullShutdown.arriveAndDeregister(); } }</code><technical_language>IMO clearer final var semantics: boolean shutdownSignalReceived; try { ... shutdownSignalReceived = true; } catch (InterruptedException e) { shutdownSignalReceived = false; }</technical_language>

Target:
public void serve() throws TException { Dispatcher dispatcher = conn.createDispatcher(newRequestHandler()); for (String subject : subjects) { if (queue != null && !queue.isEmpty()) { dispatcher.subscribe(subject, queue); } else { dispatcher.subscribe(subject); } } LOGGER.info("Frugal server running..."); partiesAwaitingFullShutdown.register(); try { boolean shutdownSignalReceived; try { shutdownSignal.await(); shutdownSignalReceived = true; } catch (InterruptedException ignored) { shutdownSignalReceived = false; } LOGGER.info("Frugal server stopping..."); conn.closeDispatcher(dispatcher); if (shutdownSignalReceived) { partiesAwaitingFullShutdown.arriveAndAwaitAdvance(); partiesAwaitingFullShutdown.arriveAndAwaitAdvance(); } } finally { partiesAwaitingFullShutdown.arriveAndDeregister(); } }
Source:
<code>static public void importTreeData( TreeReader parser, Project project, String[] recordPath, ImportColumnGroup rootColumnGroup, int limit, ImportParameters parameters ) throws ImportingParserException{ if (logger.isTraceEnabled()) { logger.trace("importTreeData(TreeReader, Project, String[], ImportColumnGroup)"); } try { while (parser.hasNext()) { Token eventType = parser.next(); if (eventType == Token.StartEntity) { findRecord(project, parser, recordPath, 0, rootColumnGroup, limit--,parameters); } } } catch (TreeReaderException e) { logger.error("Exception from XML parse",e); <START> throw new ImportingParserException(((JsonParseException)e.getCause()).getOriginalMessage()); <END> } }</code><technical_language>I assume TreeReaderException instances JsonParseException Especially JsonParseException is a subclass of TreeReaderException! good a unit test show this works. (This sort of mistake caught unit test covering lines)</technical_language>

Target:
static public void importTreeData( TreeReader parser, Project project, String[] recordPath, ImportColumnGroup rootColumnGroup, int limit, ImportParameters parameters ) throws TreeReaderException{ if (logger.isTraceEnabled()) { logger.trace("importTreeData(TreeReader, Project, String[], ImportColumnGroup)"); } try { while (parser.hasNext()) { Token eventType = parser.next(); if (eventType == Token.StartEntity) { findRecord(project, parser, recordPath, 0, rootColumnGroup, limit--,parameters); } } } catch (TreeReaderException e) { logger.error("Exception from XML parse",e); throw e; } }
Source:
<code><START> public boolean equals(final Object o) { <END> if (o instanceof Map) { if (innerMap.equals(o)) { return true; } } return false; }</code><technical_language>understand change more. left simple</technical_language>

Target:
public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof Map)) { return false; } final Map that = (Map) o; return Objects.equals(innerMap, that); }
Source:
<code>public Address(String address) { if (!StringUtils.hasText(address)) { this.exchangeName = ""; this.routingKey = ""; } else { String[] values = new String[] {"", ""}; if (address.contains("/")) { String[] groups = address.split("/"); System.arraycopy(groups, 0, values, 0, groups.length); } else { values[1] = address; } this.exchangeName = values[0]; this.routingKey = values[1]; <START> } <END> }</code><technical_language>Unfortunately, I retain logic for compatibility. MessageProperties.set/getReplyToAddress(). If sending system is older Spring AMQP, replyTo type parse result in incorrect data. Similarly, if receiving system is old, expect type. Of course, support form in @SendTo</technical_language>

Target:
public Address(String address) { if (!StringUtils.hasText(address)) { this.exchangeName = ""; this.routingKey = ""; } else if (address.lastIndexOf('/') <= 0) { this.routingKey = address.replaceFirst("/", ""); this.exchangeName = ""; } else { Matcher matcher = pattern.matcher(address); boolean matchFound = matcher.find(); if (matchFound) { this.exchangeName = matcher.group(1); this.routingKey = matcher.group(2); } else { this.exchangeName = ""; this.routingKey = address; } } }
Source:
<code>public void testSocketFinderAllowedInterfacesPublic() throws Exception { ConcurrentOpenSocketFinder finder = new ConcurrentOpenSocketFinder(socketAlwaysOpen, nodeRunning, userExecutor); finder.allowedInterfaces = AllowedInterfaces.PUBLIC; HostAndPort result = finder.findOpenSocketOnNode(node, 22, 2000, MILLISECONDS); assertEquals(result, HostAndPort.fromParts(PUBLIC_IP, 22)); <START> } <END></code><technical_language>change modifies checkNodeHasIps method (and check socket logic), method visible for testing test concrete method, inputs, instead of entire socket finder path. lead simpler tests reduce indererminism timeouts/mock executors introduce</technical_language>

Target:
public void testSocketFinderAllowedInterfacesPublic() throws Exception { FluentIterable<String> ips = ConcurrentOpenSocketFinder.checkNodeHasIps(node, AllowedInterfaces.PUBLIC); assertTrue(ips.contains(PUBLIC_IP)); assertFalse(ips.contains(PRIVATE_IP)); }
Source:
<code>protected Metric constructMetric(String metricField, Class<?> cls, EntityDictionary entityDictionary) { Meta metaData = entityDictionary.getAttributeOrRelationAnnotation(cls, Meta.class, metricField); Class<?> fieldType = entityDictionary.getType(cls, metricField); List<Class<? extends Aggregation>> aggregations = getAggregations(metricField, cls, entityDictionary); String columnName = metricField; <START> if (entityDictionary.attributeOrRelationAnnotationExists(cls, metricField, javax.persistence.Column.class)) { <END> columnName = entityDictionary .getAttributeOrRelationAnnotation(cls, javax.persistence.Column.class, metricField).name(); } return new SQLMetric( this, metricField, metaData, fieldType, aggregations, columnName ); }</code><technical_language>functionality SQLSchema do this instead</technical_language>

Target:
protected Metric constructMetric(String metricField, Class<?> cls, EntityDictionary entityDictionary) { Meta metaData = entityDictionary.getAttributeOrRelationAnnotation(cls, Meta.class, metricField); Class<?> fieldType = entityDictionary.getType(cls, metricField); List<Class<? extends Aggregation>> aggregations = getAggregations(metricField, cls, entityDictionary); return new SQLMetric( this, metricField, metaData, fieldType, aggregations, getColumnName(entityDictionary, cls, metricField) ); }
Source:
<code>private SpecialPathInfo getPathInfo( Location location, String path, Collection<SpecialPathInfo> from ) { SpecialPathInfo firstHit = null; if ( path != null ) { for ( SpecialPathInfo info : from ) { final boolean originalMatched = info.getMatcher().matches( location, path ); final boolean storagePathMatched = cacheProvider != null && info.getMatcher() .matches( location, <START> cacheProvider.getStoragePath( <END> location, path ) ); if ( originalMatched || storagePathMatched ) { if ( firstHit != null ) { Logger logger = LoggerFactory.getLogger( getClass() ); logger.error( "Duplicate special-path registration for: {}:{}. Using: {}", location, path, firstHit ); } else { firstHit = info; } } } } return firstHit; }</code><technical_language>Also, construct a ConcreteResource location + path here? If so, leave CacheProvider PathGenerator interfaces simpler. In fact, able reverse calls methods in this class put implementation logic in a form accepts a ConcreteResource...I'm that</technical_language>

Target:
private SpecialPathInfo getPathInfo( Location location, String path, Collection<SpecialPathInfo> from ) { SpecialPathInfo firstHit = null; if ( path != null ) { for ( SpecialPathInfo info : from ) { final boolean originalMatched = info.getMatcher().matches( location, path ); boolean storagePathMatched = originalMatched; if ( location != null ) { final ConcreteResource resource = new ConcreteResource( location, path ); storagePathMatched = info.getMatcher().matches( location, getStoragePath( resource ) ); } if ( originalMatched || storagePathMatched ) { if ( firstHit != null ) { Logger logger = LoggerFactory.getLogger( getClass() ); logger.error( "Duplicate special-path registration for: {}:{}. Using: {}", location, path, firstHit ); } else { firstHit = info; } } } } return firstHit; }
Source:
<code>protected void doGet(HttpServletRequest request, HttpServletResponse response) { response.setContentType("text/html"); try { String url = Config.get().getMotdUrl(); if (url == null || url.trim().length() == 0) { File f = new File(this.getServletContext().getRealPath(motdFileName)); long ft = f.lastModified(); if (ft != lastModified) { lastModified = ft; try { fileContent = FileUtils.readFileToString(f); } catch (IOException e) { LOGGER.debug("Failed to read MOTD file", e); response.getWriter().write(""); return; } } response.getWriter().write(fileContent); } else { HttpClient httpclient = new DefaultHttpClient(); try { HttpGet httpget = new HttpGet(url); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = httpclient.execute(httpget, responseHandler); <START> response.setStatus(200); <END> response.getWriter().write(responseBody); } catch (Exception e) { response.setStatus(500); response.getWriter().write("Server error"); } finally { httpclient.getConnectionManager().shutdown(); } } } catch (IOException e) { LOGGER.debug("Failed to provide MOTD file", e); } }</code><technical_language>200 -> enum</technical_language>

Target:
protected void doGet(HttpServletRequest request, HttpServletResponse response) { response.setContentType("text/html"); try { String url = Config.get().getMotdUrl(); if (url == null || url.trim().length() == 0) { File f = new File(this.getServletContext().getRealPath(motdFileName)); long ft = f.lastModified(); if (ft != lastModified) { lastModified = ft; try { fileContent = FileUtils.readFileToString(f); } catch (IOException e) { LOGGER.debug("Failed to read MOTD file", e); response.getWriter().write(""); return; } } response.getWriter().write(fileContent); } else { HttpClient httpclient = new DefaultHttpClient(); try { HttpGet httpget = new HttpGet(url); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = httpclient.execute(httpget, responseHandler); response.setStatus(Response.Status.OK.getStatusCode()); response.getWriter().write(responseBody); } catch (Exception e) { response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); response.getWriter().write("Server error"); } finally { httpclient.getConnectionManager().shutdown(); } } } catch (IOException e) { LOGGER.debug("Failed to provide MOTD file", e); } }
Source:
<code>private void logException(RuntimeException ex) { log.errorFormat("Command {0} execution failed. Exception: {1}", getCommandName(), ExceptionUtils.getMessage(ex)); <START> if (!(ex instanceof VDSExceptionBase)) { <END> log.error(ExceptionUtils.getStackTrace(ex)); } }</code><technical_language>I user of instanceof. overload method recive VDSExceptionBase? In places this function is used, information</technical_language>

Target:
private void logException(RuntimeException ex) { log.errorFormat("Command {0} execution failed. Exception: {1}", getCommandName(), ExceptionUtils.getMessage(ex)); }
Source:
<code>public GlusterVolumeProfileParameters(Guid clusterId, Guid volumeId) { <START> super(clusterId, volumeId); <END> this.nfs = false; }</code><technical_language>this( clusterId, volumenId, false);</technical_language>

Target:
public GlusterVolumeProfileParameters(Guid clusterId, Guid volumeId) { this(clusterId, volumeId, false); }
Source:
<code>public boolean isEOF() { <START> final boolean v3 = containerBlocksByteSize == 15 && alignmentContext.getReferenceContext().isUnmappedUnplaced() <END> && alignmentContext.getAlignmentStart() == 4542278 && blockCount == 1 && recordCount == 0; final boolean v2 = containerBlocksByteSize == 11 && alignmentContext.getReferenceContext().isUnmappedUnplaced() && alignmentContext.getAlignmentStart() == 4542278 && blockCount == 1 && recordCount == 0; return v3 || v2; }</code><technical_language>I 15, 11, 4542278 named constants</technical_language>

Target:
public boolean isEOF() { final boolean v3 = containerBlocksByteSize == CramIO.EOF_BLOCK_SIZE_V3 && alignmentContext.getReferenceContext().isUnmappedUnplaced() && alignmentContext.getAlignmentStart() == CramIO.EOF_ALIGNMENT_START && blockCount == 1 && recordCount == 0; final boolean v2 = containerBlocksByteSize == CramIO.EOF_BLOCK_SIZE_V2 && alignmentContext.getReferenceContext().isUnmappedUnplaced() && alignmentContext.getAlignmentStart() == CramIO.EOF_ALIGNMENT_START && blockCount == 1 && recordCount == 0; return v3 || v2; }
Source:
<code>public void define(WebService.NewController context) { WebService.NewAction action = context.createAction("groups") .setSince("5.2") .setInternal(true) .setDescription("Lists the groups with their permissions.<br>" + "This service defaults to global permissions, but can be limited to project permissions by providing project id or project key.<br> " + "This service defaults to all groups, but can be limited to groups with a specific permission by providing the desired permission.<br>" + "Requires one of the following permissions:" + "<ul>" + "<li>'Administer System'</li>" + "<li>'Administer' rights on the specified project</li>" + "</ul>") .addPagingParams(DEFAULT_PAGE_SIZE, RESULTS_MAX_SIZE) <START> .setResponseExample(Resources.getResource(getClass(), "groups-example.json")) <END> .setHandler(this); action.createParam(Param.TEXT_QUERY) .setMinimumLength(SEARCH_QUERY_MIN_LENGTH) .setDescription("Limit search to user names that contain the supplied string. <br/>" + "When this parameter is not set, only users having at least one permission are returned.") .setExampleValue("sonar"); createOrganizationParameter(action).setSince("6.2"); createPermissionParameter(action).setRequired(false); createProjectParameters(action); }</code><technical_language>remove addSearchQuery replace createSearchQuery in order .setMinimumLength(SEARCH_QUERY_MIN_LENGTH)</technical_language>

Target:
public void define(WebService.NewController context) { WebService.NewAction action = context.createAction("groups") .setSince("5.2") .setInternal(true) .setDescription("Lists the groups with their permissions.<br>" + "This service defaults to global permissions, but can be limited to project permissions by providing project id or project key.<br> " + "This service defaults to all groups, but can be limited to groups with a specific permission by providing the desired permission.<br>" + "Requires one of the following permissions:" + "<ul>" + "<li>'Administer System'</li>" + "<li>'Administer' rights on the specified project</li>" + "</ul>") .addPagingParams(DEFAULT_PAGE_SIZE, RESULTS_MAX_SIZE) .setResponseExample(Resources.getResource(getClass(), "groups-example.json")) .setHandler(this); action.createSearchQuery("sonar", "names") .setDescription("Limit search to group names that contain the supplied string. When this parameter is not set, only groups having at least one permission are returned.") .setMinimumLength(SEARCH_QUERY_MIN_LENGTH); createOrganizationParameter(action).setSince("6.2"); createPermissionParameter(action).setRequired(false); createProjectParameters(action); }
Source:
<code>public int hashCode() { <START> if (_attributes.isPresent()) { return Objects.hash(_nameOrRegex, new HashSet<>(_attributes.get())); } else { return Objects.hash(_nameOrRegex); } <END> }</code><technical_language>1. branches combined simplified to: java Objects.hash(_nameOrRegex, attributes.map(HashSet::new).orElse(null)); 2. this class is immutable, I suggest precompute cache this function returns in a private final field construction</technical_language>

Target:
public int hashCode() { return _hashCode; }
Source:
<code>public static Task<Task<?>> whenAny(Collection<? extends Task<?>> tasks) { if (tasks.size() == 0) { return Task.forResult(null); } final Task<Task<?>>.TaskCompletionSource firstCompleted = Task.create(); final AtomicBoolean isAnyTaskComplete = new AtomicBoolean(false); for (final Task<?> inputTask : tasks) { <START> ((Task<Object>)inputTask).continueWith(new Continuation<Object, Void>() { <END> @Override public Void then(Task<Object> task) { if (isAnyTaskComplete.compareAndSet(false, true)) { firstCompleted.setResult(inputTask); } return null; } }); } return firstCompleted.getTask(); }</code><technical_language>nit: space (Task<Object>) inputTask</technical_language>

Target:
public static Task<Task<?>> whenAny(Collection<? extends Task<?>> tasks) { if (tasks.size() == 0) { return Task.forResult(null); } final Task<Task<?>>.TaskCompletionSource firstCompleted = Task.create(); final AtomicBoolean isAnyTaskComplete = new AtomicBoolean(false); for (Task<?> task : tasks) { ((Task<Object>) task).continueWith(new Continuation<Object, Void>() { @Override public Void then(Task<Object> task) { if (isAnyTaskComplete.compareAndSet(false, true)) { firstCompleted.setResult(task); } return null; } }); } return firstCompleted.getTask(); }
Source:
<code>private String getAuthoritiesClaimName(Jwt jwt) { <START> for (String claimName : this.claimNames) { <END> if (jwt.containsClaim(claimName)) { return claimName; } } return null; }</code><technical_language>If application sets authorities claim name, is need search for it. run difficulties more like: java if (this.authoritiesClaimName != null) { return this.authoritiesClaimName; } for (String claimName : WELL_KNOWN..</technical_language>

Target:
private String getAuthoritiesClaimName(Jwt jwt) { if (this.authoritiesClaimName != null) { return this.authoritiesClaimName; } for (String claimName : WELL_KNOWN_AUTHORITIES_CLAIM_NAMES) { if (jwt.containsClaim(claimName)) { return claimName; } } return null; }
Source:
<code>public void visitNode(Tree tree) { Symbol sym; Arguments args; Tree methodName; if (tree.is(Tree.Kind.NEW_CLASS)) { NewClassTree nct = (NewClassTree) tree; sym = nct.constructorSymbol(); args = nct.arguments(); methodName = nct.identifier(); } else { MethodInvocationTree mit = (MethodInvocationTree) tree; sym = mit.symbol(); args = mit.arguments(); <START> methodName = ExpressionUtils.methodName(mit); <END> } if (sym.isMethodSymbol() && !args.isEmpty()) { ExpressionTree lastArg = args.get(args.size() - 1); JavaSymbol.MethodJavaSymbol methodSymbol = (JavaSymbol.MethodJavaSymbol) sym; MethodJavaType methodType = getMethodType(methodSymbol, methodName); checkInvokedMethod(methodSymbol, methodType, lastArg); } }</code><technical_language>This is a change of behavior : this imply another refactoring a test modification</technical_language>

Target:
public void visitNode(Tree tree) { Symbol sym; Arguments args; Tree methodName; if (tree.is(Tree.Kind.NEW_CLASS)) { NewClassTree nct = (NewClassTree) tree; sym = nct.constructorSymbol(); args = nct.arguments(); methodName = nct.identifier(); } else { MethodInvocationTree mit = (MethodInvocationTree) tree; sym = mit.symbol(); args = mit.arguments(); methodName = mit.methodSelect(); } if (sym.isMethodSymbol() && !args.isEmpty()) { ExpressionTree lastArg = args.get(args.size() - 1); JavaSymbol.MethodJavaSymbol methodSymbol = (JavaSymbol.MethodJavaSymbol) sym; MethodJavaType methodType = getMethodType(methodSymbol, methodName); checkInvokedMethod(methodSymbol, methodType, lastArg); } }
Source:
<code>protected void killSite(TestSite ts) { <START> TestingUtil.killCacheManagers(ts.cacheManagers); <END> }</code><technical_language>killCacheManagers method. stop __acl_cache soon fail destroy site</technical_language>

Target:
protected void killSite(TestSite ts) { ts.cacheManagers.forEach(Lifecycle::stop); }
Source:
<code>private boolean isPackageUpdated(Action action, EntityType newEntityType) { boolean updated; if (action == Action.CREATE) { updated = true; } else { EntityType currentEntityType = dataService.findOneById(EntityTypeMetadata.ENTITY_TYPE_META_DATA, newEntityType.getId(), EntityType.class); if (currentEntityType.getPackage() == null) { updated = newEntityType.getPackage() != null; } else { <START> updated = !currentEntityType.getPackage().equals(newEntityType.getPackage()); <END> } } return updated; }</code><technical_language>Compare package ID here</technical_language>

Target:
private boolean isPackageUpdated(Action action, EntityType newEntityType) { boolean updated; if (action == Action.CREATE) { updated = true; } else { EntityType currentEntityType = dataService.findOneById(EntityTypeMetadata.ENTITY_TYPE_META_DATA, newEntityType.getId(), EntityType.class); if (currentEntityType.getPackage() == null) { updated = newEntityType.getPackage() != null; } else { if (newEntityType.getPackage() == null) { updated = true; } else { updated = !currentEntityType.getPackage().getId().equals(newEntityType.getPackage().getId()); } } } return updated; }
Source:
<code>public FileDetailsPageObject clickVideoDetailsButton() { waitForElementByElement(videoDetailsButton); videoDetailsButton.click(); PageObjectLogging.log("clickVideoDetailsButton", "Video Details link is clicked", true); <START> return new FileDetailsPageObject(driver); <END> }</code><technical_language>FilePageObject (clean in versions of File\* page objects)</technical_language>

Target:
public FilePagePageObject clickVideoDetailsButton() { waitForElementByElement(videoDetailsButton); videoDetailsButton.click(); PageObjectLogging.log("clickVideoDetailsButton", "Video Details link is clicked", true); return new FilePagePageObject(driver); }
Source:
<code><START> public int getNumSplits(InputFormat inputFormat, @Nullable SplitHintSpec splitHintSpec) throws IOException <END> { int numSplits = 0; for (String inputPath : inputPaths) { Path path = new Path(inputPath); FileSystem fs = path.getFileSystem(configuration); final RemoteIterator<FileStatus> iterator = fs.listStatusIterator(path); numSplits += size(iterator); } return numSplits; }</code><technical_language>Is assumption baked in createSplits return a number of splits equal getNumSplits? If so, this implementation violate it, listing HDFS separately in method. underlying set of files changed</technical_language>

Target:
public int getNumSplits(InputFormat inputFormat, @Nullable SplitHintSpec splitHintSpec) throws IOException { cachePathsIfNeeded(); return cachedPaths.size(); }
Source:
<code><START> Set<AlternateHandle.Id> skipMe(Set<AlternateHandle.Id> skips) { <END> Set<AlternateHandle.Id> withMe = new HashSet<>(); if (skips != null) { withMe.addAll(skips); } withMe.add(getAlternateId()); return withMe; }</code><technical_language>this method declared private</technical_language>

Target:
private Set<AlternateHandle.Id> skipMe(Set<AlternateHandle.Id> skips) { Set<AlternateHandle.Id> withMe = new HashSet<>(); if (skips != null) { withMe.addAll(skips); } withMe.add(getAlternateId()); return withMe; }
Source:
<code>public List<TopWebSearchResult> getMostRecentWebSearches(DataSource dataSource, int count) throws SleuthkitCaseProviderException, TskCoreException { assertValidCount(count); List<TopWebSearchResult> results = caseProvider.get().getBlackboard().getArtifacts(ARTIFACT_TYPE.TSK_WEB_SEARCH_QUERY.getTypeID(), dataSource.getId()) .stream() <START> .map(artifact -> { <END> String searchString = DataSourceInfoUtilities.getStringOrNull(artifact, TYPE_TEXT); Date dateAccessed = DataSourceInfoUtilities.getDateOrNull(artifact, TYPE_DATETIME_ACCESSED); return (StringUtils.isNotBlank(searchString) && dateAccessed != null) ? new TopWebSearchResult(searchString, dateAccessed) : null; }) .filter(result -> result != null) .collect(Collectors.groupingBy((result) -> result.getSearchString().toUpperCase())) .entrySet() .stream() .map((entry) -> entry.getValue().stream().max(TOP_WEBSEARCH_RESULT_DATE_COMPARE).get()) .sorted(TOP_WEBSEARCH_RESULT_DATE_COMPARE.reversed()) .limit(count) .collect(Collectors.toList()); if (translationService.hasProvider()) { for (TopWebSearchResult result : results) { result.setTranslatedResult(getTranslationOrNull(result.getSearchString())); } } return results; }</code><technical_language>This difficult debug if issue. want consider revising</technical_language>

Target:
public List<TopWebSearchResult> getMostRecentWebSearches(DataSource dataSource, int count) throws SleuthkitCaseProviderException, TskCoreException { assertValidCount(count); List<BlackboardArtifact> webSearchArtifacts = caseProvider.get().getBlackboard() .getArtifacts(ARTIFACT_TYPE.TSK_WEB_SEARCH_QUERY.getTypeID(), dataSource.getId()); Collection<List<TopWebSearchResult>> resultGroups = webSearchArtifacts .stream() .map(DataSourceUserActivitySummary::getWebSearchResult) .filter(result -> result != null) .collect(Collectors.groupingBy((result) -> result.getSearchString().toUpperCase())) .values(); List<TopWebSearchResult> results = resultGroups .stream() .map((list) -> list.stream().max(TOP_WEBSEARCH_RESULT_DATE_COMPARE).get()) .sorted(TOP_WEBSEARCH_RESULT_DATE_COMPARE.reversed()) .limit(count) .collect(Collectors.toList()); if (translationService.hasProvider()) { for (TopWebSearchResult result : results) { result.setTranslatedResult(getTranslationOrNull(result.getSearchString())); } } return results; }
Source:
<code>public void read( NodeRecord record, PageCursor cursor, RecordLoad mode, int recordSize ) { int offset = cursor.getOffset(); byte headerByte = cursor.getByte(); boolean inUse = isInUse( headerByte ); record.setInUse( inUse ); if ( mode.shouldLoad( inUse ) ) { long nextRel = cursor.getInt() & 0xFFFFFFFFL; long nextProp = cursor.getInt() & 0xFFFFFFFFL; long relModifier = (headerByte & 0xEL) << 31; long propModifier = (headerByte & 0xF0L) << 28; long lsbLabels = cursor.getInt() & 0xFFFFFFFFL; long hsbLabels = cursor.getByte() & 0xFF; long labels = lsbLabels | (hsbLabels << 32); byte extra = cursor.getByte(); boolean dense = (extra & 0x1) > 0; record.initialize( inUse, BaseRecordFormat.longFromIntAndMod( nextProp, propModifier ), dense, BaseRecordFormat.longFromIntAndMod( nextRel, relModifier ), labels ); } <START> cursor.setOffset( offset ); <END> }</code><technical_language>Is necessary save restore offset? setOffset method bounds checking, nice avoid if possible</technical_language>

Target:
public void read( NodeRecord record, PageCursor cursor, RecordLoad mode, int recordSize ) { byte headerByte = cursor.getByte(); boolean inUse = isInUse( headerByte ); record.setInUse( inUse ); if ( mode.shouldLoad( inUse ) ) { long nextRel = cursor.getInt() & 0xFFFFFFFFL; long nextProp = cursor.getInt() & 0xFFFFFFFFL; long relModifier = (headerByte & 0xEL) << 31; long propModifier = (headerByte & 0xF0L) << 28; long lsbLabels = cursor.getInt() & 0xFFFFFFFFL; long hsbLabels = cursor.getByte() & 0xFF; long labels = lsbLabels | (hsbLabels << 32); byte extra = cursor.getByte(); boolean dense = (extra & 0x1) > 0; record.initialize( inUse, BaseRecordFormat.longFromIntAndMod( nextProp, propModifier ), dense, BaseRecordFormat.longFromIntAndMod( nextRel, relModifier ), labels ); } else { int nextOffset = cursor.getOffset() + recordSize - HEADER_SIZE; cursor.setOffset( nextOffset ); } }
Source:
<code>public Set<String> getDependencies() { <START> return ImmutableSet.of("workspace"); <END> }</code><technical_language>Please consider constant WorkspaceServiceTermination</technical_language>

Target:
public Set<String> getDependencies() { return ImmutableSet.of(WorkspaceServiceTermination.SERVICE_NAME); }
Source:
<code>public void init(Property[] provisioningProperties) throws IdentityProvisioningException { Properties configs = new Properties(); if (provisioningProperties != null && provisioningProperties.length > 0) { for (Property property : provisioningProperties) { if (GoogleConnectorConstants.PRIVATE_KEY.equals(property.getName())) { FileOutputStream fos = null; try { byte[] decodedBytes = Base64Utils.decode(property.getValue()); googlePrvKey = new File("googlePrvKey"); <START> fos = new FileOutputStream(googlePrvKey); <END> fos.write(decodedBytes); } catch (IOException e) { log.error("Error while generating private key file object", e); }finally { IdentityIOStreamUtils.closeOutputStream(fos); } } configs.put(property.getName(), property.getValue()); if (IdentityProvisioningConstants.JIT_PROVISIONING_ENABLED.equals(property .getName()) && "1".equals(property.getValue())) { jitProvisioningEnabled = true; } } } configHolder = new GoogleProvisioningConnectorConfig(configs); }</code><technical_language>flush() is removed ? flush() find some JDKs swallow exception if flush() is done close(). it</technical_language>

Target:
public void init(Property[] provisioningProperties) throws IdentityProvisioningException { Properties configs = new Properties(); if (provisioningProperties != null && provisioningProperties.length > 0) { for (Property property : provisioningProperties) { if (GoogleConnectorConstants.PRIVATE_KEY.equals(property.getName())) { FileOutputStream fos = null; try { byte[] decodedBytes = Base64Utils.decode(property.getValue()); googlePrvKey = new File("googlePrvKey"); fos = new FileOutputStream(googlePrvKey); fos.write(decodedBytes); } catch (IOException e) { log.error("Error while generating private key file object", e); }finally { IdentityIOStreamUtils.flushOutputStream(fos); IdentityIOStreamUtils.closeOutputStream(fos); } } configs.put(property.getName(), property.getValue()); if (IdentityProvisioningConstants.JIT_PROVISIONING_ENABLED.equals(property .getName()) && "1".equals(property.getValue())) { jitProvisioningEnabled = true; } } } configHolder = new GoogleProvisioningConnectorConfig(configs); }
Source:
<code>private void dumpCamelContext(String msg) { LOGGER.debug("\n\n*************** START: *****************", msg); List<RouteDefinition> routeDefinitions = camelContext.getRouteDefinitions(); if (routeDefinitions != null) { LOGGER.debug("Number of routes = {}", routeDefinitions.size()); for (RouteDefinition routeDef : routeDefinitions) { String routeId = routeDef.getId(); LOGGER.debug("route ID = {}", routeId); List<FromDefinition> routeInputs = routeDef.getInputs(); if (routeInputs.isEmpty()) { LOGGER.debug("routeInputs are EMPTY"); } else { for (FromDefinition fromDef : routeInputs) { LOGGER.debug("route input's URI = {}", fromDef.getUri()); } } ServiceStatus routeStatus = camelContext.getRouteStatus(routeId); if (routeStatus != null) { LOGGER.debug("Route ID is started = {}", routeId, routeStatus.isStarted()); } else { <START> LOGGER.debug("routeStamtus is NULL for routeId = {}", routeId); <END> } } } LOGGER.debug("*************** END: *****************\n\n", msg); }</code><technical_language>typo</technical_language>

Target:
private void dumpCamelContext(String msg) { LOGGER.debug("\n\n*************** START: *****************", msg); List<RouteDefinition> routeDefinitions = camelContext.getRouteDefinitions(); if (routeDefinitions != null) { LOGGER.debug("Number of routes = {}", routeDefinitions.size()); for (RouteDefinition routeDef : routeDefinitions) { String routeId = routeDef.getId(); LOGGER.debug("route ID = {}", routeId); List<FromDefinition> routeInputs = routeDef.getInputs(); if (routeInputs.isEmpty()) { LOGGER.debug("routeInputs are EMPTY"); } else { for (FromDefinition fromDef : routeInputs) { LOGGER.debug("route input's URI = {}", fromDef.getUri()); } } ServiceStatus routeStatus = camelContext.getRouteStatus(routeId); if (routeStatus != null) { LOGGER.debug("Route ID is started = {}", routeId, routeStatus.isStarted()); } else { LOGGER.debug("routeStatus is NULL for routeId = {}", routeId); } } } LOGGER.debug("*************** END: *****************\n\n", msg); }
Source:
<code>public SnapshotDto setVersion(@Nullable String version) { <START> checkArgument(version == null || version.length() <= 100, "\"%s\" is not a valid version name. " + <END> "The maximum length of version numbers is 100 characters.", version); this.version = version; return this; }</code><technical_language>Please form</technical_language>

Target:
public SnapshotDto setVersion(@Nullable String version) { if (version != null) { checkArgument(version.length() <= MAX_VERSION_LENGTH, "Event name length (%s) is longer than the maximum authorized (%s). '%s' was provided.", version.length(), MAX_VERSION_LENGTH, version); } this.version = version; return this; }
Source:
<code>public CRAMIterator(final SeekableStream seekableStream, final ReferenceSource referenceSource, final long[] coordinates) throws IOException { if (null == referenceSource) { this.referenceSource = new ReferenceSource(); } else <START> this.referenceSource = referenceSource; <END> this.countingInputStream = new CountingInputStream(seekableStream); final CramSpanContainerIterator containerIterator = CramSpanContainerIterator.fromFileSpan(seekableStream, coordinates); cramHeader = containerIterator.getCramHeader(); this.containerIterator = containerIterator; firstContainerOffset = containerIterator.getFirstContainerOffset(); records = new ArrayList<SAMRecord>(10000); normalizer = new CramNormalizer(cramHeader.getSamFileHeader(), referenceSource); parser = new ContainerParser(cramHeader.getSamFileHeader()); }</code><technical_language>note missing curly braces relying a a default-constructed ReferenceSource applies well</technical_language>

Target:
public CRAMIterator(final SeekableStream seekableStream, final ReferenceSource referenceSource, final long[] coordinates) throws IOException { if (null == referenceSource) { throw new CRAMException("A reference source is required for CRAM files"); } this.countingInputStream = new CountingInputStream(seekableStream); this.referenceSource = referenceSource; final CramSpanContainerIterator containerIterator = CramSpanContainerIterator.fromFileSpan(seekableStream, coordinates); cramHeader = containerIterator.getCramHeader(); this.containerIterator = containerIterator; firstContainerOffset = containerIterator.getFirstContainerOffset(); records = new ArrayList<SAMRecord>(10000); normalizer = new CramNormalizer(cramHeader.getSamFileHeader(), referenceSource); parser = new ContainerParser(cramHeader.getSamFileHeader()); }
Source:
<code>public HardwareLayout(JSONObject jsonObject) throws JSONException { logger.trace("HardwareLayout " + jsonObject.toString()); this.clusterName = jsonObject.getString("clusterName"); <START> this.version = jsonObject.getLong("version"); <END> this.datacenters = new ArrayList<Datacenter>(jsonObject.getJSONArray("datacenters").length()); for (int i = 0; i < jsonObject.getJSONArray("datacenters").length(); ++i) { this.datacenters.add(i, new Datacenter(this, jsonObject.getJSONArray("datacenters").getJSONObject(i))); } validate(); }</code><technical_language>I a default for version in PartitionLayout here. Is this purpose</technical_language>

Target:
public HardwareLayout(JSONObject jsonObject) throws JSONException { if (logger.isTraceEnabled()) logger.trace("HardwareLayout " + jsonObject.toString()); this.clusterName = jsonObject.getString("clusterName"); this.version = jsonObject.getLong("version"); this.datacenters = new ArrayList<Datacenter>(jsonObject.getJSONArray("datacenters").length()); for (int i = 0; i < jsonObject.getJSONArray("datacenters").length(); ++i) { this.datacenters.add(i, new Datacenter(this, jsonObject.getJSONArray("datacenters").getJSONObject(i))); } this.rawCapacityInBytes = calculateRawCapacityInBytes(); this.dataNodeCount = calculateDataNodeCount(); this.diskCount = calculateDiskCount(); this.dataNodeInHardStateCount = calculateDataNodeInHardStateCount(); this.diskInHardStateCount = calculateDiskInHardStateCount(); validate(); }
Source:
<code>private void addSubmodule(String url, String name, String revision, List<CopyFile> copyfiles, List<LinkFile> linkfiles, Set<String> groups, String recommendShallow) throws GitAPIException, IOException { if (repo.isBare()) { RepoProject proj = new RepoProject(url, name, revision, null, groups, recommendShallow); proj.addCopyFiles(copyfiles); proj.addLinkFiles(linkfiles); bareProjects.add(proj); } else { SubmoduleAddCommand add = git .submoduleAdd() .setPath(name) .setURI(url); if (monitor != null) add.setProgressMonitor(monitor); Repository subRepo = add.call(); if (revision != null) { try (Git sub = new Git(subRepo)) { sub.checkout().setName(findRef(revision, subRepo)) .call(); } subRepo.close(); git.add().addFilepattern(name).call(); } for (CopyFile copyfile : copyfiles) { copyfile.copy(); git.add().addFilepattern(copyfile.dest).call(); } <START> if (!linkfiles.isEmpty()) { throw new UnsupportedOperationException( JGitText.get().nonBareLinkFilesNotSupported); } <END> } }</code><technical_language>this moved other stuff in this block</technical_language>

Target:
private void addSubmodule(String url, String name, String revision, List<CopyFile> copyfiles, List<LinkFile> linkfiles, Set<String> groups, String recommendShallow) throws GitAPIException, IOException { if (repo.isBare()) { RepoProject proj = new RepoProject(url, name, revision, null, groups, recommendShallow); proj.addCopyFiles(copyfiles); proj.addLinkFiles(linkfiles); bareProjects.add(proj); } else { if (!linkfiles.isEmpty()) { throw new UnsupportedOperationException( JGitText.get().nonBareLinkFilesNotSupported); } SubmoduleAddCommand add = git .submoduleAdd() .setPath(name) .setURI(url); if (monitor != null) add.setProgressMonitor(monitor); Repository subRepo = add.call(); if (revision != null) { try (Git sub = new Git(subRepo)) { sub.checkout().setName(findRef(revision, subRepo)) .call(); } subRepo.close(); git.add().addFilepattern(name).call(); } for (CopyFile copyfile : copyfiles) { copyfile.copy(); git.add().addFilepattern(copyfile.dest).call(); } } }
Source:
<code><START> public Line(RevCommit startCommit, int lineNumber) { <END> commit = startCommit; number = lineNumber; }</code><technical_language>is this constructor public? If permit copying a Line (so application a "snapshot"), instead support some sort of copy constructor takes a Line object, a cloneLine() method returns a copied Line object. Otherwise, I this package-private. BlameGenerator need construct a Line object</technical_language>

Target:
Line(RevCommit startCommit, int lineNumber) { commit = startCommit; number = lineNumber; }
Source:
<code>public RegistrationAuth requireCreate(ClientRegistrationContext context) { init(); RegistrationAuth registrationAuth = RegistrationAuth.ANONYMOUS; if (isBearerToken()) { checkClientProtocol(); if (hasRole(AdminRoles.MANAGE_CLIENTS, AdminRoles.CREATE_CLIENT)) { registrationAuth = RegistrationAuth.AUTHENTICATED; } else { throw forbidden(); } } else if (isInitialAccessToken()) { if (initialAccessModel.getRemainingCount() > 0) { if (initialAccessModel.getExpiration() == 0 || (initialAccessModel.getTimestamp() + initialAccessModel.getExpiration()) > Time.currentTime()) { registrationAuth = RegistrationAuth.AUTHENTICATED; } else { throw unauthorized("Expired initial access token"); } } else { throw unauthorized("No remaining count on initial access token"); } } try { <START> ClientPolicyManager.triggerBeforeRegister(context, registrationAuth); <END> } catch (ClientRegistrationPolicyException | ClientPolicyException crpe) { throw forbidden(crpe.getMessage()); } return registrationAuth; }</code><technical_language>I find ClientPolicyManager replaced ClientRegistrationPolicyManager yet? explain client registration policies executed now</technical_language>

Target:
public RegistrationAuth requireCreate(ClientRegistrationContext context) { init(); RegistrationAuth registrationAuth = RegistrationAuth.ANONYMOUS; if (isBearerToken()) { checkClientProtocol(); if (hasRole(AdminRoles.MANAGE_CLIENTS, AdminRoles.CREATE_CLIENT)) { registrationAuth = RegistrationAuth.AUTHENTICATED; } else { throw forbidden(); } } else if (isInitialAccessToken()) { if (initialAccessModel.getRemainingCount() > 0) { if (initialAccessModel.getExpiration() == 0 || (initialAccessModel.getTimestamp() + initialAccessModel.getExpiration()) > Time.currentTime()) { registrationAuth = RegistrationAuth.AUTHENTICATED; } else { throw unauthorized("Expired initial access token"); } } else { throw unauthorized("No remaining count on initial access token"); } } try { session.clientPolicy().triggerOnEvent(new DynamicClientRegisterContext(context,registrationAuth)); ClientRegistrationPolicyManager.triggerBeforeRegister(context, registrationAuth); } catch (ClientRegistrationPolicyException | ClientPolicyException crpe) { throw forbidden(crpe.getMessage()); } return registrationAuth; }
Source:
<code><START> public String getPreview() { <END> StringBuilder bld= new StringBuilder(); bld.append("\n"); if (isEnabled(CleanUpConstants.USE_DIRECTLY_MAP_METHOD)) { bld.append("int x = map.size();\n"); bld.append("if (map.containsKey(\"hello\")) {\n"); bld.append(" map.remove(\"hello\");\n"); bld.append("}\n"); bld.append("map.clear();\n"); bld.append("if (map.isEmpty()) {\n"); } else { bld.append("int x = map.keySet().size();\n"); bld.append("if (map.keySet().contains(\"hello\")) {\n"); bld.append(" map.keySet().remove(\"hello\");\n"); bld.append("}\n"); bld.append("map.keySet().clear();\n"); bld.append("if (map.keySet().isEmpty()) {\n"); } bld.append(" x++;\n"); bld.append("}\n"); return bld.toString(); }</code><technical_language>Is worth updating preview example values()? need for cases IMO, get idea other keySet() examples</technical_language>

Target:
public String getPreview() { StringBuilder bld= new StringBuilder(); bld.append("\n"); if (isEnabled(CleanUpConstants.USE_DIRECTLY_MAP_METHOD)) { bld.append("int x = map.size();\n"); bld.append("if (map.containsKey(\"hello\")) {\n"); bld.append(" map.remove(\"hello\");\n"); bld.append("}\n"); bld.append("map.clear();\n"); bld.append("map.clear();\n"); bld.append("if (map.isEmpty()) {\n"); } else { bld.append("int x = map.keySet().size();\n"); bld.append("if (map.keySet().contains(\"hello\")) {\n"); bld.append(" map.keySet().remove(\"hello\");\n"); bld.append("}\n"); bld.append("map.keySet().clear();\n"); bld.append("map.values().clear();\n"); bld.append("if (map.keySet().isEmpty()) {\n"); } bld.append(" x++;\n"); bld.append("}\n"); return bld.toString(); }
Source:
<code>public String getSwaggerDocument(String apiName, int tenantId) throws APIException { API api = getSynapseAPIByName(apiName); if (api == null) { throw new APIException("API with name \"" + apiName + "\" does not exists."); } String resourcePath = getSwaggerResourcePath(api); String swaggerJsonString = null; if (resourcePath.startsWith(CONFIG_REG_PREFIX) || resourcePath.startsWith(GOV_REG_PREFIX)) { try { swaggerJsonString = getResourceFromRegistry(resourcePath, tenantId); } catch (RegistryException e) { handleException(log, "Could not get swagger document", e); } } else { try { swaggerJsonString = readFromURI(resourcePath); } catch (IOException e) { log.error("Error occurred while reading swagger definition from: " + resourcePath, e); } } if (swaggerJsonString == null) { if (log.isDebugEnabled()) { log.debug("Generate swagger definition for the API : " + apiName); } try { AxisConfiguration axisConfiguration = ConfigHolder.getInstance().getAxisConfiguration(); <START> ServerConfig serverConfig = new CarbonServerConfig(axisConfiguration); <END> JSONObject jsonDefinition = new JSONObject(new GenericApiObjectDefinition(api, serverConfig).getDefinitionMap()); swaggerJsonString = jsonDefinition.toString(); } catch (AxisFault axisFault) { handleException(log, "Error occurred while generating swagger definition", axisFault); } } return swaggerJsonString; }</code><technical_language>get instance a singleton if</technical_language>

Target:
public String getSwaggerDocument(String apiName, int tenantId) throws APIException { API api = getSynapseAPIByName(apiName); if (api == null) { throw new APIException("API with name \"" + apiName + "\" does not exists."); } String resourcePath = getSwaggerResourcePath(api); String swaggerJsonString = null; if (resourcePath.startsWith(CONFIG_REG_PREFIX) || resourcePath.startsWith(GOV_REG_PREFIX)) { try { swaggerJsonString = getResourceFromRegistry(resourcePath, tenantId); } catch (RegistryException e) { handleException(log, "Could not get swagger document", e); } } else { try { swaggerJsonString = readFromURI(resourcePath); } catch (IOException e) { log.error("Error occurred while reading swagger definition from: " + resourcePath, e); } } if (swaggerJsonString == null) { if (log.isDebugEnabled()) { log.debug("Generate swagger definition for the API : " + apiName); } try { ServerConfig serverConfig = new CarbonServerConfig(); JSONObject jsonDefinition = new JSONObject(new GenericApiObjectDefinition(api, serverConfig).getDefinitionMap()); swaggerJsonString = jsonDefinition.toString(); } catch (AxisFault axisFault) { handleException(log, "Error occurred while generating swagger definition", axisFault); } } return swaggerJsonString; }
Source:
<code>public void init() throws Exception { serverPropertyMap.put("-DportOffset",Integer.toString(portOffset)); AutomationContext autoCtx = new AutomationContext(); CarbonTestServerManager server = new CarbonTestServerManager(autoCtx, System.getProperty("carbon.zip"), serverPropertyMap); asServerManager.startServers(server); carbonHome = server.getCarbonHome(); context = new AutomationContext("AS", "appServerInstance0002", ContextXpathConstants.SUPER_TENANT, ContextXpathConstants.ADMIN); <START> initializeNecessaryVariables(); <END> resourceAdminServiceClient = new ResourceAdminServiceClient(backendURLForInstance002, sessionCookieForInstance002); }</code><technical_language>rename this method more specific method name</technical_language>

Target:
public void init() throws Exception { serverPropertyMap.put("-DportOffset", Integer.toString(portOffset)); AutomationContext autoCtx = new AutomationContext(); CarbonTestServerManager server = new CarbonTestServerManager(autoCtx, System.getProperty("carbon.zip"), serverPropertyMap); asServerManager.startServers(server); carbonHome = server.getCarbonHome(); context = new AutomationContext(ASIntegrationConstants.AS_PRODUCT_GROUP, ASIntegrationConstants.AS_INSTANCE_0002, ContextXpathConstants.SUPER_TENANT, ContextXpathConstants.ADMIN); initEnvironment(); resourceAdminServiceClient = new ResourceAdminServiceClient(backendURLForInstance002, sessionCookieForInstance002); }
Source:
<code>public void characters(char[] ch, int start, int length) { <START> if (currentQName.indexOf("BinData") < 0 || inPixels == false) { <END> xmlBuffer.append(new String(ch, start, length)); } }</code><technical_language>if fiddling put shortcut logic</technical_language>

Target:
public void characters(char[] ch, int start, int length) { if (!inPixels || currentQName.indexOf("BinData") < 0) { xmlBuffer.append(new String(ch, start, length)); } }