auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void validateInput() throws RequiredFieldException { documentName = et_document_name.getEditableText().toString(); if (documentName.length() == 0 || documentName.equals("")) throw new RequiredFieldException(getResources().getString(R.string.name), getString(R.string.message_field_required)); documentDescription = et_document_description.getEditableText().toString(); if (documentDescription.length() == 0 || documentDescription.equals("")) throw new RequiredFieldException(getResources().getString(R.string.description), getString(R.string.message_field_required)); <START> if (documentAction == getResources().getString(R.string.update_document)) { <END> updatedDocument = document; updatedDocument.setName(documentName); updatedDocument.setDescription(documentDescription); updatedDocument.setFileName(fileChoosen.getName()); updatedDocument.setSize(fileChoosen.length()); mDocumentDialogPresenter.updateDocument(entityType, entityId, document.getId(), documentName, documentDescription, fileChoosen); } else if (documentAction == getResources().getString(R.string.upload_document)) { createdDocument = new Document(); createdDocument.setName(documentName); createdDocument.setDescription(documentDescription); createdDocument.setFileName(fileChoosen.getName()); createdDocument.setParentEntityType(entityType); createdDocument.setParentEntityId(entityId); createdDocument.setSize(fileChoosen.length()); mDocumentDialogPresenter.createDocument(entityType, entityId, documentName, documentDescription, fileChoosen); } }</code><technical_language>@therajanmaurya I ? comparing String == equals() Please fix this ASAP</technical_language>

Target:
public void validateInput() throws RequiredFieldException { documentName = et_document_name.getEditableText().toString(); if (documentName.length() == 0 || documentName.equals("")) throw new RequiredFieldException(getResources().getString(R.string.name), getString(R.string.message_field_required)); documentDescription = et_document_description.getEditableText().toString(); if (documentDescription.length() == 0 || documentDescription.equals("")) throw new RequiredFieldException(getResources().getString(R.string.description), getString(R.string.message_field_required)); if (documentAction.equals(getResources().getString(R.string.update_document))) { updatedDocument = document; addBasicInfo(updatedDocument, documentName, documentDescription, fileChoosen.getName(), fileChoosen.length()); mDocumentDialogPresenter.updateDocument(entityType, entityId, document.getId(), documentName, documentDescription, fileChoosen); } else if (documentAction.equals(getResources().getString(R.string.upload_document))) { createdDocument = new Document(); addBasicInfo(createdDocument, documentName, documentDescription, fileChoosen.getName(), fileChoosen.length()); createdDocument.setParentEntityType(entityType); createdDocument.setParentEntityId(entityId); mDocumentDialogPresenter.createDocument(entityType, entityId, documentName, documentDescription, fileChoosen); } }
Source:
<code>private String[] cgitUntracked() throws Exception { FS fs = db.getFS(); ProcessBuilder builder = fs.runInShell("git", new String[] { "ls-files", <START> "--others", "--exclude-standard", "-o" }); <END> builder.directory(db.getWorkTree()); builder.environment().put("HOME", fs.userHome().getAbsolutePath()); ExecutionResult result = fs.execute(builder, new ByteArrayInputStream(new byte[0])); String errorOut = toString(result.getStderr()); assertEquals("External git failed", "exit 0\n", "exit " + result.getRc() + '\n' + errorOut); try (BufferedReader r = new BufferedReader(new InputStreamReader( new BufferedInputStream(result.getStdout().openInputStream()), Constants.CHARSET))) { return r.lines().toArray(String[]::new); } }</code><technical_language>-others -o, synonyms for option</technical_language>

Target:
private String[] cgitUntracked() throws Exception { FS fs = db.getFS(); ProcessBuilder builder = fs.runInShell("git", new String[] { "ls-files", "--exclude-standard", "-o" }); builder.directory(db.getWorkTree()); builder.environment().put("HOME", fs.userHome().getAbsolutePath()); ExecutionResult result = fs.execute(builder, new ByteArrayInputStream(new byte[0])); String errorOut = toString(result.getStderr()); assertEquals("External git failed", "exit 0\n", "exit " + result.getRc() + '\n' + errorOut); try (BufferedReader r = new BufferedReader(new InputStreamReader( new BufferedInputStream(result.getStdout().openInputStream()), Constants.CHARSET))) { return r.lines().toArray(String[]::new); } }
Source:
<code>private void verifyRedirectToWelcomeStrangerPage(AppUrl url, String unregUsername) { printUrl(url.toAbsoluteString()); currentPage.navigateTo(url); AssertHelper.assertContainsRegex("{*}" + unregUsername <START> + "{*}Ooops! Your Google account is not known to TEAMMATES{*}", <END> currentPage.getPageSource()); }</code><technical_language>For this changes happening in StudentHomePageActionTest.java, this kind of line break better: java AssertHelper.assertContainsRegex( "{*}" + unregUsername + "{*}Ooops! Google account is TEAMMATES{*}", currentPage.getPageSource());</technical_language>

Target:
private void verifyRedirectToWelcomeStrangerPage(AppUrl url, String unregUsername) { printUrl(url.toAbsoluteString()); currentPage.navigateTo(url); AssertHelper.assertContainsRegex( unregUsername + "{*}Ooops! Your Google account is not known to TEAMMATES", currentPage.getPageSource()); }
Source:
<code>protected void setUsernameInDrawer(RelativeLayout navigationDrawerLayout, Account account) { <START> if (navigationDrawerLayout != null && getAccount() != null) { <END> TextView username = (TextView) navigationDrawerLayout.findViewById(R.id.drawer_username); int lastAtPos = account.name.lastIndexOf("@"); username.setText(account.name.substring(0, lastAtPos)); } }</code><technical_language>right</technical_language>

Target:
protected void setUsernameInDrawer(RelativeLayout navigationDrawerLayout, Account account) { if (navigationDrawerLayout != null && account != null) { TextView username = (TextView) navigationDrawerLayout.findViewById(R.id.drawer_username); int lastAtPos = account.name.lastIndexOf("@"); username.setText(account.name.substring(0, lastAtPos)); } }
Source:
<code>public Object getParent(Object element) { <START> if (element instanceof FileDiffRegion || element instanceof Folder) { <END> return parents.get(element); } return null; }</code><technical_language>Is this needed? add other elements, parent.get(anythingElse) return null anyway</technical_language>

