auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void start() throws Exception { synchronized (lock) { if (childrenCache != null) { return; } childrenCache = cacheFactory.make(curatorFramework, config.getContainerPath()); } ContainerCacheListener containerCacheListener = new ContainerCacheListener(); childrenCache.getListenable().addListener(containerCacheListener); try { childrenCache.start(PathChildrenCache.StartMode.POST_INITIALIZED_EVENT); } catch (Exception e) { synchronized (lock) { try { stop(); } catch (IOException e1) { log.error(e1, "Exception when stopping InventoryManager that couldn't start."); } } throw e; } <START> while (!containerCacheListener.doneInitializing) { <END> Thread.sleep(2000); log.info("Waiting for PathChildrenCache to be completely loaded."); } }</code><technical_language>a CountDownLatch.await(1 minute) instead? logs printed wait more necessary</technical_language>

Target:
public void start() throws Exception { synchronized (lock) { if (childrenCache != null) { return; } childrenCache = cacheFactory.make(curatorFramework, config.getContainerPath()); } ContainerCacheListener containerCacheListener = new ContainerCacheListener(); childrenCache.getListenable().addListener(containerCacheListener); try { childrenCache.start(PathChildrenCache.StartMode.POST_INITIALIZED_EVENT); } catch (Exception e) { synchronized (lock) { try { stop(); } catch (IOException e1) { log.error(e1, "Exception when stopping InventoryManager that couldn't start."); } } throw e; } while (!latch.await(1, TimeUnit.MINUTES)) { log.info("Waiting for PathChildrenCache to be completely loaded."); } log.info("PathChildrenCache has been loaded."); }
Source:
<code>public void testDoubletonFlatbush() { <START> List<Rectangle> items = new ArrayList<>(); <END> Rectangle rect0 = new Rectangle(1, 1, 1, 1); items.add(rect0); Rectangle rect1 = new Rectangle(-1, -2, -1, -1); items.add(rect1); items.sort(RECTANGLE_COMPARATOR); Flatbush<Rectangle> rtree = new Flatbush<>(items.toArray(new Rectangle[] {})); List<Rectangle> allResults = findIntersections(rtree, EVERYTHING); allResults.sort(RECTANGLE_COMPARATOR); assertEquals(allResults, items); Rectangle hit0 = new Rectangle(1, 1, 2, 2); assertEquals(findIntersections(rtree, hit0), ImmutableList.of(rect0)); Rectangle hit1 = new Rectangle(-2, -2, -1, -2); assertEquals(findIntersections(rtree, hit1), ImmutableList.of(rect1)); Rectangle totalMiss = new Rectangle(10, 10, 12, 12); assertEquals(findIntersections(rtree, totalMiss), ImmutableList.of()); Rectangle marginalMiss = new Rectangle(0, 0, 0, 0); assertEquals(findIntersections(rtree, marginalMiss), ImmutableList.of()); }</code><technical_language>ImmutableList.of() assertEqualsNoOrder Rectangle rect0 = new Rectangle(1, 1, 1, 1); Rectangle rect1 = new Rectangle(-1, -2, -1, -1); List<Rectangle> items = ImmutableList.of(rect0, rect1); Flatbush<Rectangle> rtree = new Flatbush<>(items.toArray(new Rectangle[] {})); List<Rectangle> allResults = findIntersections(rtree, EVERYTHING); assertEqualsNoOrder(allResults.toArray(), items.toArray()); ditto testTwoLevelFlatbush</technical_language>

Target:
public void testDoubletonFlatbush() { Rectangle rect0 = new Rectangle(1, 1, 1, 1); Rectangle rect1 = new Rectangle(-1, -2, -1, -1); List<Rectangle> items = ImmutableList.of(rect0, rect1); Flatbush<Rectangle> rtree = new Flatbush<>(items.toArray(new Rectangle[] {})); List<Rectangle> allResults = findIntersections(rtree, EVERYTHING); assertEqualsSorted(allResults, items, RECTANGLE_COMPARATOR); assertEquals(findIntersections(rtree, new Rectangle(1, 1, 2, 2)), ImmutableList.of(rect0)); assertEquals(findIntersections(rtree, new Rectangle(-2, -2, -1, -2)), ImmutableList.of(rect1)); assertEquals(findIntersections(rtree, new Rectangle(10, 10, 12, 12)), ImmutableList.of()); assertEquals(findIntersections(rtree, new Rectangle(0, 0, 0, 0)), ImmutableList.of()); }
Source:
<code>public void onDeniedPendingLockNotification() { synchronized (ZKDistributedNonblockingLock.this) { <START> _isLocked = false; <END> _isPreempted = true; _isPending = false; ZKDistributedNonblockingLock.this.notify(); } }</code><technical_language>a lock in state a time. I suggest merging 2 booleans enum for cleanness of code logic</technical_language>

Target:
public void onDeniedPendingLockNotification() { _lockStatus = LockConstants.LockStatus.PREEMPTED; _countDownLatch.countDown(); }
Source:
<code>public void generateExperimentalCoordinates(Vector2d firstBondVector) throws CDKException { IMolecule original = molecule; IMolecule shallowCopy = molecule.getBuilder().newInstance(IMolecule.class,molecule); for (IAtom curAtom : shallowCopy.atoms()) { if (curAtom.getSymbol().equals("H")) { int bondsFromCurAtom=0; for (IBond bond : shallowCopy.bonds()) if(bond.contains (curAtom)) ++bondsFromCurAtom; <START> if (bondsFromCurAtom < 2) { <END> shallowCopy.removeAtomAndConnectedElectronContainers(curAtom); curAtom.setPoint2d(null); } } } molecule = shallowCopy; generateCoordinates(firstBondVector); double bondLength = GeometryTools.getBondLengthAverage(molecule); HydrogenPlacer hPlacer = new HydrogenPlacer(); molecule = original; hPlacer.placeHydrogens2D(molecule, bondLength); }</code><technical_language>IAtomContainer.getConnectedBondsCount()? IAtomContainer.getConnectedAtomsCount()? <LINK_0></technical_language>

