auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private Type targetType(TypeCastTree tree) { Tree parent = skipParentheses(tree.parent()); Type target = null; if(parent.is(Tree.Kind.RETURN_STATEMENT)) { Tree method = parent; <START> while (!method.is(Tree.Kind.METHOD)) { <END> method = method.parent(); } target = ((JavaType.MethodJavaType) ((MethodTree) method).symbol().type()).resultType(); } else if (parent.is(Tree.Kind.VARIABLE)) { VariableTree variableTree = (VariableTree) parent; target = variableTree.symbol().type(); } else if (parent.is(Tree.Kind.METHOD_INVOCATION)) { MethodInvocationTree mit = (MethodInvocationTree) parent; if(mit.symbol().isMethodSymbol()) { JavaSymbol.MethodJavaSymbol sym = (JavaSymbol.MethodJavaSymbol) mit.symbol(); int castArgIndex = mit.arguments().indexOf(tree); target = sym.parameterTypes().get(castArgIndex); } } else if(parent.is(Tree.Kind.MEMBER_SELECT, Tree.Kind.CONDITIONAL_EXPRESSION)) { target = tree.type().symbolType(); } else if(parent instanceof ExpressionTree) { target = ((ExpressionTree) parent).symbolType(); } return target; }</code><technical_language>Return statement necessary in a method. case trigger a NPE. class H { java.util.concurrent.Callable<H> c0 = () -> { return (H) getValue(); }; private Object getValue() { return null; } }</technical_language>

Target:
private static Type targetType(TypeCastTree tree) { Tree parent = skipParentheses(tree.parent()); Type target = null; if(parent.is(Tree.Kind.RETURN_STATEMENT)) { Tree method = parent; while (!method.is(Tree.Kind.METHOD, Tree.Kind.LAMBDA_EXPRESSION)) { method = method.parent(); } target = method.is(Tree.Kind.LAMBDA_EXPRESSION) ? null : ((JavaType.MethodJavaType) ((MethodTree) method).symbol().type()).resultType(); } else if (parent.is(Tree.Kind.VARIABLE)) { VariableTree variableTree = (VariableTree) parent; target = variableTree.symbol().type(); } else if (parent.is(Tree.Kind.METHOD_INVOCATION)) { MethodInvocationTree mit = (MethodInvocationTree) parent; if(mit.symbol().isMethodSymbol()) { JavaSymbol.MethodJavaSymbol sym = (JavaSymbol.MethodJavaSymbol) mit.symbol(); int castArgIndex = mit.arguments().indexOf(tree); target = sym.parameterTypes().get(castArgIndex); } } else if(parent.is(Tree.Kind.MEMBER_SELECT, Tree.Kind.CONDITIONAL_EXPRESSION)) { target = tree.type().symbolType(); } else if(parent instanceof ExpressionTree) { target = ((ExpressionTree) parent).symbolType(); } return target; }
Source:
<code>public S withEnterpriseEdition() { setDockerImageName(getDockerImageName() + "-enterprise"); LicenseAcceptance.assertLicenseAccepted(getDockerImageName()); <START> <END> addEnv("NEO4J_ACCEPT_LICENSE_AGREEMENT", "yes"); return self(); }</code><technical_language>I remove this logic completely. Adding -enterprise suffix custom image is a bit weird, it</technical_language>

Target:
public S withEnterpriseEdition() { if (!standardImage) { throw new IllegalStateException( String.format("Cannot use enterprise version with alternative image %s.", getDockerImageName())); } setDockerImageName(DEFAULT_IMAGE_NAME.withTag(ENTERPRISE_TAG).asCanonicalNameString()); LicenseAcceptance.assertLicenseAccepted(getDockerImageName()); addEnv("NEO4J_ACCEPT_LICENSE_AGREEMENT", "yes"); return self(); }
Source:
<code>private ProductType(String name, String description) { super(name); <START> this.description = ArgChecker.notEmpty(description, "description"); <END> }</code><technical_language>notBlank? notEmpty allows a string whitespace</technical_language>

Target:
private ProductType(String name, String description) { super(name); this.description = ArgChecker.notBlank(description, "description"); }
Source:
<code>private void buildSectionPanelsForForAjaxLoading(List<String> sections, InstructorFeedbackResultsPageViewType viewType) { sectionPanels = new LinkedHashMap<>(); boolean hasGeneralFeedback = false; boolean hasTeamsInNoSection = bundle.getTeamsInSectionFromRoster(Const.DEFAULT_SECTION).size() > 0; if ((viewType == InstructorFeedbackResultsPageViewType.RECIPIENT_GIVER_QUESTION || viewType == InstructorFeedbackResultsPageViewType.RECIPIENT_QUESTION_GIVER) <START> && bundle.containsResponsesToInstructorOrGeneral()) { <END> hasGeneralFeedback = true; } if (hasGeneralFeedback || hasTeamsInNoSection) { InstructorFeedbackResultsSectionPanel sectionPanel = new InstructorFeedbackResultsSectionPanel(Const.DEFAULT_SECTION, Const.NO_SPECIFIC_SECTION, true); sectionPanels.put(Const.DEFAULT_SECTION, sectionPanel); } for (String section : sections) { InstructorFeedbackResultsSectionPanel sectionPanel = new InstructorFeedbackResultsSectionPanel(section, section, true); sectionPanels.put(section, sectionPanel); } }</code><technical_language>if statement tells if viewType is blablabla responses feedback instructors -> hasGeneralFeedback. A bit confusing. I if statement separated condition disjunction. feedbackToInstructor || generalFeedback || studentInNoSection</technical_language>

Target:
private void buildSectionPanelsForForAjaxLoading(List<String> sections, InstructorFeedbackResultsPageViewType viewType) { sectionPanels = new LinkedHashMap<>(); if (hasEntitiesInNoSpecificSection(viewType)) { InstructorFeedbackResultsSectionPanel sectionPanel = new InstructorFeedbackResultsSectionPanel(Const.DEFAULT_SECTION, Const.NO_SPECIFIC_SECTION, true); sectionPanels.put(Const.DEFAULT_SECTION, sectionPanel); } for (String section : sections) { InstructorFeedbackResultsSectionPanel sectionPanel = new InstructorFeedbackResultsSectionPanel(section, section, true); sectionPanels.put(section, sectionPanel); } }
Source:
<code>private Set<PlanInstanceInput> toPlanInstanceInputs(Map<String, String> inputs) { Set<PlanInstanceInput> result = new HashSet<PlanInstanceInput>(); for (String key : inputs.keySet()) { <START> String val = inputs.get(key); <END> result.add(new PlanInstanceInput(key, val, "string")); } return result; }</code><technical_language>cleaner iterate entry set here. Alternatively forEach: inputs.forEach((key, value) -> result.add(new PlanInstanceInput(key, value, "string")));</technical_language>