Target:
public Object getParent(Object element) { return parents.get(element); }
Source:
<code>private boolean validateMetaConstraint(ValidationContext<?> validationContext, ValueContext<?, Object> valueContext, Object parent, MetaConstraint<?> metaConstraint) { ValueContext.ValueState<Object> originalValueState = valueContext.getCurrentValueState(); valueContext.appendNode( metaConstraint.getLocation() ); boolean success = true; if ( isValidationRequired( validationContext, valueContext, metaConstraint ) ) { Object valueToValidate = null; if ( parent != null ) { valueToValidate = valueContext.getValue( parent, metaConstraint.getLocation() ); valueContext.setCurrentValidatedValue( valueToValidate ); } success = metaConstraint.validateConstraint( validationContext, valueContext ); <START> <END> validationContext.markConstraintProcessed( valueContext.getCurrentBean(), valueContext.getPropertyPath(), metaConstraint ); } valueContext.resetValueState( originalValueState ); return success; }</code><technical_language>get rid of variable altogether</technical_language>

Target:
private boolean validateMetaConstraint(ValidationContext<?> validationContext, ValueContext<?, Object> valueContext, Object parent, MetaConstraint<?> metaConstraint) { ValueContext.ValueState<Object> originalValueState = valueContext.getCurrentValueState(); valueContext.appendNode( metaConstraint.getLocation() ); boolean success = true; if ( isValidationRequired( validationContext, valueContext, metaConstraint ) ) { if ( parent != null ) { valueContext.setCurrentValidatedValue( valueContext.getValue( parent, metaConstraint.getLocation() ) ); } success = metaConstraint.validateConstraint( validationContext, valueContext ); validationContext.markConstraintProcessed( valueContext.getCurrentBean(), valueContext.getPropertyPath(), metaConstraint ); } valueContext.resetValueState( originalValueState ); return success; }
Source:
<code>protected void runInternal() { try { <START> wbqCapacityCounter().incrementBackup(transactionId, getPartitionId()); <END> } catch (ReachedMaxSizeException e) { throw new TransactionException(e); } if (!recordStore.txnLock(getKey(), lockOwner, threadId, getCallId(), LOCK_TTL_MILLIS, true)) { wbqCapacityCounter().decrement(transactionId, getPartitionId()); throw new TransactionException("Lock is not owned by the transaction! Caller: " + lockOwner + ", Owner: " + recordStore.getLockOwnerInfo(getKey())); } }</code><technical_language>incrementBackup method throw this exception I guess remove catch clause. WDYT</technical_language>

Target:
protected void runInternal() { wbqCapacityCounter().increment(transactionId, true); if (!recordStore.txnLock(getKey(), lockOwnerUuid, threadId, getCallId(), LOCK_TTL_MILLIS, true)) { wbqCapacityCounter().decrement(transactionId); throw new TransactionException("Lock is not owned by the transaction! Caller: " + lockOwnerUuid + ", Owner: " + recordStore.getLockOwnerInfo(getKey())); } }
Source:
<code>private static void saveResults(String filename, Map<Integer, CorefChain> chains) throws IOException { FileWriter fout = new FileWriter(filename); BufferedWriter bout = new BufferedWriter(fout); <START> Map<Integer, CorefChain> sorted = new TreeMap<>(chains); <END> for (Map.Entry<Integer, CorefChain> entry : sorted.entrySet()) { saveKey(bout, entry.getKey(), entry.getValue()); } bout.flush(); bout.close(); fout.close(); }</code><technical_language>I expect this optimized Collections.sort. unnecessary change</technical_language>

Target:
private static void saveResults(String filename, Map<Integer, CorefChain> chains) throws IOException { FileWriter fout = new FileWriter(filename); BufferedWriter bout = new BufferedWriter(fout); List<Integer> keys = new ArrayList<>(chains.keySet()); Collections.sort(keys); for (Integer key : keys) { saveKey(bout, key, chains.get(key)); } bout.flush(); bout.close(); fout.close(); }
Source:
<code>void poll(RequestRegistrationCallback<GetOperation> requestRegistrationCallback) { Iterator<Map.Entry<Integer, GetRequestInfo>> inFlightRequestsIterator = correlationIdToGetRequestInfo.entrySet().iterator(); while (inFlightRequestsIterator.hasNext()) { Map.Entry<Integer, GetRequestInfo> entry = inFlightRequestsIterator.next(); if (time.milliseconds() - entry.getValue().startTimeMs > routerConfig.routerRequestTimeoutMs) { operationTracker.onResponse(entry.getValue().replicaId, false); setOperationException( new RouterException("Timed out waiting for responses", RouterErrorCode.OperationTimedOut)); inFlightRequestsIterator.remove(); } else { break; } } checkAndMaybeComplete(); if (isOperationComplete()) { <START> return; <END> } Iterator<ReplicaId> replicaIterator = operationTracker.getReplicaIterator(); while (replicaIterator.hasNext()) { ReplicaId replicaId = replicaIterator.next(); String hostname = replicaId.getDataNodeId().getHostname(); Port port = new Port(replicaId.getDataNodeId().getPort(), PortType.PLAINTEXT); GetRequest getRequest = createGetRequest(blobId, getOperationFlag()); RequestInfo request = new RequestInfo(hostname, port, getRequest); int correlationId = getRequest.getCorrelationId(); correlationIdToGetRequestInfo.put(correlationId, new GetRequestInfo(replicaId, time.milliseconds())); requestRegistrationCallback.registerRequestToSend(this, request); replicaIterator.remove(); } }</code><technical_language>returns in middle of a function :) This is personal preference of - I do if(!operationComplete()) instead</technical_language>

Target:
void poll(RequestRegistrationCallback<GetOperation> requestRegistrationCallback) { cleanupExpiredInFlightRequests(); checkAndMaybeComplete(); if (!isOperationComplete()) { fetchRequests(requestRegistrationCallback); } }
Source:
<code><START> public static Map<String, Object> deserializeStateMap(final Map<String, Object> serializedStateMap) { <END> final Map<String, Object> result = new HashMap<>(); for (final Map.Entry<String, Object> mapEntry : serializedStateMap.entrySet()) { final Object state = mapEntry.getValue(); if (state instanceof ByteBuffer) { final Object deserializedState = deserializeState((ByteBuffer)state); if (deserializedState == null) { throw new RuntimeException("Error while deserializing the operator state."); } else { result.put(mapEntry.getKey(), deserializedState); } } else { result.put(mapEntry.getKey(), state); } } return result; }</code><technical_language>throw RuntimeException</technical_language>