Target:
public void generateExperimentalCoordinates(Vector2d firstBondVector) throws CDKException { IMolecule original = molecule; IMolecule shallowCopy = molecule.getBuilder().newInstance(IMolecule.class,molecule); Map<IAtom,Integer> single_h = new HashMap<IAtom,Integer>(); for (IBond curBond : shallowCopy.bonds()) { boolean first = curBond.getAtom(0).getSymbol().equals("H"); boolean second = curBond.getAtom(1).getSymbol().equals("H"); if (first && !second) single_h.put(curBond.getAtom(0), 0); if (!first && second) single_h.put(curBond.getAtom(1), 0); } for (IAtom curAtom : single_h.keySet()) { if (shallowCopy.getConnectedBondsCount(curAtom) == 1) { shallowCopy.removeAtomAndConnectedElectronContainers(curAtom); } } molecule = shallowCopy; generateCoordinates(firstBondVector); double bondLength = GeometryTools.getBondLengthAverage(molecule); HydrogenPlacer hPlacer = new HydrogenPlacer(); molecule = original; hPlacer.placeHydrogens2D(molecule, bondLength); }
Source:
<code>public void visitNode(Tree tree) { if (tree.is(Kind.METHOD) && isServletInit((MethodTree) tree)) { tree.accept(new AssignmentVisitor()); } else if (tree.is(Kind.VARIABLE)) { VariableTree variable = (VariableTree) tree; <START> if (hasSemantic() && isOwnedByAServlet(variable) && !isStaticOrFinal(variable)) { <END> issuableVariables.add(variable); } } }</code><technical_language>checking for semantic done checking type of tree, semantic is get parameter type of method</technical_language>

Target:
public void visitNode(Tree tree) { if (tree.is(Kind.METHOD) && isServletInit((MethodTree) tree)) { tree.accept(new AssignmentVisitor()); } else if (tree.is(Kind.VARIABLE)) { VariableTree variable = (VariableTree) tree; if (isOwnedByAServlet(variable) && !isStaticOrFinal(variable)) { issuableVariables.add(variable); } } }
Source:
<code>public void shouldNotExpireChargesWhenAwaitingCaptureDelayIsLessThan48Hours() { <START> String extChargeId1 = addCharge(CREATED, "ref", ZonedDateTime.now().minusMinutes(90), RandomIdGenerator.newId()); <END> String extChargeId2 = addCharge(AWAITING_CAPTURE_REQUEST, "ref", ZonedDateTime.now().minusHours(48L).plusMinutes(1L), RandomIdGenerator.newId()); worldpayMockClient.mockCancelSuccess(); connectorRestApiClient .postChargeExpiryTask() .statusCode(OK.getStatusCode()) .contentType(JSON) .body("expiry-success", is(1)) .body("expiry-failed", is(0)); connectorRestApiClient .withAccountId(accountId) .withChargeId(extChargeId1) .getCharge() .statusCode(OK.getStatusCode()) .contentType(JSON) .body(JSON_CHARGE_KEY, is(extChargeId1)) .body(JSON_STATE_KEY, is(EXPIRED.toExternal().getStatus())); connectorRestApiClient .withAccountId(accountId) .withChargeId(extChargeId2) .getCharge() .statusCode(OK.getStatusCode()) .contentType(JSON) .body(JSON_CHARGE_KEY, is(extChargeId2)) .body(JSON_STATE_KEY, is(AWAITING_CAPTURE_REQUEST.toExternal().getStatus())); List<String> events1 = databaseTestHelper.getInternalEvents(extChargeId1); List<String> events2 = databaseTestHelper.getInternalEvents(extChargeId2); assertTrue(isEqualCollection(events1, asList(CREATED.getValue(), EXPIRED.getValue()))); assertTrue(isEqualCollection(events2, asList(AWAITING_CAPTURE_REQUEST.getValue()))); }</code><technical_language>role this charge is playing in test</technical_language>

Target:
public void shouldNotExpireChargesWhenAwaitingCaptureDelayIsLessThan48Hours() { String chargeToBeExpiredCreatedStatus = addCharge(CREATED, "ref", ZonedDateTime.now().minusMinutes(90), RandomIdGenerator.newId()); String chargeToBeExpiredAwaitingCaptureRequest = addCharge(AWAITING_CAPTURE_REQUEST, "ref", ZonedDateTime.now().minusHours(48L).plusMinutes(1L), RandomIdGenerator.newId()); worldpayMockClient.mockCancelSuccess(); connectorRestApiClient .postChargeExpiryTask() .statusCode(OK.getStatusCode()) .contentType(JSON) .body("expiry-success", is(1)) .body("expiry-failed", is(0)); connectorRestApiClient .withAccountId(accountId) .withChargeId(chargeToBeExpiredCreatedStatus) .getCharge() .statusCode(OK.getStatusCode()) .contentType(JSON) .body(JSON_CHARGE_KEY, is(chargeToBeExpiredCreatedStatus)) .body(JSON_STATE_KEY, is(EXPIRED.toExternal().getStatus())); connectorRestApiClient .withAccountId(accountId) .withChargeId(chargeToBeExpiredAwaitingCaptureRequest) .getCharge() .statusCode(OK.getStatusCode()) .contentType(JSON) .body(JSON_CHARGE_KEY, is(chargeToBeExpiredAwaitingCaptureRequest)) .body(JSON_STATE_KEY, is(AWAITING_CAPTURE_REQUEST.toExternal().getStatus())); List<String> events1 = databaseTestHelper.getInternalEvents(chargeToBeExpiredCreatedStatus); List<String> events2 = databaseTestHelper.getInternalEvents(chargeToBeExpiredAwaitingCaptureRequest); assertTrue(isEqualCollection(events1, asList(CREATED.getValue(), EXPIRED.getValue()))); assertTrue(isEqualCollection(events2, asList(AWAITING_CAPTURE_REQUEST.getValue()))); }
Source:
<code>public void updateSource(TaskSource sourceUpdate) { checkLockNotHeld("Can not update sources while holding the driver lock"); <START> checkArgument(sourceOperator.isPresent() && sourceOperator.get().getSourceId().equals(sourceUpdate.getPlanNodeId())); <END> pendingTaskSourceUpdates.updateAndGet(current -> current == null ? sourceUpdate : current.update(sourceUpdate)); tryWithLock(() -> TRUE); }</code><technical_language>Add a message checkArgument call</technical_language>

