auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testMany() { WeightedDoubleReservoirSample reservoir = new WeightedDoubleReservoirSample(200); long streamLength = 1_000_000; for (int i = 0; i < streamLength; ++i) { <START> assertEquals(reservoir.getTotalPopulationWeight(), (double) i); <END> reservoir.add(i, 1.0); } double[] quantized = new double[4]; int count = 0; for (double sample : reservoir.getSamples()) { ++count; int index = (int) (4.0 * sample / (streamLength + 1)); ++quantized[index]; } assertEquals(count, 200, format("Number of samples should be full: got=%s, expected=%s", count, 200)); int expectedMin = 25; for (int i = 0; i < 4; ++i) { assertTrue(quantized[i] > expectedMin, format("Expected quantized[i] > got: i=%s, quantized=%s, got=%s", i, quantized[i], 35)); } }</code><technical_language>nit: need cast int double. Java do automatically</technical_language>

Target:
public void testMany() { WeightedDoubleReservoirSample reservoir = new WeightedDoubleReservoirSample(200); long streamLength = 1_000_000; for (int i = 0; i < streamLength; ++i) { assertEquals(reservoir.getTotalPopulationWeight(), i, 0.0001); reservoir.add(i, 1.0); } double[] quantized = new double[4]; int count = 0; for (double sample : reservoir.getSamples()) { ++count; int index = (int) (4.0 * sample / (streamLength + 1)); ++quantized[index]; } assertEquals(count, 200, format("Number of samples should be full: got=%s, expected=%s", count, 200)); int expectedMin = 25; for (int i = 0; i < 4; ++i) { assertTrue(quantized[i] > expectedMin, format("Expected quantized[i] > got: i=%s, quantized=%s, got=%s", i, quantized[i], 35)); } }
Source:
<code>public void execute(String[] args, ConsoleReader reader) throws Exception { ApplicationReport appReport = currentApp; String target = args[1]; String logLevel = args[2]; StramAgent.StramUriSpec uriSpec = new StramAgent.StramUriSpec(); uriSpec = uriSpec.path(StramWebServices.PATH_LOGGERS); final JSONObject request = buildRequest(target, logLevel); JSONObject response = getResource(uriSpec, appReport, new WebServicesClient.WebServicesHandler<JSONObject>() { @Override public JSONObject process(WebResource.Builder webResource, Class<JSONObject> clazz) { return webResource.accept(MediaType.APPLICATION_JSON).post(JSONObject.class, request); } }); <START> System.out.println(response); <END> }</code><technical_language>Please other commands check consolePresent printJson</technical_language>

Target:
public void execute(String[] args, ConsoleReader reader) throws Exception { ApplicationReport appReport = currentApp; String target = args[1]; String logLevel = args[2]; StramAgent.StramUriSpec uriSpec = new StramAgent.StramUriSpec(); uriSpec = uriSpec.path(StramWebServices.PATH_LOGGERS); final JSONObject request = buildRequest(target, logLevel); JSONObject response = getResource(uriSpec, appReport, new WebServicesClient.WebServicesHandler<JSONObject>() { @Override public JSONObject process(WebResource.Builder webResource, Class<JSONObject> clazz) { return webResource.accept(MediaType.APPLICATION_JSON).post(JSONObject.class, request); } }); printJson(response); }
Source:
<code>private Iterable<Contents> filterContents(final Iterable<Contents> contents, final Path outputPath) throws IOException { final Iterable<Path> localFiles = Utils.listObjectsForDirectory(outputPath); <START> final HashMap<String, Path> mapLocalFiles = new HashMap<>(); <END> for (final Path localFile : localFiles) { mapLocalFiles.put(Utils.getFileName(outputPath, localFile), localFile); } final ArrayList<Contents> filteredContents = new ArrayList<>(); for (final Contents content : contents) { final Path filePath = mapLocalFiles.get(content.getKey()); if (filePath == null) { filteredContents.add(content); } else if (SyncUtils.needToSync(filePath, content, false)) { LOG.info("Syncing new version of " + filePath.toString()); filteredContents.add(content); } else { LOG.info("No need to sync " + filePath.toString()); } } return filteredContents; }</code><technical_language>Replace HashMap Map left side</technical_language>

Target:
private Iterable<Contents> filterContents(final Iterable<Contents> contents, final Path outputPath) throws IOException { final Iterable<Path> localFiles = Utils.listObjectsForDirectory(outputPath); final Map<String, Path> mapLocalFiles = new HashMap<>(); for (final Path localFile : localFiles) { mapLocalFiles.put(Utils.getFileName(outputPath, localFile), localFile); } final List<Contents> filteredContents = new ArrayList<>(); for (final Contents content : contents) { final Path filePath = mapLocalFiles.get(content.getKey()); if (filePath == null) { filteredContents.add(content); } else if (SyncUtils.isNewFile(filePath, content, false)) { LOG.info("Syncing new version of " + filePath.toString()); filteredContents.add(content); } else { LOG.info("No need to sync " + filePath.toString()); } } return filteredContents; }
Source:
<code>public void setup() throws Exception { workspaceQueryMigration = new WorkspaceQueryMigration(catalogFramework, filterBuilder, xmlInputTransformer); workspaceQueryMigration.setSecurity(security); when(security.runAsAdmin(any(PrivilegedAction.class))).thenReturn(subject); doAnswer( new Answer<Void>() { public Void answer(InvocationOnMock invocation) { ((Runnable) invocation.getArgument(0)).run(); return null; } }) .when(subject) .execute(any(Runnable.class)); workspace = getWorkspaceMetacard(WORKSPACE_ID); doReturn(workspace).when(result).getMetacard(); doReturn(Collections.singletonList(result)).when(queryResponse).getResults(); <START> workspace = getWorkspaceMetacard(WORKSPACE_ID); <END> doReturn(workspace).when(result).getMetacard(); doReturn(queryResponse).when(catalogFramework).query(any(QueryRequest.class)); doReturn(new MetacardImpl()).when(xmlInputTransformer).transform(any(InputStream.class)); Metacard query1 = getQueryMetacard("queryId1"); Metacard query2 = getQueryMetacard("queryId2"); CreateResponse createResponse = mock(CreateResponse.class); doReturn(ImmutableList.of(query1, query2)).when(createResponse).getCreatedMetacards(); doReturn(createResponse).when(catalogFramework).create(any(CreateRequest.class)); }</code><technical_language>lines necessary</technical_language>