Target:
public static Map<String, Object> deserializeStateMap(final Map<String, Object> serializedStateMap) throws RuntimeException { final Map<String, Object> result = new HashMap<>(); for (final Map.Entry<String, Object> mapEntry : serializedStateMap.entrySet()) { final Object state = mapEntry.getValue(); if (state instanceof ByteBuffer) { try { final Object deserializedState = deserializeState((ByteBuffer)state); result.put(mapEntry.getKey(), deserializedState); } catch (final RuntimeException e) { throw e; } } else { result.put(mapEntry.getKey(), state); } } return result; }
Source:
<code>private ObjectNode _createMappingsNode() { ObjectMapper mapper = new ObjectMapper(); ObjectNode propertiesNode = mapper.createObjectNode(); propertiesNode.put(RecordType.SCOPE.getName(), _createFieldNode(FIELD_TYPE_TEXT)); propertiesNode.put(RecordType.METRIC.getName(), _createFieldNode(FIELD_TYPE_TEXT)); propertiesNode.put(RecordType.TAGK.getName(), _createFieldNode(FIELD_TYPE_TEXT)); propertiesNode.put(RecordType.TAGV.getName(), _createFieldNode(FIELD_TYPE_TEXT)); propertiesNode.put(RecordType.NAMESPACE.getName(), _createFieldNode(FIELD_TYPE_TEXT)); <START> propertiesNode.put(RecordType.RETENTION_DISCOVERY.getName(), _createFieldNode(FIELD_TYPE_TEXT)); <END> propertiesNode.put("mts", _createFieldNodeNoAnalyzer(FIELD_TYPE_DATE)); ObjectNode typeNode = mapper.createObjectNode(); typeNode.put("properties", propertiesNode); ObjectNode mappingsNode = mapper.createObjectNode(); mappingsNode.put(TYPE_NAME, typeNode); return mappingsNode; }</code><technical_language>field_type integer/number here, nightly job a math calculation while purging stale tags</technical_language>

Target:
private ObjectNode _createMappingsNode() { ObjectMapper mapper = new ObjectMapper(); ObjectNode propertiesNode = mapper.createObjectNode(); propertiesNode.put(RecordType.SCOPE.getName(), _createFieldNode(FIELD_TYPE_TEXT)); propertiesNode.put(RecordType.METRIC.getName(), _createFieldNode(FIELD_TYPE_TEXT)); propertiesNode.put(RecordType.TAGK.getName(), _createFieldNode(FIELD_TYPE_TEXT)); propertiesNode.put(RecordType.TAGV.getName(), _createFieldNode(FIELD_TYPE_TEXT)); propertiesNode.put(RecordType.NAMESPACE.getName(), _createFieldNode(FIELD_TYPE_TEXT)); propertiesNode.put(RecordType.RETENTION_DISCOVERY.getName(), _createFieldNode(FIELD_TYPE_INTEGER)); propertiesNode.put("mts", _createFieldNodeNoAnalyzer(FIELD_TYPE_DATE)); ObjectNode typeNode = mapper.createObjectNode(); typeNode.put("properties", propertiesNode); ObjectNode mappingsNode = mapper.createObjectNode(); mappingsNode.put(TYPE_NAME, typeNode); return mappingsNode; }
Source:
<code>protected VDS checkForActiveVds() { List<VDS> hosts = getVdsDAO().getAllForStoragePoolAndStatus(getStoragePool().getId(), VDSStatus.Up); if (!hosts.isEmpty()) { try { <START> return hosts.get(SecureRandom.getInstance("SHA1PRNG").nextInt(hosts.size())); <END> } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_NO_VDS_IN_POOL); return null; }</code><technical_language>a bit hardcore for a mere selection of a random host for pool care host be? in favor of removing RandonUtils</technical_language>

Target:
protected VDS checkForActiveVds() { List<VDS> hosts = getVdsDAO().getAllForStoragePoolAndStatus(getStoragePool().getId(), VDSStatus.Up); if (!hosts.isEmpty()) { return hosts.get(new Random().nextInt(hosts.size())); } addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_NO_VDS_IN_POOL); return null; }
Source:
<code><START> public void importCertificate(Certificate cert) throws Exception { <END> final Map<String, String> trustStoreProperties = cmHelper.getTrustStoreSystemProperties(); String storeType = trustStoreProperties.get(TRUST_STORE_TYPE_KEY); final String storeLoc = trustStoreProperties.get(TRUST_STORE_KEY); final String passkey = trustStoreProperties.get(TRUST_STORE_PASSWORD_KEY); if (storeType == null) { LOG.warn("{} is not defined. Switch to use JKS by default", TRUST_STORE_TYPE_KEY); storeType = JKS_TYPE; } if (StringUtils.isNotBlank(passkey) && !(JKS_TYPE.equals(storeType) && storeLoc == null) && cert != null) { addCertificateToTrustStore(cert); } else { LOG.info("importCertificate -- validation failed"); if (JKS_TYPE.equals(storeType) && storeLoc == null) { LOG.error("{} is not defined.", TRUST_STORE_KEY); } if (StringUtils.isBlank(passkey)) { LOG.error("invalid password"); } if (null == cert) { LOG.error("Certificate is null"); } } }</code><technical_language>Wondering throwing Exception instead of CertificateManagerException</technical_language>

Target:
public void importCertificate(Certificate cert) throws CertificateManagerException { final Map<String, String> trustStoreProperties = cmHelper.getTrustStoreSystemProperties(); String storeType = trustStoreProperties.get(TRUST_STORE_TYPE_KEY); final String storeLoc = trustStoreProperties.get(TRUST_STORE_KEY); final String passkey = trustStoreProperties.get(TRUST_STORE_PASSWORD_KEY); if (storeType == null) { LOG.warn("{} is not defined. Switch to use JKS by default", TRUST_STORE_TYPE_KEY); storeType = JKS_TYPE; } if (StringUtils.isNotBlank(passkey) && !(JKS_TYPE.equals(storeType) && storeLoc == null) && cert != null) { addCertificateToTrustStore(cert); } else { LOG.info("importCertificate -- validation failed"); if (JKS_TYPE.equals(storeType) && storeLoc == null) { LOG.error("{} is not defined.", TRUST_STORE_KEY); } if (StringUtils.isBlank(passkey)) { LOG.error("invalid password"); } if (null == cert) { LOG.error("Certificate is null"); } } }
Source:
<code>public void post(Object event) { EventHandlerMethod[] handlers = byEventBaked.get( event.getClass() ); if ( handlers != null ) { for ( int i = 0; i < handlers.length; i++ ) { try { handlers[i].invoke( event ); } catch ( IllegalAccessException ex ) { throw new Error( "Method became inaccessible: " + event, ex ); } catch ( IllegalArgumentException ex ) { <START> throw new Error( "Method rejected target/argument: " + event, ex ); <END> } catch ( InvocationTargetException ex ) { logger.log( Level.WARNING, MessageFormat.format( "Error dispatching event {0} to listener {1}", event, handlers[i].getListener() ), ex.getCause() ); } } } }</code><technical_language>for is sufficient here</technical_language>