Target:
private Set<PlanInstanceInput> toPlanInstanceInputs(Map<String, String> inputs) { Set<PlanInstanceInput> result = new HashSet<PlanInstanceInput>(); inputs.forEach((key, value) -> result.add(new PlanInstanceInput(key, value, "string"))); return result; }
Source:
<code>public void testLinear() throws CyclicDependencyException { DependencyGraph<Integer> graph = new DependencyGraph<>(); int size = 100; for (int i = 1; i <= size; i++) { graph.addDependency(i, i - 1); } List<Integer> sort = graph.topologicalSort(); <START> assertTrue(sort.size() == size + 1); <END> assertTrue(sort.get(0) == 100); assertTrue(sort.get(100) == 0); }</code><technical_language>Eclipse complains object/int comparison. <LINK_0></technical_language>

Target:
public void testLinear() throws CyclicDependencyException { DependencyGraph<Integer> graph = new DependencyGraph<>(); int size = 100; for (int i = 1; i <= size; i++) { graph.addDependency(i, i - 1); } List<Integer> sort = graph.topologicalSort(); assertEquals(sort.size(), size + 1); assertEquals(sort.get(0), Integer.valueOf(100)); assertEquals(sort.get(100), Integer.valueOf(0)); }
Source:
<code>public Iterable<Rowboat> getRows() { return new Iterable<Rowboat>() { @Override public Iterator<Rowboat> iterator() { return (Iterators.transform( index.getFacts().entrySet().iterator(), new Function<Map.Entry<IncrementalIndex.TimeAndDims, ?>, Rowboat>() { int count = 0; @Override public Rowboat apply( @Nullable Map.Entry<IncrementalIndex.TimeAndDims, ?> input ) { final IncrementalIndex.TimeAndDims timeAndDims = input.getKey(); final String[][] dimValues = timeAndDims.getDims(); <START> final Object aggrs = input.getValue(); <END> int[][] dims = new int[dimValues.length][]; for (String dimension : index.getDimensions()) { int dimIndex = index.getDimensionIndex(dimension); final IncrementalIndex.DimDim dimDim = index.getDimension(dimension); dimDim.sort(); if (dimIndex >= dimValues.length || dimValues[dimIndex] == null) { continue; } dims[dimIndex] = new int[dimValues[dimIndex].length]; if (dimIndex >= dims.length || dims[dimIndex] == null) { continue; } for (int i = 0; i < dimValues[dimIndex].length; ++i) { dims[dimIndex][i] = dimDim.getSortedId(dimValues[dimIndex][i]); } } Object[] metrics = new Object[index.getMetricAggs().length]; for (int i = 0; i < metrics.length; i++) { metrics[i] = index.getMetricObjectValue(aggrs, i); } return new Rowboat( timeAndDims.getTimestamp(), dims, metrics, count++ ); } } )); } }; }</code><technical_language>is some kind of type information here, Object code hard read. want more explicit variable names if remove type information</technical_language>

Target:
public Iterable<Rowboat> getRows() { return new Iterable<Rowboat>() { @Override public Iterator<Rowboat> iterator() { final List<IncrementalIndex.DimensionDesc> dimensions = index.getDimensions(); final IncrementalIndex.SortedDimLookup[] sortedDimLookups = new IncrementalIndex.SortedDimLookup[dimensions.size()]; for (IncrementalIndex.DimensionDesc dimension : dimensions) { sortedDimLookups[dimension.getIndex()] = indexers.get(dimension.getName()).getDimLookup(); } return Iterators.transform( index.getFacts().entrySet().iterator(), new Function<Map.Entry<IncrementalIndex.TimeAndDims, Object>, Rowboat>() { int count = 0; @Override public Rowboat apply( Map.Entry<IncrementalIndex.TimeAndDims, Object> input ) { final IncrementalIndex.TimeAndDims timeAndDims = input.getKey(); final int[][] dimValues = timeAndDims.getDims(); final Object aggrs = input.getValue(); int[][] dims = new int[dimValues.length][]; for (IncrementalIndex.DimensionDesc dimension : dimensions) { final int dimIndex = dimension.getIndex(); if (dimIndex >= dimValues.length || dimValues[dimIndex] == null) { continue; } dims[dimIndex] = new int[dimValues[dimIndex].length]; if (dimIndex >= dims.length || dims[dimIndex] == null) { continue; } for (int i = 0; i < dimValues[dimIndex].length; ++i) { dims[dimIndex][i] = sortedDimLookups[dimIndex].getSortedIdFromUnsortedId(dimValues[dimIndex][i]); } } Object[] metrics = new Object[index.getMetricAggs().length]; for (int i = 0; i < metrics.length; i++) { metrics[i] = index.getMetricObjectValue(aggrs, i); } return new Rowboat( timeAndDims.getTimestamp(), dims, metrics, count++ ); } } ); } }; }
Source:
<code>protected void doGet(final HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { <START> final int fid = Integer.parseInt(request.getParameter("fid")); <END> String filePath = FILEPATH_PREFIX + "/" + fid; File file = new File(filePath); FileInputStream fileInputStream = new FileInputStream(file); StoredFile fileMetadata = SQLSource.interact(new SQLInteractionInterface<StoredFile>() { @Override public StoredFile run(Connection connection) throws ServiceException, SQLException { return StoredFile.lookup(connection, fid); } }); String fileName = fileMetadata.getTitle() + "." + fileMetadata.getExtension(); ServletContext context = getServletContext(); String mimeType = context.getMimeType(filePath); if (mimeType == null) { mimeType = "application/octet-stream"; } response.setContentType(mimeType); response.setContentLength((int) file.length()); String headerKey = "Content-Disposition"; String headerValue = String.format("attachment; filename=\"%s\"", fileName); response.setHeader(headerKey, headerValue); OutputStream outputStream = response.getOutputStream(); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = fileInputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } }</code><technical_language>OMUtil.parseInt() instead of Integer.parseInt(). null check parameter is a number. Otherwise, if page specifies fid a string for fid page break</technical_language>