Target:
public void setup() throws Exception { workspaceQueryMigration = new WorkspaceQueryMigration(catalogFramework, filterBuilder, xmlInputTransformer, security); when(security.runAsAdmin(any(PrivilegedAction.class))).thenReturn(subject); doAnswer( new Answer<Void>() { public Void answer(InvocationOnMock invocation) { ((Runnable) invocation.getArgument(0)).run(); return null; } }) .when(subject) .execute(any(Runnable.class)); workspace = getWorkspaceMetacard(WORKSPACE_ID); doReturn(workspace).when(result).getMetacard(); doReturn(Collections.singletonList(result)).when(queryResponse).getResults(); doReturn(queryResponse).when(catalogFramework).query(any(QueryRequest.class)); doReturn(new MetacardImpl()).when(xmlInputTransformer).transform(any(InputStream.class)); Metacard query1 = getQueryMetacard("queryId1"); Metacard query2 = getQueryMetacard("queryId2"); CreateResponse createResponse = mock(CreateResponse.class); doReturn(ImmutableList.of(query1, query2)).when(createResponse).getCreatedMetacards(); doReturn(createResponse).when(catalogFramework).create(any(CreateRequest.class)); }
Source:
<code>public void unindexMarkers(final IResource resource) { if(resource == null) { return; } try { Logger.debugIndexing("Unindexing markers on after removal...", resource.getFullPath()); final Term elementTypeTerm = LuceneDocumentFactory.getMarkerTypeTerm(); final Term resourcePathTerm = LuceneDocumentFactory.getResourcePathTerm(resource); final BooleanQuery deleteResourceMarkersQuery = new BooleanQuery(); deleteResourceMarkersQuery.add(new BooleanClause(new TermQuery(elementTypeTerm), Occur.MUST)); deleteResourceMarkersQuery.add(new BooleanClause(new TermQuery(resourcePathTerm), Occur.MUST)); indexWriter.deleteDocuments(deleteResourceMarkersQuery); indexWriter.commit(); <START> } catch (Exception e) { <END> Logger.error("Failed to unindex the Resource " + resource.getFullPath(), e); } finally { Logger.traceIndexing("Done unindexing {}.", resource.getFullPath()); } }</code><technical_language>specific exception here</technical_language>

Target:
public void unindexMarkers(final IResource resource) { if(resource == null) { return; } try { Logger.debugIndexing("Unindexing markers on after removal...", resource.getFullPath()); final Term elementTypeTerm = LuceneDocumentFactory.getMarkerTypeTerm(); final Term resourcePathTerm = LuceneDocumentFactory.getResourcePathTerm(resource); final BooleanQuery deleteResourceMarkersQuery = new BooleanQuery(); deleteResourceMarkersQuery.add(new BooleanClause(new TermQuery(elementTypeTerm), Occur.MUST)); deleteResourceMarkersQuery.add(new BooleanClause(new TermQuery(resourcePathTerm), Occur.MUST)); indexWriter.deleteDocuments(deleteResourceMarkersQuery); indexWriter.commit(); } catch (IOException e) { Logger.error("Failed to unindex the Resource " + resource.getFullPath(), e); } finally { Logger.traceIndexing("Done unindexing {}.", resource.getFullPath()); } }
Source:
<code><START> protected void handlePropertyChangeEvent(PropertyChangeEvent event) { <END> String key = event.getProperty(); if (key.equals(UNMERGEABLE_DIFF_COLOR_THEME_KEY) || key.equals(REQUIRED_DIFF_COLOR_THEME_KEY) || key.equals(INCOMING_CHANGE_COLOR_THEME_KEY) || key.equals(CONFLICTING_CHANGE_COLOR_THEME_KEY) || key.equals(OUTGOING_CHANGE_COLOR_THEME_KEY) || key.equals(RESOLVED_CHANGE_COLOR_THEME_KEY)) { updateColors(); } }</code><technical_language>key of changed color, give update colors update</technical_language>