Target:
public void post(Object event) { EventHandlerMethod[] handlers = byEventBaked.get( event.getClass() ); if ( handlers != null ) { for ( EventHandlerMethod method : handlers ) { try { method.invoke( event ); } catch ( IllegalAccessException ex ) { throw new Error( "Method became inaccessible: " + event, ex ); } catch ( IllegalArgumentException ex ) { throw new Error( "Method rejected target/argument: " + event, ex ); } catch ( InvocationTargetException ex ) { logger.log( Level.WARNING, MessageFormat.format( "Error dispatching event {0} to listener {1}", event, method.getListener() ), ex.getCause() ); } } } }
Source:
<code>public static Function<Resource, TreeSet<Long>> resourceToPortSet() { return new Function<Resource, TreeSet<Long>>() { @Override @NotNull <START> public TreeSet<Long> apply(@Nullable Resource resource) { <END> return resourceValueRange(Optional.fromNullable(resource)); } }; }</code><technical_language>Please mark resource parameter final</technical_language>

Target:
public static Function<Resource, TreeSet<Long>> resourceToPortSet() { return ResourceToPortSet.INSTANCE; }
Source:
<code>private static String executeProcess(final CliCommandBuilder commandBuilder, final boolean logFailure, final Map<String, String> env) { Process cliProc = null; try { cliProc = Launcher.of(commandBuilder) .addEnvironmentVariables(env) .launch(); } catch (IOException e) { fail("Failed to start CLI process: " + e.getLocalizedMessage()); } final ByteArrayOutputStream out = new ByteArrayOutputStream(); final ByteArrayOutputStream err = new ByteArrayOutputStream(); CustomCLIExecutor.ConsoleConsumer.start(cliProc.getInputStream(), out); CustomCLIExecutor.ConsoleConsumer.start(cliProc.getErrorStream(), err); int exitCode = Integer.MIN_VALUE; try { boolean finished = cliProc.waitFor(CLI_PROC_TIMEOUT, TimeUnit.MILLISECONDS); if (finished) { exitCode = cliProc.exitValue(); } else { LOGGER.info("A timeout has occurred while invoking CLI command."); } } catch (InterruptedException e1) { Assert.fail("Interupted while waiting. Error Message" + e1.getMessage()); } finally { cliProc.destroyForcibly(); } String cliOutput = null; try { <START> cliOutput = out.toString(StandardCharsets.UTF_8.name()); <END> } catch (UnsupportedEncodingException e) { fail("UTF8 charset doesn't exist"); } if (logFailure && exitCode != 0) { LOGGER.info("Command's output: '" + cliOutput + "'"); if (err.size() > 0) { LOGGER.info("Command's error log: '" + err.toString() + "'"); } else { LOGGER.info("No output data for the command."); } } return exitCode + ": " + cliOutput; }</code><technical_language>CLI side, interactive session started, CLI print-out content default JVM platform encoding (that UTF-8). safer continue rely default encoding</technical_language>

Target:
private static String executeProcess(final CliCommandBuilder commandBuilder, final boolean logFailure, final Map<String, String> env) { Process cliProc = null; try { cliProc = Launcher.of(commandBuilder) .addEnvironmentVariables(env) .launch(); } catch (IOException e) { fail("Failed to start CLI process: " + e.getLocalizedMessage()); } final ByteArrayOutputStream out = new ByteArrayOutputStream(); final ByteArrayOutputStream err = new ByteArrayOutputStream(); CustomCLIExecutor.ConsoleConsumer.start(cliProc.getInputStream(), out); CustomCLIExecutor.ConsoleConsumer.start(cliProc.getErrorStream(), err); int exitCode = Integer.MIN_VALUE; try { boolean finished = cliProc.waitFor(CLI_PROC_TIMEOUT, TimeUnit.MILLISECONDS); if (finished) { exitCode = cliProc.exitValue(); } else { LOGGER.info("A timeout has occurred while invoking CLI command."); } } catch (InterruptedException e1) { Assert.fail("Interupted while waiting. Error Message" + e1.getMessage()); } finally { cliProc.destroyForcibly(); } final String cliOutput = out.toString(); if (logFailure && exitCode != 0) { LOGGER.info("Command's output: '" + cliOutput + "'"); if (err.size() > 0) { LOGGER.info("Command's error log: '" + err.toString() + "'"); } else { LOGGER.info("No output data for the command."); } } return exitCode + ": " + cliOutput; }
Source:
<code>private BestPossibleStateOutput compute(ClusterEvent event, Map<String, Resource> resourceMap, CurrentStateOutput currentStateOutput) { ClusterDataCache cache = event.getAttribute("ClusterDataCache"); BestPossibleStateOutput output = new BestPossibleStateOutput(); JobRebalancer.resetActiveTaskCount(cache.getLiveInstances().keySet(), currentStateOutput); <START> PriorityQueue<JobResourcePriority> jobResourceQueue = new PriorityQueue<JobResourcePriority>(); <END> TaskDriver taskDriver = null; for (Resource resource : resourceMap.values()) { IdealState idealState = cache.getIdealState(resource.getResourceName()); if (idealState != null && idealState.getRebalancerClassName() != null && idealState.getRebalancerClassName().equals(JobRebalancer.class.getName())) { if (taskDriver == null) { taskDriver = new TaskDriver((HelixManager) event.getAttribute("helixmanager")); } jobResourceQueue.add(new JobResourcePriority(resource, taskDriver)); } else { computeResourceBestPossibleState(event, cache, currentStateOutput, resource, output); } } Iterator<JobResourcePriority> itr = jobResourceQueue.iterator(); while (itr.hasNext()) { computeResourceBestPossibleState(event, cache, currentStateOutput, itr.next()._resource, output); } return output; }</code><technical_language>I get this is a queue. created in this stage, a bunch of added in, iterated through. Is reason a sorted set</technical_language>