Target:
protected void doGet(final HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { final int fid = OMUtil.parseInt(request.getParameter("fid")); StoredFile fileMetadata = SQLSource.interact(new SQLInteractionInterface<StoredFile>() { @Override public StoredFile run(Connection connection) throws ServiceException, SQLException { return StoredFile.lookup(connection, fid); } }); File file = new File(fileMetadata.getFilePath()); FileInputStream fileInputStream = new FileInputStream(file); try { String fileName = fileMetadata.getTitle() + "." + fileMetadata.getExtension(); ServletContext context = getServletContext(); String mimeType = context.getMimeType(fileMetadata.getFilePath()); if (mimeType == null) { mimeType = "application/octet-stream"; } response.setContentType(mimeType); response.setContentLength((int) file.length()); String headerKey = "Content-Disposition"; String headerValue = String.format("attachment; filename=\"%s\"", fileName); response.setHeader(headerKey, headerValue); OutputStream outputStream = response.getOutputStream(); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = fileInputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } outputStream.close(); } catch(IOException e) { throw new ServiceException(ServiceStatus.FILE_READ_ERROR); } finally { fileInputStream.close(); } }
Source:
<code>private boolean isCaseSensitiveUsername(String username, int tenantId){ if (UserStoreMgtDSComponent.getRealmService() != null) { try { if (UserStoreMgtDSComponent.getRealmService().getTenantUserRealm(tenantId) != null) { UserStoreManager userStoreManager = (UserStoreManager) UserStoreMgtDSComponent.getRealmService() .getTenantUserRealm(tenantId).getUserStoreManager(); UserStoreManager userAvailableUserStoreManager = userStoreManager.getSecondaryUserStoreManager (UserCoreUtil.extractDomainFromName(username)); String isUsernameCaseInsensitiveString = userAvailableUserStoreManager.getRealmConfiguration() .getUserStoreProperty(CASE_INSENSITIVE_USERNAME); <START> if (isUsernameCaseInsensitiveString != null) { <END> return !Boolean.parseBoolean(isUsernameCaseInsensitiveString); } } } catch (UserStoreException e) { if (log.isDebugEnabled()) { log.debug("Error while reading user store property CaseInsensitiveUsername. Considering as false."); } } } return true; }</code><technical_language>need null check for Boolean.parseBoolean()</technical_language>

Target:
private boolean isCaseSensitiveUsername(String username, int tenantId) { if (UserStoreMgtDSComponent.getRealmService() != null) { try { if (UserStoreMgtDSComponent.getRealmService().getTenantUserRealm(tenantId) != null) { UserStoreManager userStoreManager = (UserStoreManager) UserStoreMgtDSComponent.getRealmService() .getTenantUserRealm(tenantId).getUserStoreManager(); UserStoreManager userAvailableUserStoreManager = userStoreManager.getSecondaryUserStoreManager (UserCoreUtil.extractDomainFromName(username)); String isUsernameCaseInsensitiveString = userAvailableUserStoreManager.getRealmConfiguration() .getUserStoreProperty(CASE_INSENSITIVE_USERNAME); return !Boolean.parseBoolean(isUsernameCaseInsensitiveString); } } catch (UserStoreException e) { if (log.isDebugEnabled()) { log.debug("Error while reading user store property CaseInsensitiveUsername. Considering as false."); } } } return true; }
Source:
<code>public void testHolderSave() throws Exception { File directory = folder.newFolder("testSave"); FileBasedStateRepository stateRepository = new FileBasedStateRepository(directory); String holderName = "myHolder"; StateHolder<Long, String> myHolder = stateRepository.getPersistentStateHolder(holderName, Long.class, String.class); myHolder.putIfAbsent(42L, "TheAnswer!"); stateRepository.close(); <START> try (FileInputStream fis = new FileInputStream(new File(directory, HOLDER_FILE_NAME))) { <END> try (ObjectInputStream ois = new ObjectInputStream(fis)) { String name = (String) ois.readObject(); assertThat(name, is(holderName)); FileBasedStateRepository.Tuple loadedTuple = (FileBasedStateRepository.Tuple) ois.readObject(); assertThat(loadedTuple.index, is(0)); @SuppressWarnings("unchecked") StateHolder<Long, String> stateHolder = (StateHolder<Long, String>) loadedTuple.holder; assertThat(stateHolder, is(myHolder)); } } }</code><technical_language>Collapse in</technical_language>

Target:
public void testHolderSave() throws Exception { File directory = folder.newFolder("testSave"); FileBasedStateRepository stateRepository = new FileBasedStateRepository(directory); String holderName = "myHolder"; StateHolder<Long, String> myHolder = stateRepository.getPersistentStateHolder(holderName, Long.class, String.class); myHolder.putIfAbsent(42L, "TheAnswer!"); stateRepository.close(); try (FileInputStream fis = new FileInputStream(new File(directory, HOLDER_FILE_NAME)); ObjectInputStream ois = new ObjectInputStream(fis)) { String name = (String) ois.readObject(); assertThat(name, is(holderName)); FileBasedStateRepository.Tuple loadedTuple = (FileBasedStateRepository.Tuple) ois.readObject(); assertThat(loadedTuple.index, is(0)); @SuppressWarnings("unchecked") StateHolder<Long, String> stateHolder = (StateHolder<Long, String>) loadedTuple.holder; assertThat(stateHolder, is(myHolder)); } }
Source:
<code>public MucClientManager(String[] features) { SmackConfiguration.setUnknownIqRequestReplyMode( SmackConfiguration.UnknownIqRequestReplyMode .replyFeatureNotImplemented); this.executor = ExecutorUtils.newScheduledThreadPool( <START> 3, true, MucClientManager.class.getSimpleName()); <END> if (features != null) { this.features.addAll(Arrays.asList(features)); } }</code><technical_language>this switch a fixed-size thread pool execute XMPP connect/login? This work number of MucClients is large</technical_language>