Target:
protected void handlePropertyChangeEvent(PropertyChangeEvent event) { String propertyKey = event.getProperty(); ColorChangeEvent colorEvent = new ColorChangeEvent(); if (propertyKey.equals(UNMERGEABLE_DIFF_COLOR_THEME_KEY)) { changeUnmergeableColor(colorEvent); } else if (propertyKey.equals(INCOMING_CHANGE_COLOR_THEME_KEY)) { changeIncomingColor(colorEvent); } else if (propertyKey.equals(REQUIRED_DIFF_COLOR_THEME_KEY)) { changeRequiredColor(colorEvent); } else if (propertyKey.equals(CONFLICTING_CHANGE_COLOR_THEME_KEY)) { changeConflictingColor(colorEvent); } else if (propertyKey.equals(OUTGOING_CHANGE_COLOR_THEME_KEY)) { changeOutgoingColor(colorEvent); } if (colorEvent.isAffectingEvent()) { if (eventBus != null) { eventBus.post(colorEvent); } } }
Source:
<code>private static GroupsRequest toGroupsRequest(Request request) { return GroupsRequest.builder() <START> .setLogin(request.mandatoryParam(PARAM_LOGIN)) <END> .setOrganization(request.param(PARAM_ORGANIZATION)) .setSelected(request.mandatoryParam(SELECTED)) .setQuery(request.param(TEXT_QUERY)) .setPage(request.mandatoryParamAsInt(PAGE)) .setPageSize(request.mandatoryParamAsInt(PAGE_SIZE)) .build(); }</code><technical_language>![MAJOR](<LINK_1> 'Severity: MAJOR') Call "org.isPresent()" accessing value. [![rule](<LINK_2>](<LINK_0></technical_language>

Target:
private static GroupsRequest toGroupsRequest(Request request) { int pageSize = request.mandatoryParamAsInt(PAGE_SIZE); checkArgument(pageSize <= MAX_PAGE_SIZE, "The '%s' parameter must be less than %s", PAGE_SIZE, MAX_PAGE_SIZE); return GroupsRequest.builder() .setLogin(request.mandatoryParam(PARAM_LOGIN)) .setOrganization(request.param(PARAM_ORGANIZATION)) .setSelected(request.mandatoryParam(SELECTED)) .setQuery(request.param(TEXT_QUERY)) .setPage(request.mandatoryParamAsInt(PAGE)) .setPageSize(pageSize) .build(); }
Source:
<code>public void checkIfCanBeExecutedOnChannel(Channel channel) throws IOException { super.checkIfCanBeExecutedOnChannel(channel); if (channel.isClosingOrClosed()) { <START> throw new IOException("The request cannot be executed on channel " + channel + ". The channel is closing down or has closed down"); <END> } }</code><technical_language>this duplicate check in Channel.call (as check in Channel.send)? I unclear check times in of call. (And this ChannelClosedException.)</technical_language>

Target:
public void checkIfCanBeExecutedOnChannel(Channel channel) throws IOException { super.checkIfCanBeExecutedOnChannel(channel); if (channel.isClosingOrClosed()) { throw new ChannelClosedException("The request cannot be executed on channel " + channel + ". " + "The channel is closing down or has closed down", channel.getCloseRequestCause()); } }
Source:
<code>public ListenableFuture<Boolean> update(final LabelMeta meta) { return transform(getLabelMeta(meta.type(), meta.identifier()), new AsyncFunction<Optional<LabelMeta>, Boolean>() { @Override public ListenableFuture<Boolean> apply(final Optional<LabelMeta> storedMeta) throws Exception { if (!storedMeta.isPresent()) { <START> LOG.debug("{} was not found.", meta); <END> return Futures.immediateFuture(Boolean.FALSE); } if (!storedMeta.get().equals(meta)) { return store.updateMeta(meta); } LOG.debug("{} does not have any changes, skipping update", meta); return Futures.immediateFuture(Boolean.FALSE); } }); }</code><technical_language>raise log level warn? If user update a meta is missing nice give a bigger splash missing</technical_language>

Target:
public ListenableFuture<Boolean> update(final LabelMeta meta) { return transform(getLabelMeta(meta.type(), meta.identifier()), new AsyncFunction<Optional<LabelMeta>, Boolean>() { @Override public ListenableFuture<Boolean> apply(final Optional<LabelMeta> storedMeta) throws Exception { if (!storedMeta.isPresent()) { return store.updateMeta(meta); } if (!storedMeta.get().equals(meta)) { return store.updateMeta(meta); } LOG.debug("{} does not have any changes, skipping update", meta); return Futures.immediateFuture(Boolean.FALSE); } }); }
Source:
<code>private void sendPower() { TileEntity tile = getTileBuffer(currentDirection).getTile(); if (tile == null) { return; } if (getClass() == tile.getClass()) { TileEngineBase_BC8 other = (TileEngineBase_BC8) tile; if (currentDirection == other.currentDirection) { other.power += extractPower(0, power, true); } return; } IMjReceiver receiver = getReceiverToPower(tile, currentDirection); <START> if (receiver != null && mjConnector.canConnect(receiver) && receiver.canConnect(mjConnector)) { <END> long extracted = getPowerToExtract(true); if (extracted > 0) { long excess = receiver.receivePower(extracted, false); extractPower(extracted - excess, extracted - excess, true); } } }</code><technical_language>This check is partially implemented in getReceiverToPower -- addition there</technical_language>

Target:
private void sendPower() { TileEntity tile = getTileBuffer(currentDirection).getTile(); if (tile == null) { return; } if (getClass() == tile.getClass()) { TileEngineBase_BC8 other = (TileEngineBase_BC8) tile; if (currentDirection == other.currentDirection) { other.power += extractPower(0, power, true); } return; } IMjReceiver receiver = getReceiverToPower(tile, currentDirection); if (receiver != null) { long extracted = getPowerToExtract(true); if (extracted > 0) { long excess = receiver.receivePower(extracted, false); extractPower(extracted - excess, extracted - excess, true); } } }
Source:
<code>public synchronized BufferedMutator getBufferedMutator(BufferedMutatorParams params) throws IOException { TableName tableName = params.getTableName(); if (tableName == null) { throw new IllegalArgumentException("TableName cannot be null."); } long maxHeapSize = params.getWriteBufferSize(); if (maxHeapSize == BufferedMutatorParams.UNSET) { params.writeBufferSize(tableConfig.getWriteBufferSize()); maxHeapSize = params.getWriteBufferSize(); } int defaultRpcCount = AsyncExecutor.MAX_INFLIGHT_RPCS_DEFAULT * options.getChannelCount(); int maxInflightRpcs = conf.getInt(MAX_INFLIGHT_RPCS_KEY, defaultRpcCount); final long id = SEQUENCE_GENERATOR.incrementAndGet(); if (this.bufferedMutatorExecutorService == null) { <START> this.bufferedMutatorExecutorService = BigtableBufferedMutator.createExecutorService(options); <END> } BigtableBufferedMutator bigtableBufferedMutator = new BigtableBufferedMutator( session.getDataClient(), createAdapter(tableName), conf, options, params.getListener(), new HeapSizeManager(maxHeapSize, maxInflightRpcs)) { @Override public void close() throws IOException { try { super.close(); } finally { ACTIVE_BUFFERED_MUTATORS.remove(id); } } }; ACTIVE_BUFFERED_MUTATORS.put(id, bigtableBufferedMutator); return bigtableBufferedMutator; }</code><technical_language>this is created, (except .shutdown())</technical_language>

Target:
public synchronized BufferedMutator getBufferedMutator(BufferedMutatorParams params) throws IOException { TableName tableName = params.getTableName(); if (tableName == null) { throw new IllegalArgumentException("TableName cannot be null."); } long maxHeapSize = params.getWriteBufferSize(); if (maxHeapSize == BufferedMutatorParams.UNSET) { params.writeBufferSize(tableConfig.getWriteBufferSize()); maxHeapSize = params.getWriteBufferSize(); } int defaultRpcCount = AsyncExecutor.MAX_INFLIGHT_RPCS_DEFAULT * options.getChannelCount(); int maxInflightRpcs = conf.getInt(MAX_INFLIGHT_RPCS_KEY, defaultRpcCount); final long id = SEQUENCE_GENERATOR.incrementAndGet(); if (this.bufferedMutatorExecutorService == null && options.getAsyncMutatorCount() > 0) { bufferedMutatorExecutorService = Executors.newCachedThreadPool( new ThreadFactoryBuilder() .setNameFormat("BigtableBufferedMutator-worker-%s") .setDaemon(true) .build()); } BigtableBufferedMutator bigtableBufferedMutator = new BigtableBufferedMutator( session.getDataClient(), createAdapter(tableName), conf, options, params.getListener(), new HeapSizeManager(maxHeapSize, maxInflightRpcs), bufferedMutatorExecutorService) { @Override public void close() throws IOException { try { super.close(); } finally { ACTIVE_BUFFERED_MUTATORS.remove(id); } } }; ACTIVE_BUFFERED_MUTATORS.put(id, bigtableBufferedMutator); return bigtableBufferedMutator; }
Source:
<code>public Iterable<UV> values() { Map<UK, UV> userMap = stateTable.get(currentNamespace); <START> return userMap == null ? emptyState.values() : userMap.values(); <END> }</code><technical_language>Collections.emptyList() ? for return results</technical_language>

Target:
public Iterable<UV> values() { Map<UK, UV> userMap = stateTable.get(currentNamespace); return userMap == null ? Collections.emptySet() : userMap.values(); }
Source:
<code>public HiveBucketProperty toTableBucketProperty() { if (isVirtuallyBucketed(columns)) { <START> return null; <END> } return new HiveBucketProperty( columns.stream() .map(HiveColumnHandle::getName) .collect(toList()), tableBucketCount, ImmutableList.of()); }</code><technical_language>alternative approach is check a virtual bucket here: <LINK_0></technical_language>

Target:
public HiveBucketProperty toTableBucketProperty() { checkState(!isVirtuallyBucketed(), "Virtual bucket does not have table bucket property"); return new HiveBucketProperty( columns.stream() .map(HiveColumnHandle::getName) .collect(toList()), tableBucketCount, ImmutableList.of()); }
Source:
<code>public static void main(String[] args) { <START> if (args == null || args.length == 0) { <END> printHelp(); } run(args); System.exit(0); }</code><technical_language>I args null, it</technical_language>

Target:
public static void main(String[] args) { if (args == null || args.length == 0) { printHelpAndExit(); } if (Arrays.asList(args).contains("-h") || Arrays.asList(args).contains("--help")) { printHelpAndExit(); } run(args); System.exit(0); }
Source:
<code><START> public @NonNull ProfileTypeUID getUID() { <END> return profileTypeUID; }</code><technical_language>I assume remove @NonNull @NonNullByDefault. for other ones..</technical_language>

Target:
public ProfileTypeUID getUID() { return profileTypeUID; }
Source:
<code>public Optional<Closeable> acquireReferences() { Closer closer = Closer.create(); boolean acquireFailed = baseSegment.acquireReferences().map(closeable -> { closer.register(closeable); return false; }).orElse(true); for (JoinableClause claws : clauses) { if (acquireFailed) { break; } <START> acquireFailed |= claws.acquireReferences().map(closeable -> { <END> closer.register(closeable); return false; }).orElse(true); } if (acquireFailed) { CloseQuietly.close(closer); return Optional.empty(); } else { return Optional.of(closer); } }</code><technical_language>Hmm, contract of acquireReferences() clarify this method throw exception? Otherwise, closer safely closed exceptions</technical_language>

Target:
public Optional<Closeable> acquireReferences() { Closer closer = Closer.create(); try { boolean acquireFailed = baseSegment.acquireReferences().map(closeable -> { closer.register(closeable); return false; }).orElse(true); for (JoinableClause joinClause : clauses) { if (acquireFailed) { break; } acquireFailed |= joinClause.acquireReferences().map(closeable -> { closer.register(closeable); return false; }).orElse(true); } if (acquireFailed) { CloseQuietly.close(closer); return Optional.empty(); } else { return Optional.of(closer); } } catch (Exception ex) { CloseQuietly.close(closer); return Optional.empty(); } }
Source:
<code>private static String resolve(GoExpression argument) { if (argument instanceof GoStringLiteral) { return argument.getText(); } if (!(argument instanceof GoReferenceExpression)) { return null; } PsiReference resolved = argument.getReference(); if (resolved == null) { return null; } PsiElement element = resolved.resolve(); <START> while (element != null && <END> element.getReference() != null && element.getReference().resolve() != null) { resolved = element.getReference(); element = resolved.resolve(); } if (element == null) { return null; } if (element.getReference() != null) { resolved = element.getReference(); if (resolved instanceof GoVarReference) { if (resolved.getElement().getParent() instanceof GoShortVarDeclaration) { element = resolved.getElement(); GoShortVarDeclaration shortVarDeclaration = (GoShortVarDeclaration)resolved.getElement().getParent(); int varPosition = shortVarDeclaration.getVarDefinitionList().indexOf(element); return resolve(shortVarDeclaration.getExpressionList().get(varPosition)); } return ""; } } else if (element instanceof GoConstDefinition) { if (element.getParent() instanceof GoConstSpec) { GoConstSpec constSpec = (GoConstSpec)element.getParent(); int constPosition = constSpec.getConstDefinitionList().indexOf(element); return resolve(constSpec.getExpressionList().get(constPosition)); } return ""; } return null; }</code><technical_language>I understand stands for. test example? covered moment: <LINK_0></technical_language>

Target:
private static String resolve(GoExpression argument) { if (argument instanceof GoStringLiteral) return argument.getText(); if (argument.getReference() == null) return null; PsiElement resolved = argument.getReference().resolve(); if (resolved instanceof GoVarDefinition) { return getValue(((GoVarDefinition)resolved).getValue()); } else if (resolved instanceof GoConstDefinition) { return getValue(((GoConstDefinition)resolved).getValue()); } return null; }
Source:
<code>private void setPackageFilePath() throws IOException, MojoFailureException { validateIncludeAndPackageType(); String projectBuildDir = getPackageDirectory(); String projectBuildName = getPackageName(); <START> packageFile = new File(projectBuildDir, projectBuildName + packageFileType.getFileExtension()); <END> }</code><technical_language>this, if need distinguish fileExtension in enum. do packageFile = new File(projectBuildDir, projectBuildName + "." + packageFileType.getValue());</technical_language>

Target:
private void setPackageFilePath() throws IOException, MojoFailureException { setPackageFileType(); String projectBuildDir = getPackageDirectory(); String projectBuildName = getPackageName(); packageFile = new File(projectBuildDir, projectBuildName + "." + packageFileType.getValue()); }
Source:
<code>public void fullExample() { StringBuilder text = new StringBuilder(); text.append("Header 1\n"); text.append("-------\n"); text.append("\n"); text.append("Lorem ipsum *dolor* sit amet, \n"); text.append("\n"); text.append("=== Header 2\n"); text.append("\n"); text.append("consetetur _adipisici_ elit.\n"); String html = parseToHtml(text.toString()); <START> assertTrue(html.contains("Header 1</h2>")); <END> assertTrue(html.contains("<p>Lorem ipsum")); assertTrue(html.contains("<strong>dolor")); assertTrue(html.contains("Header 2</h3>")); assertTrue(html.contains("<em>adipisici</em>")); }</code><technical_language>previous discussion, assertEquals contains <LINK_0></technical_language>

Target:
public void fullExample() { StringBuilder text = new StringBuilder(); text.append("Header 2\n"); text.append("-------\n"); text.append("\n"); text.append("Lorem ipsum *dolor* sit amet, \n"); text.append("\n"); text.append("=== Header 3\n"); text.append("\n"); text.append("consetetur _adipisici_ elit.\n"); String html = parseToHtml(text.toString()); assertEquals( "<h2>Header 2</h2><p>Lorem ipsum <strong>dolor</strong> sit amet, </p>\n" + "<h3>Header 3</h3><p>consetetur <em>adipisici</em> elit.</p>\n" , html); }
Source:
<code>public static @Nullable Map<Integer, TraceCompassFilter> getFilterForTrace(ITmfTrace trace) { <START> Map<Integer, TraceCompassFilter> map = FILTERS_MAP.get(trace); if (map == null) { return Collections.emptyMap(); } return map; <END> }</code><technical_language>coulb line return FILTERS_MAP.getOrDefault(trace, Collections.emptyMap());</technical_language>

Target:
public static @Nullable Map<Integer, TraceCompassFilter> getFilterForTrace(ITmfTrace trace) { return FILTERS_MAP.getOrDefault(trace, Collections.emptyMap()); }
Source:
<code>public void visitToken(DetailAST ast) { defined = true; if (!ignoreMismatch) { final String fileName = getFileContents().getFileName(); <START> final int lastPos = fileName.lastIndexOf(File.separatorChar); <END> final String directoryName = fileName.substring(0, lastPos); final DetailAST nameAST = ast.getLastChild().getPreviousSibling(); final FullIdent full = FullIdent.createFullIdent(nameAST); final String expected = full.getText().replace('.', File.separatorChar); if (!directoryName.endsWith(expected)) { log(full.getLineNo(), MSG_KEY_MISMATCH, expected); } } }</code><technical_language>lastPos mean? position of what? Try more specific in names</technical_language>

Target:
public void visitToken(DetailAST ast) { defined = true; if (matchDirectoryStructure) { final DetailAST packageNameAst = ast.getLastChild().getPreviousSibling(); final FullIdent fullIdent = FullIdent.createFullIdent(packageNameAst); final String packageName = fullIdent.getText().replace('.', File.separatorChar); final String directoryName = getDirectoryName(); if (!directoryName.endsWith(packageName)) { log(fullIdent.getLineNo(), MSG_KEY_MISMATCH, packageName); } } }
Source:
<code>private static String getCredential(String username, String password) { if (username == null || password == null) { return null; } else { <START> return okhttp3.Credentials.basic(buildDomainUser(username), buildAppPassword(password)); <END> } }</code><technical_language>Hey, intentional a version of this function *didn't* try append domain credentials. If audited clear domain-less version, fine remove it, change name of this function clear double duty (IE: Creating basic auth credential string *AND* mutating username attach domain data). I in context used, necessarily unambiguous username pass in out, worried a source of future errors</technical_language>

Target:
private static String getCredential(String username, String password) { if (username == null || password == null) { return null; } else { return Credentials.basic(username, buildAppPassword(password)); } }
Source:
<code>private void doInit(ExtMap inputMap, ExtMap outputMap) { context = inputMap.<ExtMap> get(Base.InvokeKeys.CONTEXT); configuration = context.<Properties> get(Base.ContextKeys.CONFIGURATION); <START> Config.setConfiguration((Properties) configuration.get("config")); <END> broker = LdapFactory.getInstance(getAuthzName()); context.<List<String>> get( Base.ContextKeys.CONFIGURATION_SENSITIVE_KEYS ).add("config.authn.user.password"); context.mput( Base.ContextKeys.AUTHOR, "The oVirt Project").mput( Base.ContextKeys.EXTENSION_NAME, "Kerberos/Ldap Authn (Built-in)" ).mput( Base.ContextKeys.LICENSE, "ASL 2.0" ).mput( Base.ContextKeys.HOME_URL, "<LINK_0>" ).mput( Base.ContextKeys.VERSION, "N/A" ).mput( Authn.ContextKeys.CAPABILITIES, Authn.Capabilities.AUTHENTICATE_PASSWORD ).mput( Base.ContextKeys.BUILD_INTERFACE_VERSION, Base.INTERFACE_VERSION_CURRENT); KerberosManager.getInstance(); UsersDomainsCacheManagerService.getInstance().init(); }</code><technical_language>please defaults for all, work variables specified</technical_language>

Target:
private void doInit(ExtMap inputMap, ExtMap outputMap) { context = inputMap.<ExtMap> get(Base.InvokeKeys.CONTEXT); configuration = context.<Properties> get(Base.ContextKeys.CONFIGURATION); broker = LdapFactory.getInstance(getAuthzName()); context.<List<String>> get( Base.ContextKeys.CONFIGURATION_SENSITIVE_KEYS ).add("config.authn.user.password"); context.mput( Base.ContextKeys.AUTHOR, "The oVirt Project").mput( Base.ContextKeys.EXTENSION_NAME, "Kerberos/Ldap Authn (Built-in)" ).mput( Base.ContextKeys.LICENSE, "ASL 2.0" ).mput( Base.ContextKeys.HOME_URL, "<LINK_0>" ).mput( Base.ContextKeys.VERSION, "N/A" ).mput( Authn.ContextKeys.CAPABILITIES, Authn.Capabilities.AUTHENTICATE_PASSWORD ).mput( Base.ContextKeys.BUILD_INTERFACE_VERSION, Base.INTERFACE_VERSION_CURRENT); KerberosManager.getInstance(configuration); UsersDomainsCacheManagerService.getInstance().init(configuration); }
Source:
<code>public void questionableMatchFails() { <START> TimeLimitedMatcher.create(Pattern.compile("(a+)+"), StringUtils.repeat("a", 1000) + "!"); <END> }</code><technical_language>long this match system</technical_language>

Target:
public void questionableMatchFails() throws Exception { TimeLimitedMatcher.create(Pattern.compile("(a+)+"), StringUtils.repeat("a", 1000) + "!"); }
Source:
<code>protected Set<E> parseData(Parser<E> parser, URL url, Bundle bundle) { InputStreamReader reader = null; InputStream is = null; try { is = url.openStream(); <START> reader = new InputStreamReader(is, "UTF-8"); <END> return parser.parse(reader); } catch (ParsingException e) { logger.error(e.getLocalizedMessage(), e); } catch (IOException e) { logger.error("Can't read from resource of bundle with ID {}", bundle.getBundleId(), e); processAutomationProviderUninstalled(bundle); } finally { if (reader != null) { try { reader.close(); } catch (IOException ignore) { } } if (is != null) { try { is.close(); } catch (IOException ignore) { } } } return null; }</code><technical_language>Java reader = new InputStreamReader(is, StandardCharsets.UTF_8);</technical_language>

Target:
protected Set<E> parseData(Parser<E> parser, URL url, Bundle bundle) { InputStreamReader reader = null; InputStream is = null; try { is = url.openStream(); reader = new InputStreamReader(is, StandardCharsets.UTF_8); return parser.parse(reader); } catch (ParsingException e) { logger.error(e.getLocalizedMessage(), e); } catch (IOException e) { logger.error("Can't read from resource of bundle with ID {}", bundle.getBundleId(), e); processAutomationProviderUninstalled(bundle); } finally { if (reader != null) { try { reader.close(); } catch (IOException ignore) { } } if (is != null) { try { is.close(); } catch (IOException ignore) { } } } return null; }
Source:
<code>private int index(Iterator<Item> iterator) throws DSpaceSolrIndexerException { try { int i = 0; int batchSize = configurationService.getIntProperty("oai.import.batch.size", 1000); SolrServer server = solrServerResolver.getServer(); ArrayList<SolrInputDocument> list = new ArrayList<>(); while (iterator.hasNext()) { try { Item item = iterator.next(); if (item.getHandle() == null) { log.warn("Skipped item without handle: " + item.getID()); } else { list.add(this.index(item)); } context.uncacheEntity(item); } catch (SQLException | MetadataBindException | ParseException | XMLStreamException | WritingXmlException ex) { log.error(ex.getMessage(), ex); } i++; <START> if (i % 1000 == 0) { <END> System.out.println(i + " items imported so far..."); } if (i % batchSize == 0) { System.out.println(i + " items imported so far..."); server.add(list); server.commit(); list.clear(); } } System.out.println("Total: " + i + " items"); server.add(list); server.commit(true, true); list.clear(); return i; } catch (SolrServerException | IOException ex) { throw new DSpaceSolrIndexerException(ex.getMessage(), ex); } }</code><technical_language>Note get message oai.import.batch.size is defaulted. Cosmetic. do need this</technical_language>

Target:
private int index(Iterator<Item> iterator) throws DSpaceSolrIndexerException { try { int i = 0; int batchSize = configurationService.getIntProperty("oai.import.batch.size", 1000); SolrServer server = solrServerResolver.getServer(); ArrayList<SolrInputDocument> list = new ArrayList<>(); while (iterator.hasNext()) { try { Item item = iterator.next(); if (item.getHandle() == null) { log.warn("Skipped item without handle: " + item.getID()); } else { list.add(this.index(item)); } context.uncacheEntity(item); } catch (SQLException | MetadataBindException | ParseException | XMLStreamException | WritingXmlException ex) { log.error(ex.getMessage(), ex); } i++; if (i % 1000 == 0 && batchSize != 1000) { System.out.println(i + " items imported so far..."); } if (i % batchSize == 0) { System.out.println(i + " items imported so far..."); server.add(list); server.commit(); list.clear(); } } System.out.println("Total: " + i + " items"); server.add(list); server.commit(true, true); list.clear(); return i; } catch (SolrServerException | IOException ex) { throw new DSpaceSolrIndexerException(ex.getMessage(), ex); } }
Source:
<code>private static boolean isTable(TagNode node) { <START> return "TABLE".equalsIgnoreCase(node.getLocalName()); <END> }</code><technical_language>I node.getNodeName() instead, rule apply table tags coming XML Tag library. Ex: <myLib:table role="none"> </myLib:table></technical_language>

Target:
private static boolean isTable(TagNode node) { return "TABLE".equalsIgnoreCase(node.getNodeName()); }
Source:
<code>public static Slice stCentroid(@SqlType(GEOMETRY_TYPE_NAME) Slice input) { OGCGeometry geometry = deserialize(input); validateType("ST_Centroid", geometry, EnumSet.of(POINT, MULTI_POINT, LINE_STRING, MULTI_LINE_STRING, POLYGON, MULTI_POLYGON)); <START> GeometrySerializationType geometryType = GeometrySerializationType.getForEsriGeometryType(geometry.geometryType()); <END> if (geometryType == POINT) { return input; } int pointCount = ((MultiVertexGeometry) geometry.getEsriGeometry()).getPointCount(); if (pointCount == 0) { return serialize(createFromEsriGeometry(new Point(), geometry.getEsriSpatialReference())); } Point centroid; switch (geometryType) { case MULTI_POINT: centroid = computePointsCentroid((MultiVertexGeometry) geometry.getEsriGeometry()); break; case LINE_STRING: case MULTI_LINE_STRING: centroid = computeLineCentroid((Polyline) geometry.getEsriGeometry()); break; case POLYGON: centroid = computePolygonCentroid((Polygon) geometry.getEsriGeometry()); break; case MULTI_POLYGON: centroid = computeMultiPolygonCentroid((OGCMultiPolygon) geometry); break; default: throw new PrestoException(INVALID_FUNCTION_ARGUMENT, "Unexpected geometry type: " + geometryType); } return serialize(createFromEsriGeometry(centroid, geometry.getEsriSpatialReference())); }</code><technical_language>GeometryType</technical_language>

Target:
public static Slice stCentroid(@SqlType(GEOMETRY_TYPE_NAME) Slice input) { OGCGeometry geometry = deserialize(input); validateType("ST_Centroid", geometry, EnumSet.of(POINT, MULTI_POINT, LINE_STRING, MULTI_LINE_STRING, POLYGON, MULTI_POLYGON)); GeometryType geometryType = GeometryType.getForEsriGeometryType(geometry.geometryType()); if (geometryType == GeometryType.POINT) { return input; } int pointCount = ((MultiVertexGeometry) geometry.getEsriGeometry()).getPointCount(); if (pointCount == 0) { return serialize(createFromEsriGeometry(new Point(), geometry.getEsriSpatialReference())); } Point centroid; switch (geometryType) { case MULTI_POINT: centroid = computePointsCentroid((MultiVertexGeometry) geometry.getEsriGeometry()); break; case LINE_STRING: case MULTI_LINE_STRING: centroid = computeLineCentroid((Polyline) geometry.getEsriGeometry()); break; case POLYGON: centroid = computePolygonCentroid((Polygon) geometry.getEsriGeometry()); break; case MULTI_POLYGON: centroid = computeMultiPolygonCentroid((OGCMultiPolygon) geometry); break; default: throw new PrestoException(INVALID_FUNCTION_ARGUMENT, "Unexpected geometry type: " + geometryType); } return serialize(createFromEsriGeometry(centroid, geometry.getEsriSpatialReference())); }
Source:
<code>private void plugDiskToVmIfNeeded() { if (Boolean.TRUE.equals(getParameters().getPlugDiskToVm()) && getVm() != null && getVm().getStatus() != VMStatus.Down) { <START> HotPlugDiskToVmParameters params = new HotPlugDiskToVmParameters(getVmId(), getParameters().getDiskInfo().getId()); <END> VdcReturnValueBase returnValue = Backend.getInstance().runInternalAction(VdcActionType.HotPlugDiskToVm, params); if (!returnValue.getSucceeded()) { AuditLogDirector.log(this, AuditLogType.USER_FAILED_HOTPLUG_DISK); } } }</code><technical_language>i wrote in previous patchset, please avoid memory lock in hotplug command. unneeded</technical_language>

Target:
private void plugDiskToVmIfNeeded() { if (Boolean.TRUE.equals(getParameters().getPlugDiskToVm()) && getVm() != null && getVm().getStatus() != VMStatus.Down) { HotPlugDiskToVmParameters params = new HotPlugDiskToVmParameters(getVmId(), getParameters().getDiskInfo().getId()); params.setShouldBeLogged(false); VdcReturnValueBase returnValue = Backend.getInstance().runInternalAction(VdcActionType.HotPlugDiskToVm, params); if (!returnValue.getSucceeded()) { AuditLogDirector.log(this, AuditLogType.USER_FAILED_HOTPLUG_DISK); } } }
Source:
<code>public boolean equals(Object obj) { <START> return (this == obj) || (obj instanceof ErrorMessage) && equalTo((ErrorMessage) obj); <END> }</code><technical_language>feedback other classes. check equals(), equalTo() methods in changeset</technical_language>

Target:
public boolean equals(Object obj) { return (this == obj) || (obj instanceof NotifiedMessage) && equalTo((NotifiedMessage) obj); }
Source:
<code>public Builder(HttpResponse response) { this(response.getStatusCode(), response.getStatusMessage(), response.getHeaders()); try { content = response.parseAsString(); if (content.length() == 0) { content = null; } <START> } catch (IOException exception) { <END> exception.printStackTrace(); } catch (IllegalCharsetNameException exception) { exception.printStackTrace(); } StringBuilder builder = computeMessageBuffer(response); if (content != null) { builder.append(StringUtils.LINE_SEPARATOR).append(content); } message = builder.toString(); }</code><technical_language>some extra whitespace added</technical_language>

Target:
public Builder(HttpResponse response) { this(response.getStatusCode(), response.getStatusMessage(), response.getHeaders()); try { content = response.parseAsString(); if (content.length() == 0) { content = null; } } catch (IOException exception) { exception.printStackTrace(); } catch (IllegalArgumentException exception) { exception.printStackTrace(); } StringBuilder builder = computeMessageBuffer(response); if (content != null) { builder.append(StringUtils.LINE_SEPARATOR).append(content); } message = builder.toString(); }
Source:
<code>public NotAnOutputTypeError(TypeDefinition typeDefinition) { <START> super(typeDefinition, format("The %s type is used as an OutputType, but is not declared as one", typeDefinition.getName())); <END> }</code><technical_language>phrase a bit diffrent: "expected OutputType, %s type"</technical_language>

Target:
public NotAnOutputTypeError(TypeDefinition typeDefinition) { super(typeDefinition, format("expected OutputType, but found %s type", typeDefinition.getName())); }
Source:
<code>public void eventRaised(Event<? extends EventArgs> ev, Object sender, EventArgs args) { super.eventRaised(ev, sender, args); if (ev.matchesDefinition(RegistrationResult.RetrievedEventDefinition)) { asyncResult_Retrieved(); } if (ev.matchesDefinition(ProvideTickEvent.definition)) { syncSearch(); } <START> entityModel.eventRaised(ev, sender, args); <END> }</code><technical_language>a more defensive put this call 'super()' call want treat EntityModel ancestor (as before)</technical_language>

Target:
public void eventRaised(Event<? extends EventArgs> ev, Object sender, EventArgs args) { super.eventRaised(ev, sender, args); entityModel.eventRaised(ev, sender, args); if (ev.matchesDefinition(RegistrationResult.RetrievedEventDefinition)) { asyncResult_Retrieved(); } if (ev.matchesDefinition(ProvideTickEvent.definition)) { syncSearch(); } }
Source:
<code>public ModelAndView newServiceRecord(@PathVariable(value = "sequencerReferenceId") Long sequencerReferenceId, ModelMap model) throws IOException { SequencerReference sequencer = requestManager.getSequencerReferenceById(sequencerReferenceId); if (sequencer == null) { throw new IOException("Cannot retrieve the requested Sequencer Reference"); } SequencerServiceRecord record = dataObjectFactory.getSequencerServiceRecord(); record.setSequencerReference(sequencer); <START> model.put("serviceRecord", record); <END> return new ModelAndView("/pages/editServiceRecord.jsp", model); }</code><technical_language>good if constants in enum</technical_language>

Target:
public ModelAndView newServiceRecord(@PathVariable(value = "sequencerReferenceId") Long sequencerReferenceId, ModelMap model) throws IOException { SequencerReference sequencer = requestManager.getSequencerReferenceById(sequencerReferenceId); if (sequencer == null) { throw new IOException("No such Sequencer Reference"); } SequencerServiceRecord record = dataObjectFactory.getSequencerServiceRecord(); record.setSequencerReference(sequencer); model.put(ModelKeys.RECORD.getKey(), record); return new ModelAndView("/pages/editServiceRecord.jsp", model); }
Source:
<code>public static ProcessInstanceCustomVarsList convertToProcessInstanceCustomVarsList(Collection<ProcessInstanceCustomDesc> instances) { if (instances == null) { return new ProcessInstanceCustomVarsList(new org.kie.server.api.model.instance.ProcessInstanceCustomVars[0]); } List<ProcessInstanceCustomVars> processInstances = new ArrayList<ProcessInstanceCustomVars>(instances.size()); for (ProcessInstanceCustomDesc pi : instances) { org.kie.server.api.model.instance.ProcessInstanceCustomVars instance = convertToProcessInstanceCustomVars(pi); <START> instance.setVariables(pi.getVariables()); <END> processInstances.add(instance); } return new ProcessInstanceCustomVarsList(processInstances); }</code><technical_language>builder's variables() method in convertToProcessInstanceCustomVars(pi)</technical_language>

Target:
public static ProcessInstanceCustomVarsList convertToProcessInstanceCustomVarsList(Collection<ProcessInstanceCustomDesc> instances) { if (instances == null) { return new ProcessInstanceCustomVarsList(new org.kie.server.api.model.instance.ProcessInstanceCustomVars[0]); } List<ProcessInstanceCustomVars> processInstances = new ArrayList<ProcessInstanceCustomVars>(instances.size()); for (ProcessInstanceCustomDesc pi : instances) { org.kie.server.api.model.instance.ProcessInstanceCustomVars instance = convertToProcessInstanceCustomVars(pi); processInstances.add(instance); } return new ProcessInstanceCustomVarsList(processInstances); }
Source:
<code>public MetadataSchema[] getSchemas(@QueryParam("expand") @DefaultValue("fields") String expand, @QueryParam("userIP") String user_ip, @QueryParam("userAgent") String user_agent, @QueryParam("xforwarderfor") String xforwarderfor, @Context HttpHeaders headers, @Context HttpServletRequest request) throws WebApplicationException { log.info("Reading all metadata schemas."); org.dspace.core.Context context = null; ArrayList<MetadataSchema> metadataSchemas = null; try { context = createContext(getUser(headers)); List<org.dspace.content.MetadataSchema> schemas = metadataSchemaService.findAll(context); metadataSchemas = new ArrayList<MetadataSchema>(); for(org.dspace.content.MetadataSchema schema: schemas) { metadataSchemas.add(new MetadataSchema(schema, expand, context)); } context.complete(); } catch (SQLException e) { processException("Could not read metadata schemas, SQLException. Message:" + e, context); <START> log.error(e.getMessage()); <END> throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR); } catch (ContextException e) { processException("Could not read metadata schemas, ContextException. Message:" + e.getMessage(), context); } finally { processFinally(context); } log.trace("All metadata schemas successfully read."); return metadataSchemas.toArray(new MetadataSchema[0]); }</code><technical_language>log stacktrace, is useful in a lot of cases</technical_language>

Target:
public MetadataSchema[] getSchemas(@QueryParam("expand") @DefaultValue("fields") String expand, @QueryParam("userIP") String user_ip, @QueryParam("userAgent") String user_agent, @QueryParam("xforwarderfor") String xforwarderfor, @Context HttpHeaders headers, @Context HttpServletRequest request) throws WebApplicationException { log.info("Reading all metadata schemas."); org.dspace.core.Context context = null; ArrayList<MetadataSchema> metadataSchemas = null; try { context = createContext(getUser(headers)); List<org.dspace.content.MetadataSchema> schemas = metadataSchemaService.findAll(context); metadataSchemas = new ArrayList<MetadataSchema>(); for(org.dspace.content.MetadataSchema schema: schemas) { metadataSchemas.add(new MetadataSchema(schema, expand, context)); } context.complete(); } catch (SQLException e) { processException("Could not read metadata schemas, SQLException. Message:" + e, context); } catch (ContextException e) { processException("Could not read metadata schemas, ContextException. Message:" + e.getMessage(), context); } finally { processFinally(context); } log.trace("All metadata schemas successfully read."); return metadataSchemas.toArray(new MetadataSchema[0]); }
Source:
<code>private void handleNoInternet() { if (null != getView()) { if (null != progressBar) { progressBar.setVisibility(GONE); } ViewUtil.showShortSnackbar(imagesRecyclerView, R.string.no_internet); } else { <START> Timber.d(TAG + ": attempt to update fragment ui after its view was destroyed"); <END> } }</code><technical_language>Timber automatically adds TAG. need append explicitly</technical_language>

Target:
private void handleNoInternet() { if (null != getView()) { if (null != progressBar) { progressBar.setVisibility(GONE); } ViewUtil.showShortSnackbar(imagesRecyclerView, R.string.no_internet); } else { Timber.d("Attempt to update fragment ui after its view was destroyed"); } }
Source:
<code>public static void main(String[] args) { System.loadLibrary(args[0]); System.out.println("Startup completed: " + hasStartupCompleted()); Thread workerThread = new WorkerThread(); workerThread.start(); do { resetStartupCompleted(); <START> VMRuntime.getRuntime().notifyStartupCompleted(); <END> } while (!completed.get()); try { workerThread.join(); } catch (Throwable e) { System.err.println(e); } System.out.println("Startup completed: " + hasStartupCompleted()); }</code><technical_language>Add a yield</technical_language>

Target:
public static void main(String[] args) { System.loadLibrary(args[0]); System.out.println("Startup completed: " + hasStartupCompleted()); Thread workerThread = new WorkerThread(); workerThread.start(); do { resetStartupCompleted(); VMRuntime.getRuntime().notifyStartupCompleted(); Thread.yield(); } while (!completed.get()); try { workerThread.join(); } catch (Throwable e) { System.err.println(e); } System.out.println("Startup completed: " + hasStartupCompleted()); }
Source:
<code>protected void updateModelDataCenterFromVds(ArrayList<StoragePool> dataCenters, VDS vds) { <START> if (dataCenters != null && vds.getStoragePoolId() != null) <END> { getDataCenter().setItems(dataCenters); getDataCenter().setSelectedItem(Linq.firstOrDefault(dataCenters, new Linq.DataCenterPredicate(vds.getStoragePoolId()))); if (getDataCenter().getSelectedItem() == null) { getDataCenter().setSelectedItem(Linq.firstOrDefault(dataCenters)); } } }</code><technical_language>do need check- vds.getStoragePoolId() != null</technical_language>

Target:
protected void updateModelDataCenterFromVds(ArrayList<StoragePool> dataCenters, VDS vds) { if (dataCenters != null) { getDataCenter().setItems(dataCenters); getDataCenter().setSelectedItem(Linq.firstOrDefault(dataCenters, new Linq.DataCenterPredicate(vds.getStoragePoolId()))); if (getDataCenter().getSelectedItem() == null) { getDataCenter().setSelectedItem(Linq.firstOrDefault(dataCenters)); } } }