Target:
private BestPossibleStateOutput compute(ClusterEvent event, Map<String, Resource> resourceMap, CurrentStateOutput currentStateOutput) { ClusterDataCache cache = event.getAttribute("ClusterDataCache"); BestPossibleStateOutput output = new BestPossibleStateOutput(); PriorityQueue<ResourcePriority> resourcePriorityQueue = new PriorityQueue<ResourcePriority>(); for (Resource resource : resourceMap.values()) { resourcePriorityQueue.add(new ResourcePriority(resource, cache.getIdealState(resource.getResourceName()), (HelixManager) event.getAttribute("helixmanager"))); } Iterator<ResourcePriority> itr = resourcePriorityQueue.iterator(); while (itr.hasNext()) { computeResourceBestPossibleState(event, cache, currentStateOutput, itr.next()._resource, output); } return output; }
Source:
<code>private RowExpression not(RowExpression expression) { <START> return call("not", metadata.getFunctionManager().lookupFunction("not", fromTypes(BOOLEAN)), BOOLEAN, expression); <END> }</code><technical_language>"not" function is in StandardFunctionResolution. I mind a test</technical_language>

Target:
private RowExpression not(RowExpression expression) { return call("not", new FunctionResolution(metadata.getFunctionManager()).notFunction(), BOOLEAN, expression); }
Source:
<code>public static PassthroughServer remove(URI uri) { URI keyURI = createKey(uri); ServerDescriptor serverDescriptor = SERVERS.remove(keyURI); if (serverDescriptor != null) { for (Connection connection : serverDescriptor.getConnections().keySet()) { try { LOGGER.warn("Force close {}", formatConnectionId(connection)); connection.close(); } catch (AssertionError e) { } catch (IOException e) { } } PassthroughConnection connection = serverDescriptor.server.connectNewClient("destroy-connection"); for(Entry entry : serverDescriptor.knownEntities.entrySet()) { @SuppressWarnings("unchecked") Class<? extends Entity> type = (Class) entry.getKey(); List args = (List)entry.getValue(); Long version = (Long)args.get(0); String stringArg = (String)args.get(1); try { EntityRef entityRef = connection.getEntityRef(type, version, stringArg); entityRef.destroy(); } catch (EntityNotProvidedException ex) { LOGGER.error("Entity destroy failed: ", ex); } catch (EntityNotFoundException ex) { LOGGER.error("Entity destroy failed: ", ex); } catch (PermanentEntityException e) { <START> LOGGER.error("Entity destroy failed (permanent???): ", e); <END> } } serverDescriptor.server.stop(); LOGGER.info("Stopped PassthroughServer at {}", keyURI); return serverDescriptor.server; } else { return null; } }</code><technical_language>exception is called e while others called ex. 3 question marks is weird a permanent destroy</technical_language>

Target:
public static PassthroughServer remove(URI uri) { URI keyURI = createKey(uri); ServerDescriptor serverDescriptor = SERVERS.remove(keyURI); if (serverDescriptor != null) { for (Connection connection : serverDescriptor.getConnections().keySet()) { try { LOGGER.warn("Force close {}", formatConnectionId(connection)); connection.close(); } catch (AssertionError e) { } catch (IOException e) { } } PassthroughConnection connection = serverDescriptor.server.connectNewClient("destroy-connection"); for(Entry entry : serverDescriptor.knownEntities.entrySet()) { @SuppressWarnings("unchecked") Class<? extends Entity> type = (Class) entry.getKey(); List args = (List)entry.getValue(); Long version = (Long)args.get(0); String stringArg = (String)args.get(1); try { EntityRef entityRef = connection.getEntityRef(type, version, stringArg); entityRef.destroy(); } catch (EntityNotProvidedException ex) { LOGGER.error("Entity destroy failed: ", ex); } catch (EntityNotFoundException ex) { LOGGER.error("Entity destroy failed: ", ex); } catch (PermanentEntityException ex) { LOGGER.error("Entity destroy failed (permanent???): ", ex); } } serverDescriptor.server.stop(); LOGGER.info("Stopped PassthroughServer at {}", keyURI); return serverDescriptor.server; } else { return null; } }
Source:
<code>public Person updatePerson(Config config, Person person) { String requestJson = buildGsonWithUpdatePersonAdapter().toJson(person); <START> String responseJson = postForJson(config, requestJson, "/person/{uuid}", person.getUuid()); <END> return (Person) JsonUtils.readJson(responseJson, Person.class); }</code><technical_language>remove this 'full' option</technical_language>

Target:
public Person updatePerson(Config config, Person person) { String requestJson = buildGsonWithUpdatePersonAdapter().toJson(person); String responseJson = postForJson(config, requestJson, "/person/{uuid}?v=full", person.getUuid()); return (Person) JsonUtils.readJson(responseJson, Person.class); }
Source:
<code>public DlmsDevice convertTo(final SmartMeteringDevice source, final Type<DlmsDevice> destinationType) { final DlmsDevice dlmsDevice = new DlmsDevice(); dlmsDevice.setDeviceIdentification(source.getDeviceIdentification()); dlmsDevice.setCommunicationMethod(source.getCommunicationMethod()); dlmsDevice.setCommunicationProvider(source.getCommunicationProvider()); dlmsDevice.setIccId(source.getICCId()); dlmsDevice.setHls3Active(source.isHLS3Active()); dlmsDevice.setHls4Active(source.isHLS4Active()); dlmsDevice.setHls5Active(source.isHLS5Active()); if (source.getMasterKey() != null) { final SecurityKey masterKey = new SecurityKey(); masterKey.setSecurityKeyType(SecurityKeyType.E_METER_MASTER); masterKey.setSecurityKey(source.getMasterKey()); masterKey.setValidFrom(source.getDeliveryDate()); dlmsDevice.addSecurityKey(masterKey); <START> } <END> if (source.getAuthenticationKey() != null) { final SecurityKey authenticationKey = new SecurityKey(); authenticationKey.setSecurityKeyType(SecurityKeyType.E_METER_AUTHENTICATION); authenticationKey.setSecurityKey(source.getAuthenticationKey()); authenticationKey.setValidFrom(source.getDeliveryDate()); dlmsDevice.addSecurityKey(authenticationKey); } if (source.getGlobalEncryptionUnicastKey() != null) { final SecurityKey encryptionKey = new SecurityKey(); encryptionKey.setSecurityKeyType(SecurityKeyType.E_METER_ENCRYPTION); encryptionKey.setSecurityKey(source.getGlobalEncryptionUnicastKey()); encryptionKey.setValidFrom(source.getDeliveryDate()); dlmsDevice.addSecurityKey(encryptionKey); } return dlmsDevice; }</code><technical_language>A function crreate a security key nice. function for authentication key encryption key</technical_language>