Target:
public void updateSource(TaskSource sourceUpdate) { checkState(initialized.get(), "Driver is not initialized"); checkLockNotHeld("Can not update sources while holding the driver lock"); checkArgument( sourceOperator.isPresent() && sourceOperator.get().getSourceId().equals(sourceUpdate.getPlanNodeId()), "sourceUpdate is for a plan node that is different from this Driver's source node"); pendingTaskSourceUpdates.updateAndGet(current -> current == null ? sourceUpdate : current.update(sourceUpdate)); tryWithLock(() -> TRUE); }
Source:
<code>protected int persistHydrant( FireHydrant indexToPersist, DataSchema schema, Interval interval, Map<String, Object> metadataElems ) { synchronized (indexToPersist) { if (indexToPersist.hasSwapped()) { log.info( "DataSource[%s], Interval[%s], Hydrant[%s] already swapped. Ignoring request to persist.", schema.getDataSource(), interval, indexToPersist ); return 0; } log.info( "DataSource[%s], Interval[%s], Metadata [%s] persisting Hydrant[%s]", schema.getDataSource(), interval, metadataElems, indexToPersist ); try { int numRows = indexToPersist.getIndex().size(); <START> final IndexSpec indexSpec = config.getIndexSpec(); <END> indexToPersist.getIndex().getMetadata().putAll(metadataElems); final File persistedFile = indexMerger.persist( indexToPersist.getIndex(), interval, new File(computePersistDir(schema, interval), String.valueOf(indexToPersist.getCount())), indexSpec, config.getSegmentWriteOutMediumFactory() ); indexToPersist.swapSegment( new QueryableIndexSegment(indexIO.loadIndex(persistedFile), indexToPersist.getSegmentId()) ); return numRows; } catch (IOException e) { log.makeAlert("dataSource[%s] -- incremental persist failed", schema.getDataSource()) .addData("interval", interval) .addData("count", indexToPersist.getCount()) .emit(); throw new RuntimeException(e); } } }</code><technical_language>Change belong this PR</technical_language>

Target:
protected int persistHydrant( FireHydrant indexToPersist, DataSchema schema, Interval interval, Map<String, Object> metadataElems ) { synchronized (indexToPersist) { if (indexToPersist.hasSwapped()) { log.info( "DataSource[%s], Interval[%s], Hydrant[%s] already swapped. Ignoring request to persist.", schema.getDataSource(), interval, indexToPersist ); return 0; } log.info( "DataSource[%s], Interval[%s], Metadata [%s] persisting Hydrant[%s]", schema.getDataSource(), interval, metadataElems, indexToPersist ); try { int numRows = indexToPersist.getIndex().size(); indexToPersist.getIndex().getMetadata().putAll(metadataElems); final File persistedFile = indexMerger.persist( indexToPersist.getIndex(), interval, new File(computePersistDir(schema, interval), String.valueOf(indexToPersist.getCount())), config.getIndexSpecForIntermediatePersists(), config.getSegmentWriteOutMediumFactory() ); indexToPersist.swapSegment( new QueryableIndexSegment(indexIO.loadIndex(persistedFile), indexToPersist.getSegmentId()) ); return numRows; } catch (IOException e) { log.makeAlert("dataSource[%s] -- incremental persist failed", schema.getDataSource()) .addData("interval", interval) .addData("count", indexToPersist.getCount()) .emit(); throw new RuntimeException(e); } } }
Source:
<code>private void doBuildProject(File projectLocation, IProgressMonitor monitor) throws CoreException { if (monitor.isCanceled()) { return; } try { monitor.beginTask(Messages.MSBuild_BuildProjectTask, 10); <START> String msBuild = getMSBuildPath(); <END> if (msBuild != null) { File csprojFile = WPProjectUtils.getCsrojFile(projectLocation); Assert.isNotNull(csprojFile); StringBuilder cmdString = new StringBuilder(msBuild); cmdString.append(" "); if (isRelease()) { cmdString.append("/p:Configuration=Release "); } cmdString.append(csprojFile.getAbsolutePath()); ExternalProcessUtility processUtility = new ExternalProcessUtility(); if (monitor.isCanceled()) { return; } monitor.worked(1); TextDetectingStreamListener listener = new TextDetectingStreamListener( "Build succeeded."); processUtility.execSync(cmdString.toString(), projectLocation, listener, listener, monitor, null, getLaunchConfiguration()); if (!listener.isTextDetected()) { throw new CoreException(new Status(IStatus.ERROR, WPCore.PLUGIN_ID, Messages.MSBuild_MSBuildError)); } } } finally { monitor.done(); } }</code><technical_language>Needs quotes msbuild command</technical_language>

Target:
private void doBuildProject(File projectLocation, IProgressMonitor monitor) throws CoreException { if (monitor.isCanceled()) { return; } try { monitor.beginTask(Messages.MSBuild_BuildProjectTask, 10); String msBuild = getMSBuildPath(); if (msBuild != null) { File csprojFile = WPProjectUtils.getCsrojFile(projectLocation); Assert.isNotNull(csprojFile); StringBuilder cmdString = new StringBuilder(addQuotes(msBuild)); cmdString.append(" "); if (isRelease()) { cmdString.append("/p:Configuration=Release "); } cmdString.append(addQuotes(csprojFile.getAbsolutePath())); ExternalProcessUtility processUtility = new ExternalProcessUtility(); if (monitor.isCanceled()) { return; } monitor.worked(1); TextDetectingStreamListener listener = new TextDetectingStreamListener( "Build succeeded."); processUtility.execSync(cmdString.toString(), projectLocation, listener, listener, monitor, null, getLaunchConfiguration()); if (!listener.isTextDetected()) { throw new CoreException(new Status(IStatus.ERROR, WPCore.PLUGIN_ID, Messages.MSBuild_MSBuildError)); } } } finally { monitor.done(); } }
Source:
<code>private void initializeServices() { <START> logger().debug("Initializing couchbase services on host: " + enabledServices); <END> final String services = enabledServices.stream().map(s -> { switch (s) { case KV: return "kv"; case QUERY: return "n1ql"; case INDEX: return "index"; case SEARCH: return "fts"; default: throw new IllegalStateException("Unknown service!"); } }).collect(Collectors.joining(",")); Response response = doHttpRequest(MGMT_PORT, "/node/controller/setupServices", "POST", new FormBody.Builder() .add("services", services) .build(), false ); checkSuccessfulResponse(response, "Could not enable couchbase services"); }</code><technical_language>suggestion logger().debug("Initializing couchbase services host: {}", enabledServices);</technical_language>