Target:
public MucClientManager(String[] features) { SmackConfiguration.setUnknownIqRequestReplyMode( SmackConfiguration.UnknownIqRequestReplyMode .replyFeatureNotImplemented); if (features != null) { this.features.addAll(Arrays.asList(features)); } }
Source:
<code>public void onClick(View v) { if (!NetworkUtil.isConnected(activity)) { callback.showErrorMessage(activity.getString(R.string.no_connectivity), <START> activity.getString(R.string.network_not_connected)); <END> } else { Task<Void> logout = new Task<Void>(activity) { @Override public Void call() { socialLogout(socialType); return null; } @Override public void onSuccess(Void result) { socialLogin(socialType); } @Override public void onException(Exception ex) { super.onException(ex); if (activity instanceof ICommonUI) ((ICommonUI) activity).tryToSetUIInteraction(true); } }; if (activity instanceof ICommonUI) ((ICommonUI) activity).tryToSetUIInteraction(false); logout.execute(); } }</code><technical_language>Do want show a dialog fly-in message social login failure</technical_language>

Target:
public void onClick(View v) { if (!NetworkUtil.isConnected(activity)) { callback.showErrorDialog(activity.getString(R.string.no_connectivity), activity.getString(R.string.network_not_connected)); } else { Task<Void> logout = new Task<Void>(activity) { @Override public Void call() { socialLogout(socialType); return null; } @Override public void onSuccess(Void result) { socialLogin(socialType); } @Override public void onException(Exception ex) { super.onException(ex); if (activity instanceof ICommonUI) ((ICommonUI) activity).tryToSetUIInteraction(true); } }; if (activity instanceof ICommonUI) ((ICommonUI) activity).tryToSetUIInteraction(false); logout.execute(); } }
Source:
<code>public void setup() throws NoSuchFieldException, IllegalAccessException { <START> instanceCountField = OpenHelperManager.class.getDeclaredField("instanceCount"); <END> instanceCountField.setAccessible(true); instanceCount = instanceCountField.getInt(null); activity = Robolectric.buildActivity(OrmLiteActivity_.class).create().get(); }</code><technical_language>need for this. tests independent, instance count zero</technical_language>

Target:
public void setup() { activity = Robolectric.buildActivity(OrmLiteActivity_.class).create().get(); }
Source:
<code>public CDNContainer apply(final HttpResponse from) { String uri = checkNotNull(from.getFirstHeaderOrNull(CDN_URI), CDN_URI); String sslUri = checkNotNull(from.getFirstHeaderOrNull(CDN_SSL_URI), CDN_SSL_URI); String streamingUri = checkNotNull(from.getFirstHeaderOrNull(CDN_STREAMING_URI), CDN_STREAMING_URI); String iosUri = checkNotNull(from.getFirstHeaderOrNull(CDN_IOS_URI), CDN_IOS_URI); <START> if (uri == null) { <END> return null; } else { String enabled = checkNotNull(from.getFirstHeaderOrNull(CDN_ENABLED), CDN_ENABLED); String logRetention = checkNotNull(from.getFirstHeaderOrNull(CDN_LOG_RETENTION), CDN_LOG_RETENTION); String ttl = checkNotNull(from.getFirstHeaderOrNull(CDN_TTL), CDN_TTL); List<String> parts = newArrayList(Splitter.on('/').split(request.getEndpoint().getPath())); return CDNContainer.builder().name(parts.get(parts.size() - 1)) .enabled(Boolean.parseBoolean(enabled)) .logRetention(Boolean.parseBoolean(logRetention)) .ttl(Integer.parseInt(ttl)) .uri(URI.create(uri)) .sslUri(URI.create(sslUri)) .streamingUri(URI.create(streamingUri)) .iosUri(URI.create(iosUri)) .build(); } }</code><technical_language>this point uri null</technical_language>

Target:
public CDNContainer apply(final HttpResponse from) { String uri = checkNotNull(from.getFirstHeaderOrNull(CDN_URI), CDN_URI); String sslUri = checkNotNull(from.getFirstHeaderOrNull(CDN_SSL_URI), CDN_SSL_URI); String streamingUri = checkNotNull(from.getFirstHeaderOrNull(CDN_STREAMING_URI), CDN_STREAMING_URI); String iosUri = checkNotNull(from.getFirstHeaderOrNull(CDN_IOS_URI), CDN_IOS_URI); String enabled = checkNotNull(from.getFirstHeaderOrNull(CDN_ENABLED), CDN_ENABLED); String logRetention = checkNotNull(from.getFirstHeaderOrNull(CDN_LOG_RETENTION), CDN_LOG_RETENTION); String ttl = checkNotNull(from.getFirstHeaderOrNull(CDN_TTL), CDN_TTL); List<String> parts = newArrayList(Splitter.on('/').split(request.getEndpoint().getPath())); checkArgument(parts.size() > 0); return CDNContainer.builder().name(parts.get(parts.size() - 1)) .enabled(Boolean.parseBoolean(enabled)) .logRetention(Boolean.parseBoolean(logRetention)) .ttl(Integer.parseInt(ttl)) .uri(URI.create(uri)) .sslUri(URI.create(sslUri)) .streamingUri(URI.create(streamingUri)) .iosUri(URI.create(iosUri)) .build(); }
Source:
<code>public boolean close() { if (recordManager != null) { try { logger.info("Closing Record Manager"); recordManager.close(); recordManager = null; } catch (IOException e) { logger.warn("Error when closing Record Manager", e); } } <START> return true; <END> }</code><technical_language>do need return if is true</technical_language>

Target:
public void close() { if (recordManager != null) { try { logger.info("Closing Record Manager"); recordManager.close(); recordManager = null; } catch (IOException e) { logger.warn("Error when closing Record Manager", e); } } }
Source:
<code>private void service() throws IOException, Failure { project = projectControl.getProjectState().getProject(); try { repo = repoManager.openRepository(project.getNameKey()); } catch (RepositoryNotFoundException e) { <START> final String name = project.getName(); <END> throw new Failure(1, "fatal: '" + name + "': not a git archive", e); } try { runImpl(); } finally { repo.close(); } }</code><technical_language>name is in next statement, inlined</technical_language>