Target:
public DlmsDevice convertTo(final SmartMeteringDevice source, final Type<DlmsDevice> destinationType) { final DlmsDevice dlmsDevice = new DlmsDevice(); dlmsDevice.setDeviceIdentification(source.getDeviceIdentification()); dlmsDevice.setCommunicationMethod(source.getCommunicationMethod()); dlmsDevice.setCommunicationProvider(source.getCommunicationProvider()); dlmsDevice.setIccId(source.getICCId()); dlmsDevice.setHls3Active(source.isHLS3Active()); dlmsDevice.setHls4Active(source.isHLS4Active()); dlmsDevice.setHls5Active(source.isHLS5Active()); if (source.getMasterKey() != null) { dlmsDevice.addSecurityKey(new SecurityKey(dlmsDevice, SecurityKeyType.E_METER_MASTER, source.getMasterKey(), source.getDeliveryDate(), null)); } if (source.getAuthenticationKey() != null) { dlmsDevice.addSecurityKey(new SecurityKey(dlmsDevice, SecurityKeyType.E_METER_AUTHENTICATION, source .getAuthenticationKey(), source.getDeliveryDate(), null)); } if (source.getGlobalEncryptionUnicastKey() != null) { dlmsDevice.addSecurityKey(new SecurityKey(dlmsDevice, SecurityKeyType.E_METER_ENCRYPTION, source .getGlobalEncryptionUnicastKey(), source.getDeliveryDate(), null)); } return dlmsDevice; }
Source:
<code>public void testSerializationComplex() { TDigest digest = new TDigest(); addAll(digest, asList(0, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 5, 6, 7)); TDigest deserialized = TDigest.deserialize(digest.serialize()); <START> assertEquals(deserialized.getMin(), digest.getMin()); <END> assertEquals(deserialized.getMax(), digest.getMax()); assertEquals(deserialized.getCount(), digest.getCount()); for (double quantile = 0; quantile <= 1; quantile += 0.1) { assertEquals(deserialized.valueAt(quantile), digest.valueAt(quantile)); } }</code><technical_language>this equals for TDigest is repeated a number of times... add a method</technical_language>

Target:
public void testSerializationComplex() { TDigest digest = new TDigest(); addAll(digest, asList(0, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 5, 6, 7)); TDigest deserialized = TDigest.deserialize(digest.serialize()); assertSimilar(deserialized, digest); for (double quantile = 0; quantile <= 1; quantile += 0.1) { assertEquals(deserialized.valueAt(quantile), digest.valueAt(quantile)); } }
Source:
<code>private static boolean isOptional(ExpressionTree expression) { <START> return expression.symbolType().is(Optional.class.getName()) && !expression.is(Tree.Kind.NULL_LITERAL); <END> }</code><technical_language>Please remove usage of .class, for reason above</technical_language>

Target:
private static boolean isOptional(ExpressionTree expression) { return expression.symbolType().is(OPTIONAL) && !isNull(expression); }
Source:
<code>public void close() { <START> closeAsync().awaitUninterruptibly(); <END> }</code><technical_language>rethrow interruptedexception reset interrupted bit. wrap in a RuntimeException</technical_language>