Target:
private void initializeServices() { logger().debug("Initializing couchbase services on host: {}", enabledServices); final String services = enabledServices.stream().map(s -> { switch (s) { case KV: return "kv"; case QUERY: return "n1ql"; case INDEX: return "index"; case SEARCH: return "fts"; default: throw new IllegalStateException("Unknown service!"); } }).collect(Collectors.joining(",")); Response response = doHttpRequest(MGMT_PORT, "/node/controller/setupServices", "POST", new FormBody.Builder() .add("services", services) .build(), false ); checkSuccessfulResponse(response, "Could not enable couchbase services"); }
Source:
<code>public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { Optional<Object> customHttpHeadersObject = context.getData(AZURE_REQUEST_HTTP_HEADERS_KEY); <START> if (customHttpHeadersObject.isPresent() && customHttpHeadersObject.get() instanceof HttpHeaders) { HttpHeaders customHttpHeaders = (HttpHeaders) customHttpHeadersObject.get(); <END> for (HttpHeader httpHeader : customHttpHeaders) { if (!Objects.isNull(httpHeader.getName()) && !Objects.isNull(httpHeader.getValue())) { context.getHttpRequest().getHeaders().put(httpHeader.getName(), httpHeader.getValue()); } } } return next.process(); }</code><technical_language>This replaced java context.getData(AZURE_REQUEST_HTTP_HEADERS_KEY).ifPresent(headers -> { // for loop headers });</technical_language>

Target:
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { context.getData(AZURE_REQUEST_HTTP_HEADERS_KEY).ifPresent(headers -> { if (headers instanceof HttpHeaders) { HttpHeaders customHttpHeaders = (HttpHeaders) headers; for (HttpHeader httpHeader : customHttpHeaders) { if (!Objects.isNull(httpHeader.getName()) && !Objects.isNull(httpHeader.getValue())) { context.getHttpRequest().getHeaders().put(httpHeader.getName(), httpHeader.getValue()); } } } }); return next.process(); }
Source:
<code>public FreeStyleProject newInstance(Branch branch) { FreeStyleProject job = new FreeStyleProject(getOwner(), branch.getEncodedName()); setBranch(job, branch); try { <START> job.setQuietPeriod(0); <END> } catch(IOException e) { e.printStackTrace(); } return job; }</code><technical_language>For test stability maintain previous quiet period of 0. live behavior change</technical_language>

Target:
public FreeStyleProject newInstance(Branch branch) { FreeStyleProject job = new FreeStyleProject(getOwner(), branch.getEncodedName()); setBranch(job, branch); if (quietPeriodSeconds >= 0) { try { job.setQuietPeriod(quietPeriodSeconds); } catch(IOException e) { e.printStackTrace(); } } return job; }
Source:
<code>public void init(final GlusterVolumeGeoRepCreateModel model) { super.init(model); model.getPropertyChangedEvent().addListener(new IEventListener<PropertyChangedEventArgs>() { @Override public void eventRaised(Event<? extends PropertyChangedEventArgs> ev, Object sender, PropertyChangedEventArgs args) { if(args.propertyName.equalsIgnoreCase("RecommendationViolations")) { getView().setSuggestedConfigViolations(model.getRecommendationViolations()); } else if (args.propertyName.equalsIgnoreCase("QueryFailed")) { getView().setFailureMessage(model.getQueryFailureMessage()); } } }); <START> model.getSlaveUserName().getEntityChangedEvent().addListener(new IEventListener<EventArgs>() { @Override public void eventRaised(Event<? extends EventArgs> ev, Object sender, EventArgs args) { String slaveUser = model.getSlaveUserName() .getEntity(); getView().setUserGroupVisibility(slaveUser != null && !slaveUser .equalsIgnoreCase(ConstantsManager.getInstance().getConstants().rootUser())); } }); <END> }</code><technical_language>do this in model userGroup is represented in model. getSlaveUserGroupName().setIsChangeable() ui-editor enable disable</technical_language>

Target:
public void init(final GlusterVolumeGeoRepCreateModel model) { super.init(model); model.getPropertyChangedEvent().addListener(new IEventListener<PropertyChangedEventArgs>() { @Override public void eventRaised(Event<? extends PropertyChangedEventArgs> ev, Object sender, PropertyChangedEventArgs args) { if(args.propertyName.equalsIgnoreCase("RecommendationViolations")) { getView().setSuggestedConfigViolations(model.getRecommendationViolations()); } else if (args.propertyName.equalsIgnoreCase("QueryFailed")) { getView().setFailureMessage(model.getQueryFailureMessage()); } } }); }
Source:
<code>public Scheduler cleanupResponseUrlDataScheduler() throws SchedulerException { <START> return this.constructScheduler(ResponseDataCleanupJob.class, KEY_CLEANUP_JOB_THREAD_COUNT, <END> KEY_CLEANUP_JOB_CRON_EXPRESSION, this.getDatabaseUrl(), this.databaseUsername, this.databasePassword, this.databaseDriver); }</code><technical_language>guess is ResponseUrlDataCleanupJob.class in stead of ResponseDataCleanupJob.class</technical_language>

Target:
public Scheduler cleanupResponseUrlDataScheduler() throws SchedulerException { return this.constructScheduler(ResponseUrlDataCleanupJob.class, KEY_CLEANUP_JOB_THREAD_COUNT, KEY_CLEANUP_JOB_CRON_EXPRESSION, this.getDatabaseUrl(), this.databaseUsername, this.databasePassword, this.databaseDriver); }
Source:
<code>public void generateType(final Ds3Type typeEntry) throws IOException { final Template typeTemplate = config.getTemplate("TypeEnumConstant.tmplt"); final Type type = TypeConverter.toType(typeEntry); final Path outputPath = getTypeOutputPath(type); final OutputStream outStream = fileUtils.getOutputFile(outputPath); final Writer writer = new OutputStreamWriter(outStream); try { typeTemplate.process(type, writer); } catch (final NullPointerException e) { LOG.error("Encountered NullPointerException while processing template " + typeTemplate.getName(), e); <START> e.printStackTrace(); <END> } catch (final TemplateException e) { LOG.error("Encountered TemplateException while processing template " + typeTemplate.getName(), e); e.printStackTrace(); } }</code><technical_language>appending exception in logging statement, do print stack trace. This result in stack printing twice, depending logger is configured</technical_language>

Target:
public void generateType(final Ds3Type typeEntry) throws IOException { final Template typeTemplate = config.getTemplate("TypeEnumConstant.tmplt"); final Type type = TypeConverter.toType(typeEntry); final Path outputPath = getTypeOutputPath(type); final OutputStream outStream = fileUtils.getOutputFile(outputPath); final Writer writer = new OutputStreamWriter(outStream); try { typeTemplate.process(type, writer); } catch (final NullPointerException e) { LOG.error("Encountered NullPointerException while processing template " + typeTemplate.getName(), e); } catch (final TemplateException e) { LOG.error("Encountered TemplateException while processing template " + typeTemplate.getName(), e); } }
Source:
<code>private Map<Long, ISegmentAspect> getAspectsFromColumnsId(List<Long> desiredColumns) { Map<Long, ISegmentAspect> aspects = new LinkedHashMap<>(); if <START> (!desiredColumns.isEmpty()) <END> { for (Long columnsId : desiredColumns) { ISegmentAspect segmentAspect = fAspectMap.get(columnsId); if (segmentAspect != null) { aspects.put(columnsId, segmentAspect); } } return aspects; } return fAspectMap; }</code><technical_language>return instantiating map</technical_language>

Target:
private Map<Long, ISegmentAspect> getAspectsFromColumnsId(List<Long> desiredColumns) { if (!desiredColumns.isEmpty()) { Map<Long, ISegmentAspect> aspects = new LinkedHashMap<>(); for (Long columnsId : desiredColumns) { ISegmentAspect segmentAspect = fAspectMap.get(columnsId); if (segmentAspect != null) { aspects.put(columnsId, segmentAspect); } } return aspects; } return fAspectMap; }
Source:
<code>public String toString() { <START> return "KubernetesCloud '" + name + "' serverUrl :" + serverUrl; <END> }</code><technical_language>more of a personal taste question, Guava MoreObjects</technical_language>

Target:
public String toString() { return MoreObjects.toStringHelper(this).add("name", name).add("serverUrl", serverUrl).toString(); }
Source:
<code>public int getOptimalTileWidth() { FormatTools.assertId(currentId, true, 1); RandomAccessInputStream plane = getPlane(getSeries(), 0); if (plane == null) return super.getOptimalTileWidth(); try { TiffParser tp = new TiffParser(plane); IFD ifd = tp.getFirstIFD(); return (int) ifd.getTileWidth(); } catch (FormatException e) { LOGGER.debug("Could not retrieve tile width", e); } catch (IOException e) { LOGGER.debug("Could not retrieve tile width", e); <START> } finally { <END> try { plane.close(); } catch (IOException e2) { LOGGER.debug("Could not close stream", e2); } } return super.getOptimalTileWidth(); }</code><technical_language>RAIS plane2 = plane here, e.g.: import java.io.Closeable; class C implements Closeable { public void close() { System.out.println("closed"); } } public class M { public static void main(String[] args) { C c = new C(); try (C c2 = c) { System.out.println("done"); } } }</technical_language>

Target:
public int getOptimalTileWidth() { FormatTools.assertId(currentId, true, 1); RandomAccessInputStream plane = getPlane(getSeries(), 0); if (plane == null) return super.getOptimalTileWidth(); try (RandomAccessInputStream p = plane) { TiffParser tp = new TiffParser(plane); IFD ifd = tp.getFirstIFD(); return (int) ifd.getTileWidth(); } catch (FormatException e) { LOGGER.debug("Could not retrieve tile width", e); } catch (IOException e) { LOGGER.debug("Could not retrieve tile width", e); } return super.getOptimalTileWidth(); }
Source:
<code>public void createOrLoadKey() { String keyLocation = env.getProperty("keyLocation"); if (rsaJsonWebKey == null) { try { loadSavedKey(keyLocation); } catch (ClassNotFoundException | IOException e1) { logger.error("Key not found or error loading key. Creating new key. ", e1); try { RsaKeyUtil keyUtil = new RsaKeyUtil(); KeyPair keyPair; <START> keyPair = keyUtil.generateKeyPair(2048); <END> rsaJsonWebKey = (RsaJsonWebKey) PublicJsonWebKey.Factory.newPublicJwk(keyPair.getPublic()); rsaJsonWebKey.setPrivateKey(keyPair.getPrivate()); saveKey(keyLocation); } catch (JoseException e) { logger.error("Error creating key: ", e1); throw new RuntimeException(e); } } } }</code><technical_language>2048 a magic number</technical_language>

Target:
public void createOrLoadKey() { String keyLocation = env.getProperty("keyLocation"); if (rsaJsonWebKey == null) { try { loadSavedKey(keyLocation); } catch (ClassNotFoundException | IOException e1) { logger.error("Key not found or error loading key. Creating new key. ", e1); try { RsaKeyUtil keyUtil = new RsaKeyUtil(); KeyPair keyPair; keyPair = keyUtil.generateKeyPair(KEY_BIT_LENGTH); rsaJsonWebKey = (RsaJsonWebKey) PublicJsonWebKey.Factory.newPublicJwk(keyPair.getPublic()); rsaJsonWebKey.setPrivateKey(keyPair.getPrivate()); saveKey(keyLocation); } catch (JoseException e) { logger.error("Error creating key: ", e); throw new RuntimeException(e); } } } }
Source:
<code>public synchronized void onJobArrival(final JobEntity jobEntity) { final int numResourcesToUse = jobEntity.getNumWorkers() + jobEntity.getNumServers(); <START> if (numAvailableResources >= numResourcesToUse) { <END> LOG.log(Level.INFO, "Start job {0} with {1} resources. Remaining free resources: {2}", new Object[]{jobEntity.getJobId(), numAvailableResources, numAvailableResources - numResourcesToUse}); numAvailableResources -= numResourcesToUse; jobServerDriverFuture.get().executeJob(jobEntity); } else { LOG.log(Level.INFO, "Put job {0} into queue", jobEntity.getJobId()); jobWaitingQueue.add(jobEntity); } }</code><technical_language>this code block (if in L54-L59) encapsulated a method avoid duplicate in onJobFinished(), boolean tryExecute() returns job execution successful</technical_language>

Target:
public synchronized boolean onJobArrival(final JobEntity jobEntity) { if (numTotalResources < jobEntity.getNumServers() + jobEntity.getNumWorkers()) { return false; } if (!tryExecute(jobEntity)) { LOG.log(Level.INFO, "Put job {0} into queue", jobEntity.getJobId()); jobWaitingQueue.add(jobEntity); } return true; }
Source:
<code>AuthenticatingHttpConnector(final String user, final Optional<AgentProxy> agentProxyOpt, final Optional<Path> clientCertificatePath, final Optional<Path> clientKeyPath, final EndpointIterator endpointIterator, final DefaultHttpConnector delegate, final List<Identity> identities) { <START> if (clientCertificatePath.isPresent() ^ clientKeyPath.isPresent()) { <END> throw new IllegalArgumentException( "both or neither of clientCertificatePath and clientKeyPath must be specified"); } this.user = user; this.agentProxy = agentProxyOpt; this.clientCertificatePath = clientCertificatePath; this.clientKeyPath = clientKeyPath; this.endpointIterator = endpointIterator; this.delegate = delegate; this.identities = identities; }</code><technical_language>u fancy</technical_language>

Target:
AuthenticatingHttpConnector(final String user, final Optional<AgentProxy> agentProxyOpt, final Optional<Path> clientCertificatePath, final Optional<Path> clientKeyPath, final EndpointIterator endpointIterator, final DefaultHttpConnector delegate, final List<Identity> identities) { if (clientCertificatePath.isPresent() != clientKeyPath.isPresent()) { throw new IllegalArgumentException( "both or neither of clientCertificatePath and clientKeyPath must be specified"); } this.user = user; this.agentProxy = agentProxyOpt; this.clientCertificatePath = clientCertificatePath; this.clientKeyPath = clientKeyPath; this.endpointIterator = endpointIterator; this.delegate = delegate; this.identities = identities; }
Source:
<code>public Set<List<JavaFileScannerContext.Location>> flow(List<Integer> parameterIndices, List<Class<? extends Constraint>> domains) { Preconditions.checkArgument(!parameterIndices.isEmpty(), "computing flow on empty symbolic value list should never happen"); if(node == null || behavior == null) { return Collections.emptySet(); } <START> String key = parameterIndices.stream().sorted().map(Object::toString).reduce("", String::concat); <END> String domainKey = domains.stream().map(Class::getName).sorted().reduce("", String::concat); Map<String, Set<List<JavaFileScannerContext.Location>>> flowByDomain = cachedFlows.computeIfAbsent(key, k -> new HashMap<>()); return flowByDomain.computeIfAbsent(domainKey, k -> FlowComputation.flow(node, getSymbolicValues(parameterIndices), c -> true, c -> false, domains, node.programState.getLastEvaluated())); }</code><technical_language>generating key this unique: I it, if call method [1,2], end key ("12") asking for 12th parameter list [12]. (I this is pretty unlikely, still...)</technical_language>

Target:
public Set<List<JavaFileScannerContext.Location>> flow(List<Integer> parameterIndices, List<Class<? extends Constraint>> domains) { Preconditions.checkArgument(!parameterIndices.isEmpty(), "computing flow on empty symbolic value list should never happen"); if(node == null || behavior == null) { return Collections.emptySet(); } String key = parameterIndices.stream().sorted().map(Object::toString).collect(Collectors.joining(",")); String domainKey = domains.stream().map(Class::getName).sorted().reduce("", String::concat); Map<String, Set<List<JavaFileScannerContext.Location>>> flowByDomain = cachedFlows.computeIfAbsent(key, k -> new HashMap<>()); return flowByDomain.computeIfAbsent(domainKey, k -> FlowComputation.flow(node, getSymbolicValues(parameterIndices), c -> true, c -> false, domains, node.programState.getLastEvaluated())); }
Source:
<code>public synchronized void handleMessageLayoutPrepare( @NonNull CorfuPayloadMsg<LayoutPrepareRequest> msg, ChannelHandlerContext ctx, @NonNull IServerRouter r) { if (!isBootstrapped(msg, ctx, r)) { return; } final long msgEpoch = msg.getPayload().getEpoch(); final long serverEpoch = getServerEpoch(); final Rank prepareRank = new Rank(msg.getPayload().getRank(), msg.getClientID()); final Rank phase1Rank = getPhase1Rank(msgEpoch); <START> if (msgEpoch != serverEpoch) { <END> r.sendResponse(ctx, msg, new CorfuPayloadMsg<>(CorfuMsgType.WRONG_EPOCH, serverEpoch)); log.trace("handleMessageLayoutPrepare: Incoming message with wrong epoch, got {}, " + "expected {}, message was: {}", msg.getPayload().getEpoch(), serverEpoch, msg); return; } Layout proposedLayout = getProposedLayout(msgEpoch); if (phase1Rank != null && prepareRank.lessThanEqualTo(phase1Rank)) { log.debug("handleMessageLayoutPrepare: Rejected phase 1 prepare of rank={}, " + "phase1Rank={}", prepareRank, phase1Rank); r.sendResponse(ctx, msg, CorfuMsgType.LAYOUT_PREPARE_REJECT.payloadMsg(new LayoutPrepareResponse(phase1Rank.getRank(), proposedLayout))); } else { Rank highestProposedRank = proposedLayout == null ? new Rank(-1L, msg.getClientID()) : getPhase2Rank(msgEpoch); setPhase1Rank(prepareRank, msgEpoch); log.debug("handleMessageLayoutPrepare: New phase 1 rank={}", getPhase1Rank(msgEpoch)); r.sendResponse(ctx, msg, CorfuMsgType.LAYOUT_PREPARE_ACK.payloadMsg(new LayoutPrepareResponse(highestProposedRank.getRank(), proposedLayout))); } }</code><technical_language>checks necessary ? this condition is false, time of check, true immediately evaluation</technical_language>

Target:
public synchronized void handleMessageLayoutPrepare( @NonNull CorfuPayloadMsg<LayoutPrepareRequest> msg, ChannelHandlerContext ctx, @NonNull IServerRouter r) { if (!isBootstrapped(msg, ctx, r)) { return; } final long payloadEpoch = msg.getPayload().getEpoch(); final long serverEpoch = getServerEpoch(); final Rank prepareRank = new Rank(msg.getPayload().getRank(), msg.getClientID()); final Rank phase1Rank = getPhase1Rank(payloadEpoch); if (payloadEpoch != serverEpoch) { r.sendResponse(ctx, msg, new CorfuPayloadMsg<>(CorfuMsgType.WRONG_EPOCH, serverEpoch)); log.trace("handleMessageLayoutPrepare: Incoming message with wrong epoch, got {}, " + "expected {}, message was: {}", msg.getPayload().getEpoch(), serverEpoch, msg); return; } Layout proposedLayout = getProposedLayout(payloadEpoch); if (phase1Rank != null && prepareRank.lessThanEqualTo(phase1Rank)) { log.debug("handleMessageLayoutPrepare: Rejected phase 1 prepare of rank={}, " + "phase1Rank={}", prepareRank, phase1Rank); r.sendResponse(ctx, msg, CorfuMsgType.LAYOUT_PREPARE_REJECT.payloadMsg(new LayoutPrepareResponse(phase1Rank.getRank(), proposedLayout))); } else { Rank highestProposedRank = proposedLayout == null ? new Rank(-1L, msg.getClientID()) : getPhase2Rank(payloadEpoch); setPhase1Rank(prepareRank, payloadEpoch); log.debug("handleMessageLayoutPrepare: New phase 1 rank={}", prepareRank); r.sendResponse(ctx, msg, CorfuMsgType.LAYOUT_PREPARE_ACK.payloadMsg(new LayoutPrepareResponse(highestProposedRank.getRank(), proposedLayout))); } }
Source:
<code><START> public void setSpeed(Double degreesPerSecond) { <END> if (maxSpeed != -1 && degreesPerSecond > maxSpeed) { speed = maxSpeed; log.info("Trying to set speed to a value greater than max speed"); } this.speed = degreesPerSecond; for (String controller : controllers) { ServiceInterface si = Runtime.getService(controller); if (si.isLocal()) { ((ServoController) Runtime.getService(controller)).servoSetVelocity(this); } else { send(controller, "servoSetVelocity", this); } } broadcastState(); }</code><technical_language>I need maintain compatibility for skewl setSpeed . new proper method is setVelocity takes a double specifies angular velocity of servo try achieve</technical_language>

Target:
public void setSpeed(Double degreesPerSecond) { if (degreesPerSecond == null) { log.info("disabling speed control"); speed = null; } if (maxSpeed != -1 && degreesPerSecond != null && degreesPerSecond > maxSpeed) { speed = maxSpeed; log.info("Trying to set speed to a value greater than max speed"); } this.speed = degreesPerSecond; for (String controller : controllers) { send(controller, "servoSetVelocity", this); } broadcastState(); }
Source:
<code>private String getMemberName(String topic) { String[] topicElements = getTopicElements(topic); <START> if (topicElements.length != 5) <END> throw new IllegalArgumentException("Event creation failed, invalid topic: " + topic); return topicElements[5]; }</code><technical_language>a check for "lower then" sufficient</technical_language>

Target:
private String getMemberName(String topic) { String[] topicElements = getTopicElements(topic); if (topicElements.length < 5) throw new IllegalArgumentException("Event creation failed, invalid topic: " + topic); return topicElements[3]; }
Source:
<code><START> private int countOccurrencesInTopology(final String topologyString, <END> final String searchPattern) { final Matcher matcher = Pattern.compile(searchPattern).matcher(topologyString); final List<String> repartitionTopicsFound = new ArrayList<>(); while (matcher.find()) { repartitionTopicsFound.add(matcher.group()); } return repartitionTopicsFound.size(); }</code><technical_language>likewise, this static</technical_language>

Target:
private static int countOccurrencesInTopology(final String topologyString, final String searchPattern) { final Matcher matcher = Pattern.compile(searchPattern).matcher(topologyString); final List<String> repartitionTopicsFound = new ArrayList<>(); while (matcher.find()) { repartitionTopicsFound.add(matcher.group()); } return repartitionTopicsFound.size(); }
Source:
<code>public void run() { <START> if (StringUtils.isNotBlank(id)) { <END> boolean hasParent; if (vocabularyAndHasParent.get(name) == null) { String dirSchema = directoryService.getDirectorySchema(name); Schema schema = schemaManager.getSchema(dirSchema); hasParent = schema.hasField("parent"); vocabularyAndHasParent.put(name, hasParent); } else { hasParent = vocabularyAndHasParent.get(name); } Session directorySession = directoryService.open(name); if (!directorySession.hasEntry(id)) { Map<String, Object> entry = new HashMap<>(); entry.put("id", id); if (StringUtils.isEmpty(label)) { label = id; } entry.put("label", label); if (hasParent) { entry.put("parent", parent); } entry.put("obsolete", obsolete); entry.put("ordering", ordering); directorySession.createEntry(entry); } directorySession.close(); } }</code><technical_language>do if (StringUtils.isBlank(id)) { return; } reduce nesting level</technical_language>

Target:
public void run() { if (StringUtils.isBlank(id)) { return; } try(Session directorySession = directoryService.open(name)) { if (directorySession.hasEntry(id)) { return; } Map<String, Object> entry = new HashMap<>(); entry.put("id", id); entry.put("label", defaultIfEmpty(label, id)); String dirSchema = directoryService.getDirectorySchema(name); Schema schema = schemaManager.getSchema(dirSchema); if (schema.hasField("parent")) { entry.put("parent", parent); } entry.put("obsolete", obsolete); entry.put("ordering", ordering); directorySession.createEntry(entry); } }
Source:
<code>private EntitySpec<? extends Entity> build(Topology topology, String node, Set<String> visited) { final Map<String, NodeTemplate> nodeTemplates = topology.getNodeTemplates(); final NodeTemplate nodeTemplate = nodeTemplates.get(node); visited.add(node); EntitySpec<?> spec = createSpec(node, nodeTemplate, topology); <START> LOG.info("applying spec modifiers {}", specModifiers); <END> for (EntitySpecModifier builder : specModifiers) { builder.apply(spec, nodeTemplate, topology); } for (String child : children.get(node)) { if (!visited.contains(child)) { final EntitySpec<? extends Entity> childSpec = build(topology, child, visited); spec.child(childSpec) .configure(SoftwareProcess.CHILDREN_STARTABLE_MODE, SoftwareProcess.ChildStartableMode.BACKGROUND_LATE); } } return spec; }</code><technical_language>This is debug best, trace, include spec/nodeTemplate in question. tweak subsequently</technical_language>

Target:
private EntitySpec<? extends Entity> build(Topology topology, String node, Set<String> visited) { final Map<String, NodeTemplate> nodeTemplates = topology.getNodeTemplates(); final NodeTemplate nodeTemplate = nodeTemplates.get(node); visited.add(node); EntitySpec<?> spec = createSpec(node, nodeTemplate, topology); LOG.trace("applying spec modifiers to spec {}", specModifiers, spec); for (EntitySpecModifier builder : specModifiers) { builder.apply(spec, nodeTemplate, topology); } for (String child : children.get(node)) { if (!visited.contains(child)) { final EntitySpec<? extends Entity> childSpec = build(topology, child, visited); spec.child(childSpec) .configure(SoftwareProcess.CHILDREN_STARTABLE_MODE, SoftwareProcess.ChildStartableMode.BACKGROUND_LATE); } } return spec; }
Source:
<code>public static ReviewCompareAnnotationSupport getAnnotationSupport(Viewer contentViewer) { ReviewCompareAnnotationSupport support = (ReviewCompareAnnotationSupport) contentViewer.getData(KEY_ANNOTAION_SUPPORT); if (support == null) { <START> if (support == null) { <END> support = new ReviewCompareAnnotationSupport(contentViewer); contentViewer.setData(KEY_ANNOTAION_SUPPORT, support); } } return support; }</code><technical_language>Making *really* null? ;)</technical_language>

Target:
public static ReviewCompareAnnotationSupport getAnnotationSupport(Viewer contentViewer) { ReviewCompareAnnotationSupport support = (ReviewCompareAnnotationSupport) contentViewer.getData(KEY_ANNOTAION_SUPPORT); if (support == null) { support = new ReviewCompareAnnotationSupport(contentViewer); contentViewer.setData(KEY_ANNOTAION_SUPPORT, support); } return support; }
Source:
<code>private static Type getComponentOrElementType(Type arrayOrListType, ClientLogger logger) { if (arrayOrListType.getClass().isArray()) { return arrayOrListType.getClass().getComponentType(); } if (isList(arrayOrListType)) { ParameterizedType pt = (ParameterizedType) arrayOrListType; return pt.getActualTypeArguments()[0]; } <START> throw logger.logExceptionAsError(new RuntimeException("Should not be there")); <END> }</code><technical_language>add actual exception message if run this issue in production</technical_language>

Target:
private static Type getComponentOrElementType(Type arrayOrListType, ClientLogger logger) { if (arrayOrListType.getClass().isArray()) { return arrayOrListType.getClass().getComponentType(); } if (isList(arrayOrListType)) { ParameterizedType pt = (ParameterizedType) arrayOrListType; return pt.getActualTypeArguments()[0]; } throw logger.logExceptionAsError(new RuntimeException(String.format( "Collection type %s is not supported.", arrayOrListType.getTypeName()))); }
Source:
<code>private ThriftType convertEnumTypeField(Class enumClass, String fieldName){ List<ThriftType.EnumValue> enumValues = new ArrayList<ThriftType.EnumValue>(); String enumName = enumClass.getName(); try { List enumCollection = getEnumList(enumName); for (Object enumObj : enumCollection) { ScroogeEnumDesc enumDesc = ScroogeEnumDesc.fromEnum(enumObj); enumValues.add(new ThriftType.EnumValue(enumDesc.id, enumDesc.originalName)); } return new ThriftType.EnumType(enumValues); <START> } catch (Exception e) { <END> throw new ScroogeSchemaConversionException("Can not convert enum field " + fieldName, e); } }</code><technical_language>Exceptions other RuntimeExceptions</technical_language>

Target:
private ThriftType convertEnumTypeField(Class enumClass, String fieldName) { List<ThriftType.EnumValue> enumValues = new ArrayList<ThriftType.EnumValue>(); String enumName = enumClass.getName(); try { List enumCollection = getEnumList(enumName); for (Object enumObj : enumCollection) { ScroogeEnumDesc enumDesc = ScroogeEnumDesc.fromEnum(enumObj); enumValues.add(new ThriftType.EnumValue(enumDesc.id, enumDesc.originalName)); } return new ThriftType.EnumType(enumValues); } catch (ReflectiveOperationException e) { throw new ScroogeSchemaConversionException("Can not convert enum field " + fieldName, e); } catch (RuntimeException e) { throw new ScroogeSchemaConversionException("Can not convert enum field " + fieldName, e); } }
Source:
<code><START> public static Map<String, DbmsType> all() { <END> Map<String, DbmsType> types = new HashMap<>(); types.put("ARRAY", ARRAY); types.put("BIGINT", BIGINT); types.put("BINARY", BINARY); types.put("BOOLEAN", BOOLEAN); types.put("CHARACTER", CHARACTER); types.put("DATE", DATE); types.put("DATETIME", DATETIME); types.put("DECIMAL", DECIMAL); types.put("DOUBLE", DOUBLE); types.put("DOUBLE PRECISION", DOUBLE_PRECISION); types.put("FLOAT", FLOAT); types.put("FLOAT4", FLOAT4); types.put("FLOAT8", FLOAT8); types.put("INT", INT); types.put("INTEGER", INTEGER); types.put("NUMBER", NUMBER); types.put("NUMERIC", NUMERIC); types.put("OBJECT", OBJECT); types.put("REAL", REAL); types.put("SMALLINT", SMALLINT); types.put("STRING", STRING); types.put("TEXT", TEXT); types.put("TIME", TIME); types.put("TIMESTAMP", TIMESTAMP); types.put("TIMESTAMP_LTZ", TIMESTAMP_LTZ); types.put("TIMESTAMP_NTZ", TIMESTAMP_NTZ); types.put("TIMESTAMP_TZ", TIMESTAMP_TZ); types.put("VARBINARY", VARBINARY); types.put("VARCHAR", VARCHAR); types.put("VARIANT", VARIANT); return types; }</code><technical_language>generates map everytime call all() method ? this map is in a static{...} bloc code</technical_language>

Target:
public static Map<String, DbmsType> all() { return Collections.unmodifiableMap(allTypes); }
Source:
<code>private void restoreState(Bundle savedInstanceState) { if (savedInstanceState == null) return; boolean isInMultiSelectMode = savedInstanceState.getBoolean(BUNDLE_IN_MULTI_SELECT_MODE); if (isInMultiSelectMode) { mGridAdapter.setInMultiSelect(true); if (savedInstanceState.containsKey(BUNDLE_SELECTED_STATES)) { ArrayList<Integer> selectedItems = ListUtils.fromIntArray(savedInstanceState.getIntArray(BUNDLE_SELECTED_STATES)); mGridAdapter.setSelectedItems(selectedItems); setFilterSpinnerVisible(mGridAdapter.getSelectedItems().size() == 0); mSwipeToRefreshHelper.setEnabled(false); } } <START> mHasRetrievedAllMedia = savedInstanceState.getBoolean(BUNDLE_HAS_RETRIEVED_ALL_MEDIA, false); <END> mFilter = Filter.getFilter(savedInstanceState.getInt(BUNDLE_FILTER)); mEmptyViewMessageType = EmptyViewMessageType.getEnumFromString(savedInstanceState. getString(BUNDLE_EMPTY_VIEW_MESSAGE)); mIsDateFilterSet = savedInstanceState.getBoolean(BUNDLE_DATE_FILTER_SET, false); mStartDay = savedInstanceState.getInt(BUNDLE_DATE_FILTER_START_DAY); mStartMonth = savedInstanceState.getInt(BUNDLE_DATE_FILTER_START_MONTH); mStartYear = savedInstanceState.getInt(BUNDLE_DATE_FILTER_START_YEAR); mEndDay = savedInstanceState.getInt(BUNDLE_DATE_FILTER_END_DAY); mEndMonth = savedInstanceState.getInt(BUNDLE_DATE_FILTER_END_MONTH); mEndYear = savedInstanceState.getInt(BUNDLE_DATE_FILTER_END_YEAR); boolean datePickerShowing = savedInstanceState.getBoolean(BUNDLE_DATE_FILTER_VISIBLE); if (datePickerShowing) showDatePicker(); }</code><technical_language>This leaves ActivityLauncher.newGalleryPost() unused - I clean too</technical_language>

Target:
private void restoreState(Bundle savedInstanceState) { if (savedInstanceState == null) return; boolean isInMultiSelectMode = savedInstanceState.getBoolean(BUNDLE_IN_MULTI_SELECT_MODE); if (isInMultiSelectMode) { mGridAdapter.setInMultiSelect(true); if (savedInstanceState.containsKey(BUNDLE_SELECTED_STATES)) { ArrayList<Integer> selectedItems = ListUtils.fromIntArray(savedInstanceState.getIntArray(BUNDLE_SELECTED_STATES)); mGridAdapter.setSelectedItems(selectedItems); setFilterSpinnerVisible(mGridAdapter.getSelectedItems().size() == 0); mSwipeToRefreshHelper.setEnabled(false); } } mHasRetrievedAllMedia = savedInstanceState.getBoolean(BUNDLE_HAS_RETRIEVED_ALL_MEDIA, false); mFilter = Filter.getFilter(savedInstanceState.getInt(BUNDLE_FILTER)); mEmptyViewMessageType = EmptyViewMessageType.getEnumFromString(savedInstanceState. getString(BUNDLE_EMPTY_VIEW_MESSAGE)); }