Target:
private void service() throws IOException, Failure { project = projectControl.getProjectState().getProject(); try { repo = repoManager.openRepository(project.getNameKey()); } catch (RepositoryNotFoundException e) { throw new Failure(1, "fatal: '" + project.getName() + "': not a git archive", e); } try { runImpl(); } finally { repo.close(); } }
Source:
<code><START> public InitialisingTransactionManager( <END> AtlasDbConfig config, java.util.function.Supplier<java.util.Optional<AtlasDbRuntimeConfig>> runtimeConfigSupplier, Set<Schema> schemas, TransactionManagers.Environment env, LockServerOptions lockServerOptions, boolean allowHiddenTableAccess, String userAgent) { atlasFactory = new ServiceDiscoveringAtlasSupplier(config); this.config = config; this.runtimeConfigSupplier = runtimeConfigSupplier; this.schemas = schemas; this.env = env; this.lockServerOptions = lockServerOptions; this.allowHiddenTableAccess = allowHiddenTableAccess; this.userAgent = userAgent; LockRequest.setDefaultLockTimeout( SimpleTimeDuration.of(config.getDefaultLockTimeoutSeconds(), TimeUnit.SECONDS)); registerEndpoints(); try { initialise(); } catch (Throwable th) { log.error("Synchronous initialisation failed, initialisation will be done asynchronously", th); initialiseAsync(); } }</code><technical_language>want a status property this class, users check initialized</technical_language>

Target:
public InitialisingTransactionManager( AtlasDbConfig config, java.util.function.Supplier<java.util.Optional<AtlasDbRuntimeConfig>> runtimeConfigSupplier, Set<Schema> schemas, TransactionManagers.Environment env, LockServerOptions lockServerOptions, boolean allowHiddenTableAccess, String userAgent) { atlasFactory = new ServiceDiscoveringAtlasSupplier(config); this.config = config; this.runtimeConfigSupplier = runtimeConfigSupplier; this.schemas = schemas; this.env = env; this.lockServerOptions = lockServerOptions; this.allowHiddenTableAccess = allowHiddenTableAccess; this.userAgent = userAgent; LockRequest.setDefaultLockTimeout( SimpleTimeDuration.of(config.getDefaultLockTimeoutSeconds(), TimeUnit.SECONDS)); registerEndpoints(); try { initialise(); } catch (Throwable th) { log.info("Synchronous initialisation failed, initialisation will be done asynchronously", th); initialiseAsync(); } }
Source:
<code>private void addProjectToProjectVersions( final DatabaseTransOperator transOperator, final int projectId, final int version, final File localFile, final File startupDependencies, final String uploader, final byte[] md5, final String resourceId) throws ProjectManagerException { final long updateTime = System.currentTimeMillis(); final String INSERT_PROJECT_VERSION = "INSERT INTO project_versions " <START> + "(project_id, version, upload_time, uploader, file_type, file_name, md5, num_chunks, resource_id, startup_dependencies) values " <END> + "(?,?,?,?,?,?,?,?,?,?)"; try { String lowercaseFileExtension = FilenameUtils.getExtension(localFile.getName()).toLowerCase(); InputStream startupDependenciesStream = getStartupDependenciesInputStream(startupDependencies); transOperator.update(INSERT_PROJECT_VERSION, projectId, version, updateTime, uploader, lowercaseFileExtension, localFile.getName(), md5, 0, resourceId, startupDependenciesStream); } catch (final SQLException e) { final String msg = String .format("Error initializing project id: %d version: %d ", projectId, version); logger.error(msg, e); throw new ProjectManagerException(msg, e); } }</code><technical_language>reformat wrap properly resource_id put rest in next line</technical_language>

Target:
private void addProjectToProjectVersions( final DatabaseTransOperator transOperator, final int projectId, final int version, final File localFile, final File startupDependencies, final String uploader, final byte[] md5, final String resourceId) throws ProjectManagerException { final long updateTime = System.currentTimeMillis(); final String INSERT_PROJECT_VERSION = "INSERT INTO project_versions " + "(project_id, version, upload_time, uploader, file_type, file_name, md5, num_chunks, resource_id, " + "startup_dependencies) values (?,?,?,?,?,?,?,?,?,?)"; try { String lowercaseFileExtension = FilenameUtils.getExtension(localFile.getName()).toLowerCase(); InputStream startupDependenciesStream = getStartupDependenciesInputStream(startupDependencies); transOperator.update(INSERT_PROJECT_VERSION, projectId, version, updateTime, uploader, lowercaseFileExtension, localFile.getName(), md5, 0, resourceId, startupDependenciesStream); } catch (final SQLException e) { final String msg = String .format("Error initializing project id: %d version: %d ", projectId, version); logger.error(msg, e); throw new ProjectManagerException(msg, e); } }
Source:
<code>public static ConsumeOrder getConsumeOrder(String consumeOrderStr) { <START> for (ConsumeOrder consumeOrder : ConsumeOrder.values()) { <END> if (consumeOrder.order.equals(consumeOrderStr)) { return consumeOrder; } } return null; }</code><technical_language>ConsumeOrder.values() -> values()</technical_language>

Target:
public static ConsumeOrder getConsumeOrder(String consumeOrderStr) { for (ConsumeOrder consumeOrder : values()) { if (consumeOrder.order.equalsIgnoreCase(consumeOrderStr)) { return consumeOrder; } } throw new IllegalArgumentException( "Illegal value: " + consumeOrderStr + ", only " + Arrays.toString(values()) + " are supported."); }
Source:
<code>private void geoCodeTypedAddress(final String address) { mPoiGeocodeParameters.setPreferredSearchLocation(mPreferredSearchLocation); mPoiGeocodeParameters.setSearchArea(mPreferredSearchLocation); mLocatorTask.addDoneLoadingListener(new Runnable() { @Override public void run() { if (mLocatorTask.getLoadStatus() == LoadStatus.LOADED) { final ListenableFuture<List<GeocodeResult>> geocodeResultListenableFuture = mLocatorTask <START> .geocodeAsync(address, mPoiGeocodeParameters); <END> geocodeResultListenableFuture.addDoneListener(new Runnable() { @Override public void run() { try { List<GeocodeResult> geocodeResults = geocodeResultListenableFuture.get(); if (geocodeResults.size() > 0) { displaySearchResult(geocodeResults); } else { Toast.makeText(getApplicationContext(), getString(R.string.location_not_found) + address, Toast.LENGTH_LONG).show(); } } catch (InterruptedException | ExecutionException e) { Log.e(TAG, "Geocode error: " + e.getMessage()); Toast.makeText(getApplicationContext(), getString(R.string.geo_locate_error), Toast.LENGTH_LONG).show(); } } }); } else { Log.i(TAG, "Trying to reload locator task"); mLocatorTask.retryLoadAsync(); } } }); mLocatorTask.loadAsync(); }</code><technical_language>Need check parameters valid and/or address null</technical_language>