Target:
public void close() { try { closeAsync().await(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } }
Source:
<code>public int compare(Repository db, FileElement localFile, FileElement remoteFile, String mergedFilePath, String toolName, BooleanOption prompt, BooleanOption gui, BooleanOption trustExitCode) throws DiffToolException { int rc = 0; IDiffTool tool = guessTool(toolName, gui); try { File workingDir = db.getWorkTree(); String localFilePath = localFile.getFile(workingDir).getPath(); String remoteFilePath = remoteFile.getFile(workingDir).getPath(); String command = tool.getCommand(); command = command.replace("$LOCAL", localFilePath); command = command.replace("$REMOTE", remoteFilePath); command = command.replace("$MERGED", mergedFilePath); Map<String, String> env = new TreeMap<>(); env.put(Constants.GIT_DIR_KEY, db.getDirectory().getAbsolutePath()); env.put("LOCAL", localFilePath); env.put("REMOTE", remoteFilePath); env.put("MERGED", mergedFilePath); ExecutionResult result = CommandExecutor.run(db.getFS(), command, workingDir, env); rc = result.getRc(); if (rc != 0) { boolean trust = config.isTrustExitCode(); if (trustExitCode.isDefined()) { trust = trustExitCode.toBoolean(); } <START> if (trust) { <END> throw new DiffToolException( new String(result.getStderr().toByteArray())); } } } catch (Exception e) { throw new DiffToolException(e); } finally { localFile.cleanTemporaries(); remoteFile.cleanTemporaries(); } return rc; }</code><technical_language>throw exception for exit codes 126 (permission for executing command denied) 127 (command found), if trust exit code is false</technical_language>

Target:
public ExecutionResult compare(Repository db, FileElement localFile, FileElement remoteFile, String mergedFilePath, String toolName, BooleanOption prompt, BooleanOption gui, BooleanOption trustExitCode) throws ToolException { IDiffTool tool = guessTool(toolName, gui); try { File workingDir = db.getWorkTree(); String localFilePath = localFile.getFile().getPath(); String remoteFilePath = remoteFile.getFile().getPath(); String command = tool.getCommand(); command = command.replace("$LOCAL", localFilePath); command = command.replace("$REMOTE", remoteFilePath); command = command.replace("$MERGED", mergedFilePath); Map<String, String> env = new TreeMap<>(); env.put(Constants.GIT_DIR_KEY, db.getDirectory().getAbsolutePath()); env.put("LOCAL", localFilePath); env.put("REMOTE", remoteFilePath); env.put("MERGED", mergedFilePath); boolean trust = config.isTrustExitCode(); if (trustExitCode.isDefined()) { trust = trustExitCode.toBoolean(); } CommandExecutor cmdExec = new CommandExecutor(db.getFS(), trust); return cmdExec.run(command, workingDir, env); } catch (IOException | InterruptedException e) { throw new ToolException(e); } finally { localFile.cleanTemporaries(); remoteFile.cleanTemporaries(); } }
Source:
<code>private GridData createServerUrlField(final ScrolledForm form) { Label labelUrl = new Label(form.getBody(), SWT.NULL); labelUrl.setText(Messages.ServerLocationWizardPage_label_host); serverUrlText = new Text(form.getBody(), SWT.BORDER | SWT.SINGLE); GridData urlGd = new GridData(GridData.FILL_HORIZONTAL); <START> GridData gd = urlGd; <END> gd.horizontalSpan = 2; serverUrlText.setLayoutData(gd); if (edit) { serverUrlText.setText(StringUtils.defaultString(server.getHost())); } else { serverUrlText.setText(DEFAULT_URL_SUGGESTION); } serverUrlText.setFocus(); serverUrlText.setSelection(serverUrlText.getText().length()); serverUrlText.addModifyListener(e -> { if (!edit && !serverIdManuallyChanged) { try { URL url = new URL(serverUrlText.getText()); serverIdText.removeModifyListener(idModifyListener); serverIdText.setText(StringUtils.substringBefore(url.getHost(), ".")); serverIdText.addModifyListener(idModifyListener); } catch (MalformedURLException e1) { } } dialogChanged(); }); return urlGd; }</code><technical_language>pointless extra local variable</technical_language>

Target:
private void createServerUrlField(final ScrolledForm form) { Label labelUrl = new Label(form.getBody(), SWT.NULL); labelUrl.setText(Messages.ServerLocationWizardPage_label_host); serverUrlText = new Text(form.getBody(), SWT.BORDER | SWT.SINGLE); GridData gd = new GridData(GridData.FILL_HORIZONTAL); gd.horizontalSpan = 2; serverUrlText.setLayoutData(gd); if (edit) { serverUrlText.setText(StringUtils.defaultString(server.getHost())); } else { serverUrlText.setText(DEFAULT_URL_SUGGESTION); } serverUrlText.setFocus(); serverUrlText.setSelection(serverUrlText.getText().length()); serverUrlText.addModifyListener(e -> { if (!edit && !serverIdManuallyChanged) { try { URL url = new URL(serverUrlText.getText()); serverIdText.removeModifyListener(idModifyListener); serverIdText.setText(StringUtils.substringBefore(url.getHost(), ".")); serverIdText.addModifyListener(idModifyListener); } catch (MalformedURLException e1) { } } dialogChanged(); }); }
Source:
<code>private String constructParametersString(DetailAST methodDefToken) { <START> StringBuilder sb = new StringBuilder(); <END> final DetailAST parametersToken = methodDefToken.findFirstToken(TokenTypes.PARAMETERS); for (DetailAST ast = parametersToken.getFirstChild(); ast != null; ast = ast.getNextSibling()) { if (ast.getType() != TokenTypes.PARAMETER_DEF) { continue; } final DetailAST typeToken = ast.findFirstToken(TokenTypes.TYPE); final DetailAST identToken = typeToken.findFirstToken(TokenTypes.IDENT); String parameterType = ""; if (identToken != null) { parameterType = identToken.getText(); } else { DetailAST arrayDeclarator = typeToken.findFirstToken(TokenTypes.ARRAY_DECLARATOR); if (arrayDeclarator == null) { parameterType = typeToken.getFirstChild().getText(); } DetailAST arrayDeclaratorIterator = arrayDeclarator; while (arrayDeclaratorIterator != null) { DetailAST temp = arrayDeclaratorIterator.findFirstToken(TokenTypes.ARRAY_DECLARATOR); if (temp == null) { parameterType = arrayDeclaratorIterator.getFirstChild().getText(); break; } arrayDeclaratorIterator = temp; } } sb.append(parameterType).append("-"); } int size = sb.length(); if (size == 0) { return null; } return sb.substring(0, size - 1); }</code><technical_language>suggestion final StringBuilder sb = new StringBuilder();</technical_language>

Target:
private String constructParametersString(DetailAST methodDefToken) { final StringBuilder sb = new StringBuilder(); final DetailAST parametersToken = methodDefToken.findFirstToken(TokenTypes.PARAMETERS); for (DetailAST ast = parametersToken.getFirstChild(); ast != null; ast = ast.getNextSibling()) { if (ast.getType() != TokenTypes.PARAMETER_DEF) { continue; } final DetailAST typeToken = ast.findFirstToken(TokenTypes.TYPE); final DetailAST identToken = typeToken.findFirstToken(TokenTypes.IDENT); String parameterType = ""; if (identToken != null) { parameterType = identToken.getText(); } else { DetailAST arrayDeclarator = typeToken.findFirstToken(TokenTypes.ARRAY_DECLARATOR); if (arrayDeclarator == null) { parameterType = typeToken.getFirstChild().getText(); } DetailAST arrayDeclaratorIterator = arrayDeclarator; while (arrayDeclaratorIterator != null) { DetailAST temp = arrayDeclaratorIterator.findFirstToken(TokenTypes.ARRAY_DECLARATOR); if (temp == null) { parameterType = arrayDeclaratorIterator.getFirstChild().getText(); break; } arrayDeclaratorIterator = temp; } } sb.append(parameterType).append("-"); } int size = sb.length(); if (size == 0) { return null; } return sb.substring(0, size - 1); }
Source:
<code>public void single_file() throws Exception { PhpIniSensor sensor = new PhpIniSensor(null); ActiveRules activeRules = new ActiveRulesBuilder() .create(RuleKey.of("repo1", "rule1")) .activate() .build(); CheckFactory checkFactory = new CheckFactory(activeRules); Checks<PhpIniCheck> checks = checkFactory.<PhpIniCheck>create("repo1").addAnnotatedChecks(MyCheck.class); <START> DefaultInputFile file1 = new DefaultInputFile("php.ini", "php.ini").initMetadata("line1\nline2\n"); <END> context.fileSystem().add(file1); sensor.execute(context, checks); Collection<Issue> issues = context.allIssues(); assertThat(issues).hasSize(1); Issue issue = issues.iterator().next(); assertThat(issue.ruleKey().rule()).isEqualTo("rule1"); assertThat(issue.primaryLocation().inputComponent()).isEqualTo(file1); assertThat(issue.primaryLocation().message()).isEqualTo("message1"); assertThat(issue.primaryLocation().textRange().start().line()).isEqualTo(2); }</code><technical_language>@pynicolas i avoid for moduleKey relativePath</technical_language>

Target:
public void single_file() throws Exception { File baseDir = new File("src/test/resources/phpini"); SensorContextTester context = SensorContextTester.create(baseDir); DefaultInputFile file1 = setupSingleFile(baseDir, context); sensor().execute(context, checks()); Collection<Issue> issues = context.allIssues(); assertThat(issues).hasSize(1); Issue issue = issues.iterator().next(); assertThat(issue.ruleKey().rule()).isEqualTo("rule1"); assertThat(issue.primaryLocation().inputComponent()).isEqualTo(file1); assertThat(issue.primaryLocation().message()).isEqualTo("message1"); assertThat(issue.primaryLocation().textRange().start().line()).isEqualTo(2); }
Source:
<code>public IServer getServer(IModule module, IModuleArtifact moduleArtifact, IProgressMonitor monitor) throws CoreException { IServer server = ServerCore.getDefaultServer(module); <START> if (server != null && !ServerUtil.containsModule(server, module, monitor)) { <END> IServerWorkingCopy wc = server.createWorkingCopy(); try { ServerUtil.modifyModules(wc, new IModule[] { module }, new IModule[0], monitor); wc.save(false, monitor); } catch (CoreException ce) { server = null; } } IServer[] servers = getCompatibleServers(module); if( servers.length == 1 ) return servers[0]; Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(); if (server == null) { FullPublishToServerWizard wizard = new FullPublishToServerWizard(module, moduleArtifact); WizardDialog dialog = new WizardDialog(shell, wizard); if (dialog.open() == Window.CANCEL) { if (monitor != null) monitor.setCanceled(true); return null; } try { Job.getJobManager().join("org.eclipse.wst.server.ui.family", null); } catch (Exception e) { } server = wizard.getServer(); boolean preferred = wizard.isPreferredServer(); if (server != null && preferred) { try { ServerCore.setDefaultServer(module, server, monitor); } catch (CoreException ce) { String message = "Could not save server preference information."; ErrorDialog.openError(shell, "Server Error", message, ce.getStatus()); } } } try { Job.getJobManager().join("org.eclipse.wst.server.ui.family", new NullProgressMonitor()); } catch (Exception e) { } return server; }</code><technical_language>default server of a module module</technical_language>

Target:
public IServer getServer(IModule module, IModuleArtifact moduleArtifact, IProgressMonitor monitor) throws CoreException { IServer server = ServerCore.getDefaultServer(module); if (server != null && !ServerUtil.containsModule(server, module, monitor)) { IServerWorkingCopy wc = server.createWorkingCopy(); try { ServerUtil.modifyModules(wc, new IModule[] { module }, new IModule[0], monitor); wc.save(false, monitor); } catch (CoreException ce) { WTPOveridePlugin.logError(ce); server = null; } } IServer[] servers = getCompatibleServers(module); if( servers.length == 1 ) return servers[0]; Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(); if (server == null) { FullPublishToServerWizard wizard = new FullPublishToServerWizard(module, moduleArtifact); WizardDialog dialog = new WizardDialog(shell, wizard); if (dialog.open() == Window.CANCEL) { if (monitor != null) monitor.setCanceled(true); return null; } joinJobFamily(); server = wizard.getServer(); boolean preferred = wizard.isPreferredServer(); if (server != null && preferred) { try { ServerCore.setDefaultServer(module, server, monitor); } catch (CoreException ce) { String message = "Could not save server preference information."; ErrorDialog.openError(shell, "Server Error", message, ce.getStatus()); } } } joinJobFamily(); return server; }
Source:
<code>private void populateCPUList(ClusterModel clusterModel, List<ServerCpu> cpus, boolean canChangeArchitecture) { ServerCpu oldSelectedCpu = clusterModel.getCPU().getSelectedItem(); clusterModel.getCPU().setItems(cpus); clusterModel.getCPU().setSelectedItem(oldSelectedCpu != null ? Linq.firstOrDefault(cpus, new Linq.ServerCpuPredicate(oldSelectedCpu.getCpuName())) : null); if (clusterModel.getCPU().getSelectedItem() == null || !isCPUinitialized) { initCPU(); } if (clusterModel.getIsEdit()) { if (canChangeArchitecture) { getArchitecture().setItems(new ArrayList<ArchitectureType>(Arrays.asList(ArchitectureType.values()))); } else { getArchitecture().setItems(new ArrayList<ArchitectureType>(Arrays.asList(clusterModel.getEntity() .getArchitecture()))); } ArchitectureType oldSelectedArch = (ArchitectureType) clusterModel.getArchitecture().getSelectedItem(); if (oldSelectedArch != null) { getArchitecture().setSelectedItem(oldSelectedArch); } else { getArchitecture().setSelectedItem(getEntity().getArchitecture()); } <START> } else { <END> getArchitecture().setItems(new ArrayList<ArchitectureType>(Arrays.asList(ArchitectureType.values()))); getArchitecture().setSelectedItem(ArchitectureType.undefined); } }</code><technical_language>try setting items instead</technical_language>

Target:
private void populateCPUList(ClusterModel clusterModel, List<ServerCpu> cpus, boolean canChangeArchitecture) { ServerCpu oldSelectedCpu = clusterModel.getCPU().getSelectedItem(); clusterModel.getCPU().setItems(cpus); clusterModel.getCPU().setSelectedItem(oldSelectedCpu != null ? Linq.firstOrDefault(cpus, new Linq.ServerCpuPredicate(oldSelectedCpu.getCpuName())) : null); if (clusterModel.getCPU().getSelectedItem() == null || !isCPUinitialized) { initCPU(); } if (clusterModel.getIsEdit()) { if (canChangeArchitecture) { getArchitecture().setItems(new ArrayList<ArchitectureType>(Arrays.asList(ArchitectureType.values()))); } else { getArchitecture().setItems(new ArrayList<ArchitectureType>(Arrays.asList(clusterModel.getEntity() .getArchitecture()))); } ArchitectureType oldSelectedArch = (ArchitectureType) clusterModel.getArchitecture().getSelectedItem(); if (oldSelectedArch != null) { getArchitecture().setSelectedItem(oldSelectedArch); } else { getArchitecture().setSelectedItem(getEntity().getArchitecture()); } } else { filterUnsupportedArchs(clusterModel); getArchitecture().setSelectedItem(ArchitectureType.undefined); } }