Target:
private void geoCodeTypedAddress(final String address) { if (address != null) { mPoiGeocodeParameters.setPreferredSearchLocation(mPreferredSearchProximity); mPoiGeocodeParameters.setSearchArea(mPreferredSearchProximity); mLocatorTask.addDoneLoadingListener(new Runnable() { @Override public void run() { if (mLocatorTask.getLoadStatus() == LoadStatus.LOADED) { final ListenableFuture<List<GeocodeResult>> geocodeResultListenableFuture = mLocatorTask .geocodeAsync(address, mPoiGeocodeParameters); geocodeResultListenableFuture.addDoneListener(new Runnable() { @Override public void run() { try { List<GeocodeResult> geocodeResults = geocodeResultListenableFuture.get(); if (geocodeResults.size() > 0) { displaySearchResult(geocodeResults); } else { Toast.makeText(getApplicationContext(), getString(R.string.location_not_found) + address, Toast.LENGTH_LONG).show(); } } catch (InterruptedException | ExecutionException e) { Log.e(TAG, "Geocode error: " + e.getMessage()); Toast.makeText(getApplicationContext(), getString(R.string.geo_locate_error), Toast.LENGTH_LONG) .show(); } } }); } else { Log.i(TAG, "Trying to reload locator task"); mLocatorTask.retryLoadAsync(); } } }); mLocatorTask.loadAsync(); } }
Source:
<code>public void testCheckThreadLocalLeaks() throws Exception { final ConfigurationBuilder builder = new ConfigurationBuilder(); builder .memory().size(4096) .locking().concurrencyLevel(2048) <START> .persistence().passivation(false) <END> .addSingleFileStore().location(tmpDirectory).shared(false).preload(true); Future<Map<String, Map<ThreadLocal<?>, Object>>> result = fork(() -> { TestResourceTracker.testThreadStarted(ThreadLocalLeakTest.this.getTestName()); Thread forkedThread = doStuffWithCache(builder); beforeGC(); System.gc(); Thread.sleep(500); System.gc(); afterGC(); List<Thread> threadSet = Arrays.asList(Thread.currentThread(), forkedThread); Map<String, Map<ThreadLocal<?>, Object>> allThreadLocals = new HashMap<>(); for (Thread thread : threadSet) { Map<ThreadLocal<?>, Object> threadLocalLeaks = findThreadLocalLeaks(thread); if (threadLocalLeaks != null && !threadLocalLeaks.isEmpty()) allThreadLocals.put(thread.getName(), threadLocalLeaks); } return allThreadLocals; }); Map<String, Map<ThreadLocal<?>, Object>> allThreadLocals = result.get(30, TimeUnit.SECONDS); if (!allThreadLocals.isEmpty()) throw new IllegalStateException("Thread locals still present: " + allThreadLocals); }</code><technical_language>global configuration is defined, I enable global state call globalBuilder.globalState().persistentLocation(tmpDirectory)</technical_language>

Target:
public void testCheckThreadLocalLeaks() throws Exception { final ConfigurationBuilder builder = new ConfigurationBuilder(); builder .memory().size(4096) .locking().concurrencyLevel(2048) .persistence().passivation(false) .addSingleFileStore().shared(false).preload(true); Future<Map<String, Map<ThreadLocal<?>, Object>>> result = fork(() -> { TestResourceTracker.testThreadStarted(ThreadLocalLeakTest.this.getTestName()); Thread forkedThread = doStuffWithCache(builder); beforeGC(); System.gc(); Thread.sleep(500); System.gc(); afterGC(); List<Thread> threadSet = Arrays.asList(Thread.currentThread(), forkedThread); Map<String, Map<ThreadLocal<?>, Object>> allThreadLocals = new HashMap<>(); for (Thread thread : threadSet) { Map<ThreadLocal<?>, Object> threadLocalLeaks = findThreadLocalLeaks(thread); if (threadLocalLeaks != null && !threadLocalLeaks.isEmpty()) allThreadLocals.put(thread.getName(), threadLocalLeaks); } return allThreadLocals; }); Map<String, Map<ThreadLocal<?>, Object>> allThreadLocals = result.get(30, TimeUnit.SECONDS); if (!allThreadLocals.isEmpty()) throw new IllegalStateException("Thread locals still present: " + allThreadLocals); }
Source:
<code>public String toPath() { <START> if (getBuild() == "") <END> { return String.format("%s-%s-%s-%s-%s", getId(), getVersion(), getLanguageImplementationVersion(), getAbi(), getPlatform()) + ".whl"; } return String.format("%s-%s-%s-%s-%s-%s", getId(), getVersion(), getBuild(), getLanguageImplementationVersion(), getAbi(), getPlatform()) + ".whl"; }</code><technical_language>Please, StringUtils.isBlank() instead</technical_language>

Target:
public String toPath() { if (StringUtils.isBlank(getBuild())) { return String.format("%s-%s-%s-%s-%s", getId(), getVersion(), getLanguageImplementationVersion(), getAbi(), getPlatform()) + ".whl"; } return String.format("%s-%s-%s-%s-%s-%s", getId(), getVersion(), getBuild(), getLanguageImplementationVersion(), getAbi(), getPlatform()) + ".whl"; }
Source:
<code>public void rebind() { Transition expectedState = getAttribute(SERVICE_STATE_EXPECTED); if (expectedState == null || expectedState.getState() != Lifecycle.RUNNING) { <START> log.warn("On rebind of {}, not calling software process rebind hooks because state is {}", this, expectedState); <END> return; } Lifecycle actualState = getAttribute(SERVICE_STATE_ACTUAL); if (actualState == null || actualState != Lifecycle.RUNNING) { log.warn("Rebinding entity {}, even though actual state is {}. Expected state is {}", new Object[] {this, actualState, expectedState}); } log.info("Rebind connecting to pre-running service", this); MachineLocation machine = getMachineOrNull(); if (machine != null) { initDriver(machine); driver.rebind(); if (log.isDebugEnabled()) log.debug("On rebind of {}, re-created driver {}", this, driver); } else { log.info("On rebind of {}, no MachineLocation found (with locations {}) so not generating driver", this, getLocations()); } callRebindHooks(); }</code><technical_language>Minor possibly worthwhile: clarify state referenced is expectedState, actualState</technical_language>

Target:
public void rebind() { Transition expectedState = getAttribute(SERVICE_STATE_EXPECTED); if (expectedState == null || expectedState.getState() != Lifecycle.RUNNING) { log.warn("On rebind of {}, not calling software process rebind hooks because expected state is {}", this, expectedState); return; } Lifecycle actualState = getAttribute(SERVICE_STATE_ACTUAL); if (actualState == null || actualState != Lifecycle.RUNNING) { log.warn("Rebinding entity {}, even though actual state is {}. Expected state is {}", new Object[] {this, actualState, expectedState}); } log.info("Rebind connecting to pre-running service", this); MachineLocation machine = getMachineOrNull(); if (machine != null) { initDriver(machine); driver.rebind(); if (log.isDebugEnabled()) log.debug("On rebind of {}, re-created driver {}", this, driver); } else { log.info("On rebind of {}, no MachineLocation found (with locations {}) so not generating driver", this, getLocations()); } callRebindHooks(); }
Source:
<code>public void creating_a_qg_with_a_name_used_in_another_organization_should_work() { <START> OrganizationDto org1 = db.organizations().insert(); <END> OrganizationDto org2 = db.organizations().insert(); userSession.logIn() .addPermission(ADMINISTER_QUALITY_GATES, org1) .addPermission(ADMINISTER_QUALITY_GATES, org2); executeRequest(Optional.of(org1), "Default"); executeRequest(Optional.of(org2), "Default"); }</code><technical_language>This test is clear => 2 execution of web service, implying permission 2 organizations. I expect : 1. Create organization1, create a quality gate 2. Create organization2 3. Execute request create a quality gate in organization2, name of quality gate created in organization1</technical_language>

Target:
public void creating_a_qg_with_a_name_used_in_another_organization_should_work() { OrganizationDto anOrganization = db.organizations().insert(); QGateWithOrgDto qualityGate = db.qualityGates().insertQualityGate(anOrganization); OrganizationDto anotherOrganization = db.organizations().insert(); userSession.addPermission(ADMINISTER_QUALITY_GATES, anotherOrganization); CreateResponse response = ws.newRequest() .setParam(PARAM_NAME, qualityGate.getName()) .setParam(PARAM_ORGANIZATION, anotherOrganization.getKey()) .executeProtobuf(CreateResponse.class); assertThat(response.getName()).isEqualTo(qualityGate.getName()); assertThat(response.getId()).isNotEqualTo(qualityGate.getId()); }
Source:
<code>public void visitNode(Tree tree) { <START> if (!hasSemantic()) { <END> return; } MethodInvocationTree mit = (MethodInvocationTree) tree; if (ASSERT_NULLABLE_FIRST_ARGUMENT.matches(mit)) { checkNullableAssertion(new Argument(mit, 0)); } else if (ASSERT_NULLABLE_SECOND_ARGUMENT.matches(mit)) { checkNullableAssertion(new Argument(mit, 1)); } else if (ASSERT_EQUALS_SECOND_AND_FIRST_ARGUMENTS.matches(mit)) { checkCompatibleTypes(new Argument(mit, 1), new Argument(mit, 0), Option.ACCEPT_DISSIMILAR_INTERFACE); } else if (ASSERT_EQUALS_THIRD_AND_SECOND_ARGUMENTS.matches(mit)) { checkCompatibleTypes(new Argument(mit, 2), new Argument(mit, 1), Option.ACCEPT_DISSIMILAR_INTERFACE); } else if (ASSERT_NOT_EQUALS_SECOND_AND_FIRST_ARGUMENTS.matches(mit)) { checkCompatibleTypes(new Argument(mit, 1), new Argument(mit, 0), Option.REJECT_DISSIMILAR_INTERFACE); } else if (ASSERT_NOT_EQUALS_THIRD_AND_SECOND_ARGUMENTS.matches(mit)) { checkCompatibleTypes(new Argument(mit, 2), new Argument(mit, 1), Option.REJECT_DISSIMILAR_INTERFACE); } else if (ASSERTJ_ASSERT_THAT.matches(mit)) { checkSubsequentAssertJPredicateCompatibleTypes(new Argument(mit, 0), mit); } }</code><technical_language>is need for this check anymore. remove related test</technical_language>

Target:
public void visitNode(Tree tree) { MethodInvocationTree mit = (MethodInvocationTree) tree; if (ASSERT_NULLABLE_FIRST_ARGUMENT.matches(mit)) { checkNullableAssertion(new Argument(mit, 0)); } else if (ASSERT_NULLABLE_SECOND_ARGUMENT.matches(mit)) { checkNullableAssertion(new Argument(mit, 1)); } else if (ASSERT_EQUALS_FIRST_AND_SECOND_ARGUMENTS.matches(mit)) { checkCompatibleTypes(new Argument(mit, 1), new Argument(mit, 0), Option.ACCEPT_DISSIMILAR_INTERFACE); } else if (ASSERT_EQUALS_SECOND_AND_THIRD_ARGUMENTS.matches(mit)) { checkCompatibleTypes(new Argument(mit, 2), new Argument(mit, 1), Option.ACCEPT_DISSIMILAR_INTERFACE); } else if (ASSERT_NOT_EQUALS_FIRST_AND_SECOND_ARGUMENTS.matches(mit)) { checkCompatibleTypes(new Argument(mit, 1), new Argument(mit, 0), Option.REJECT_DISSIMILAR_INTERFACE); } else if (ASSERT_NOT_EQUALS_SECOND_AND_THIRD_ARGUMENTS.matches(mit)) { checkCompatibleTypes(new Argument(mit, 2), new Argument(mit, 1), Option.REJECT_DISSIMILAR_INTERFACE); } else if (ASSERTJ_ASSERT_THAT.matches(mit)) { checkSubsequentAssertJPredicateCompatibleTypes(new Argument(mit, 0), mit); } }
Source:
<code><START> public int getNumSplits(@Nullable SplitHintSpec splitHintSpec) throws IOException <END> { return 0; }</code><technical_language>remove throws IOException</technical_language>

Target:
public int getNumSplits(@Nullable SplitHintSpec splitHintSpec) { throw new UnsupportedOperationException(); }
Source:
<code>public SingleImageProxyBundle(@NonNull ImageProxy imageProxy) { ImageInfo imageInfo = imageProxy.getImageInfo(); if (imageInfo == null) { throw new IllegalArgumentException("ImageProxy has no associated ImageInfo"); } Object tag = <START> imageInfo.getTag(); <END> if (tag == null) { throw new IllegalArgumentException("ImageProxy has no associated tag"); } if (tag instanceof SessionConfigTagMap) { mCaptureId = (Integer) ((SessionConfigTagMap) tag).getTag(PREVIEW_KEY_FOR_TAG_MAP); mImageProxy = imageProxy; } else if (tag instanceof Integer) { mCaptureId = (Integer) tag; mImageProxy = imageProxy; } else { throw new IllegalArgumentException("ImageProxy has tag that isn't an integer or " + "SessionConfigTagMap"); } }</code><technical_language>please try add API getTag(String key) imageInfo</technical_language>

Target:
public SingleImageProxyBundle(@NonNull ImageProxy imageProxy) { ImageInfo imageInfo = imageProxy.getImageInfo(); if (imageInfo == null) { throw new IllegalArgumentException("ImageProxy has no associated ImageInfo"); } Object tag = imageInfo.getTag("CaptureStageId"); if (tag == null) { throw new IllegalArgumentException("ImageProxy has no associated tag"); } if (!(tag instanceof Integer)) { throw new IllegalArgumentException("ImageProxy has tag that isn't an integer"); } mCaptureId = (Integer) tag; mImageProxy = imageProxy; }
Source:
<code>public Map<String, Object> convertJobGrabToText(@RequestBody Graph graph) { <START> Map<String, Object> response = new HashMap<String, Object>(); <END> try { String dslText = graph.toDSLText(); response.put("text", dslText); } catch (JobSpecificationException jse) { response.put("error", jse.toExceptionDescriptor()); } catch (Throwable e) { response.put("error", e.toString()); } return response; }</code><technical_language>For consistence statement higher up, use: new HashMap<>();</technical_language>

Target:
public Map<String, Object> convertJobGrabToText(@RequestBody Graph graph) { Map<String, Object> response = new HashMap<>(); try { String dslText = graph.toDSLText(); response.put("text", dslText); } catch (JobSpecificationException jse) { response.put("error", jse.toExceptionDescriptor()); } catch (Throwable e) { response.put("error", e.toString()); } return response; }
Source:
<code>protected void setNavMenuItems() { navMenu = new NavDrawerItem[] { NavMenuItem.create(SWITCH_MODE, getResources().getString(R.string.switch_to_vendor), "ic_action_vendor_mode", false, this), <START> NavMenuItem.create(LOGOUT, getResources().getString(R.string.logout), "ic_logout", false, this) <END> }; }</code><technical_language>lol logout button... ;) I appreciate effort though! a free one: <LINK_1> you'll, of course, need pass asset studio set color white: <LINK_0></technical_language>

Target:
protected void setNavMenuItems() { navMenu = new NavDrawerItem[] { NavMenuItem.create(SWITCH_MODE, getResources().getString(R.string.switch_to_vendor), "ic_action_vendor_mode", false, this), LogoutMenuItem.create(this) }; }
Source:
<code>public SpongeMapDecorationType(MapDecoration.Type mapDecorationType, String id, String name) { <START> type = mapDecorationType; <END> this.id = id; this.name = name; }</code><technical_language>this.type</technical_language>

Target:
public SpongeMapDecorationType(MapDecoration.Type mapDecorationType, String id, String name) { this.type = mapDecorationType; this.id = id; this.name = name; }
Source:
<code>private void updateConfButton(FormStatus form, ExportConfigurationButton button) { <START> button.setStatus(forms.hasConfiguration(form)); <END> }</code><technical_language>I button.setStatus() is kinda unexpected meaning of "status" in a conf button is in a details button. I name for classes extend ButtonProcessing, this is a requirement, subclasses (DetailStatusButton ExportConfigurationButton) instead of interface, Polymorphism (which is totally fine here, way). This is telling setStatus method is part of ButtonProcessing interface. suggest remove interface chance give a more specific name in ExportConfigurationButton e.g. setConfigured</technical_language>

Target:
private void updateConfButton(FormStatus form, ExportConfigurationButton button) { button.setConfigured(forms.hasConfiguration(form)); }
Source:
<code>public PackingPlan repack(PackingPlan currentPackingPlan, Map<String, Integer> componentChanges) throws PackingException { int initialNumContainer = TopologyUtils.getNumContainers(topology); int initialNumInstance = TopologyUtils.getTotalInstance(topology); <START> double initialNumInstancePerContainer = (double) initialNumInstance / initialNumContainer; <END> Map<String, Integer> currentComponentParallelism = currentPackingPlan.getComponentCounts(); Map<String, Integer> newComponentParallelism = new HashMap<>(); int newNumInstance = 0; for (Map.Entry<String, Integer> e : currentComponentParallelism.entrySet()) { String componentName = e.getKey(); Integer count = e.getValue(); if (componentChanges.containsKey(componentName)) { count += componentChanges.get(componentName); } newComponentParallelism.put(componentName, count); newNumInstance += count; } int newNumContainer = (int) Math.ceil(newNumInstance / initialNumInstancePerContainer); return packInternal(newNumContainer, newComponentParallelism); }</code><technical_language>This implementation ratio of #(instances)/#(containers) re-scaling. issue is: re-scale, update # of instances in topology def, # of containers updated. # of containers fetched TopologyUtils.getNumContainers(topology) is accurate. if continues scaling-up a topology, end up: **increasing # of instances in single container boundlessly**. thought is # of instances containers based currentPackingPlan. This reflect correct values. some issues: try ratio of #(instances)/#(containers) currentPackingPlan, original one. time ceil # of containers, # of containers integer. times of scale-up, lead to: **The # of instances in container decreases eventually instance container.** ideal case is ratio of #(instances)/#(containers) **original** ratio. current state updating is kind of messy, I is a simple get it. thought is insert this original ratio a config submission</technical_language>

Target:
public PackingPlan repack(PackingPlan currentPackingPlan, Map<String, Integer> componentChanges) throws PackingException { int initialNumContainer = TopologyUtils.getNumContainers(topology); int initialNumInstance = TopologyUtils.getTotalInstance(topology); double initialNumInstancePerContainer = (double) initialNumInstance / initialNumContainer; Map<String, Integer> currentComponentParallelism = currentPackingPlan.getComponentCounts(); for (Map.Entry<String, Integer> e : componentChanges.entrySet()) { currentComponentParallelism.put(e.getKey(), e.getValue()); } int newNumInstance = TopologyUtils.getTotalInstance(currentComponentParallelism); int newNumContainer = (int) Math.ceil(newNumInstance / initialNumInstancePerContainer); return packInternal(newNumContainer, currentComponentParallelism); }